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,EAAI,EAAE,EAAE,GACjE,GAAI,EACF,OAAO,EAAY,QAAQ,KAAM,IAAI,CAAC,QAAQ,MAAO,KAAK,CCX9D,IAAM,GAAc,GAAY,OAAM,CACtC,GAAY,MAAQ,UACb,SAAW,GAKlB,GAAoB,GAHlB,mECTF,IAAI,GAASE,GAAyB,CAEpC,YAAa,GACb,cAAe,GACf,cAAe,GACf,uBAAwB,CAAC,2BAA2B,CACpD,sBAAuB,CAAC,kBAAkB,CAC1C,uBAAwB,CAAC,kBAAkB,CAC5C,CAAC,CACFC,GAAY,CACV,IAAK,uEACL,eAAgB,GAChB,iBAAkB,EAClB,yBAA0B,EAC1B,yBAA0B,EAC3B,CAAC,CACaC,GAAkB,CAC1B,eAAe,GAAO,CAC7B,IAAI,GAAOC,IAAkB,CAC7B,GAAK,OAAO,CACZ,GAAK,OAAO,CAER,SAAS,eAAe,WAAW,EAAI,OACzC,GAAe,CACb,GAAI,SAAS,eAAe,WAAW,CAAC,QAAQ,OAChD,SAAU,SAAS,eAAe,WAAW,CAAC,QAAQ,UACvD,CAAC,CACF,GAAkB,OAAQ,CACxB,GAAI,SAAS,eAAe,WAAW,CAAC,QAAQ,OAChD,SAAU,SAAS,eAAe,WAAW,CAAC,QAAQ,UACvD,CAAC,EAIJ,MAAM,QAAQ,MAAQ","names":["handlers","instrumented","addHandler","debug","triggerHandlers","_getBufferMap","DEBUG_BUILD","isErrorEvent","isTransactionEvent","debounce","INTEGRATION_NAME","_shouldDropEvent","WINDOW","_INTERNAL_enhanceErrorWithSentryInfo","getEventTarget","cachedImplementations","setTimeout","debounce$1","Turbo","snakeize","Sentry.replayIntegration","Sentry.init","Sentry.getClient","Sentry.getReplay"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91],"sources":["../../../node_modules/@sentry/core/build/esm/instrument/handlers.js","../../../node_modules/@sentry/core/build/esm/instrument/globalError.js","../../../node_modules/@sentry/core/build/esm/instrument/globalUnhandledRejection.js","../../../node_modules/@sentry/core/build/esm/utils/parseSampleRate.js","../../../node_modules/@sentry/core/build/esm/utils/should-ignore-span.js","../../../node_modules/@sentry/core/build/esm/utils/envelope.js","../../../node_modules/@sentry/core/build/esm/envelope.js","../../../node_modules/@sentry/core/build/esm/api.js","../../../node_modules/@sentry/core/build/esm/integration.js","../../../node_modules/@sentry/core/build/esm/logs/envelope.js","../../../node_modules/@sentry/core/build/esm/logs/internal.js","../../../node_modules/@sentry/core/build/esm/metrics/envelope.js","../../../node_modules/@sentry/core/build/esm/metrics/internal.js","../../../node_modules/@sentry/core/build/esm/utils/promisebuffer.js","../../../node_modules/@sentry/core/build/esm/utils/ratelimit.js","../../../node_modules/@sentry/core/build/esm/transports/base.js","../../../node_modules/@sentry/core/build/esm/utils/clientreport.js","../../../node_modules/@sentry/core/build/esm/utils/eventUtils.js","../../../node_modules/@sentry/core/build/esm/utils/transactionEvent.js","../../../node_modules/@sentry/core/build/esm/client.js","../../../node_modules/@sentry/core/build/esm/utils/eventbuilder.js","../../../node_modules/@sentry/core/build/esm/sdk.js","../../../node_modules/@sentry/core/build/esm/utils/url.js","../../../node_modules/@sentry/core/build/esm/utils/isSentryRequestUrl.js","../../../node_modules/@sentry/core/build/esm/utils/ipAddress.js","../../../node_modules/@sentry/core/build/esm/utils/sdkMetadata.js","../../../node_modules/@sentry/core/build/esm/utils/debounce.js","../../../node_modules/@sentry/core/build/esm/breadcrumbs.js","../../../node_modules/@sentry/core/build/esm/integrations/functiontostring.js","../../../node_modules/@sentry/core/build/esm/integrations/eventFilters.js","../../../node_modules/@sentry/core/build/esm/utils/aggregate-errors.js","../../../node_modules/@sentry/core/build/esm/instrument/console.js","../../../node_modules/@sentry/core/build/esm/utils/severity.js","../../../node_modules/@sentry/core/build/esm/integrations/dedupe.js","../../../node_modules/@sentry/core/build/esm/integrations/conversationId.js","../../../node_modules/@sentry/core/build/esm/utils/breadcrumb-log-level.js","../../../node_modules/@sentry/core/build/esm/utils/supports.js","../../../node_modules/@sentry/core/build/esm/instrument/fetch.js","../../../node_modules/@sentry/core/build/esm/utils/env.js","../../../node_modules/@sentry/core/build/esm/utils/node.js","../../../node_modules/@sentry/core/build/esm/utils/isBrowser.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/helpers.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/eventbuilder.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/client.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/types.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/bindReporter.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getNavigationEntry.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getActivationStart.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/globalListeners.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getVisibilityWatcher.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/generateUniqueID.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/initMetric.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/initUnique.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/LayoutShiftManager.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/observe.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/runOnce.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenActivated.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onFCP.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getCLS.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/InteractionManager.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenIdleOrHidden.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getINP.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/LCPEntryManager.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getLCP.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/instrument.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/dom.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/history.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/getNativeImplementation.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/xhr.js","../../../node_modules/@sentry-internal/browser-utils/build/esm/networkUtils.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/transports/fetch.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/debug-build.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/stack-parsers.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/integrations/breadcrumbs.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/integrations/browserapierrors.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/integrations/browsersession.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/integrations/globalhandlers.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/integrations/httpcontext.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/integrations/linkederrors.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/utils/detectBrowserExtension.js","../../../node_modules/@sentry/browser/build/npm/esm/prod/sdk.js","../../../node_modules/@sentry-internal/replay/build/npm/esm/index.js","../../../node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js","../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js","../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js","../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js","../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/fetch_requests.js","../../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js","../../../app/javascript/controllers/response_container_quantity_controller.js","../../../node_modules/stimulus-vite-helpers/dist/index.js","../../../app/javascript/controllers/index.js","../../../app/javascript/entrypoints/application.js"],"sourcesContent":["import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getFunctionName } from '../utils/stacktrace.js';\n\n// We keep the handlers globally\nconst handlers = {};\nconst instrumented = {};\n\n/** Add a handler function. */\nfunction addHandler(type, handler) {\n handlers[type] = handlers[type] || [];\n handlers[type].push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nfunction resetInstrumentationHandlers() {\n Object.keys(handlers).forEach(key => {\n handlers[key ] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nfunction maybeInstrument(type, instrumentFn) {\n if (!instrumented[type]) {\n instrumented[type] = true;\n try {\n instrumentFn();\n } catch (e) {\n DEBUG_BUILD && debug.error(`Error while instrumenting ${type}`, e);\n }\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n debug.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nexport { addHandler, maybeInstrument, resetInstrumentationHandlers, triggerHandlers };\n//# sourceMappingURL=handlers.js.map\n","import { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnErrorHandler = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalErrorInstrumentationHandler(handler) {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError() {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n // Note: The reason we are doing window.onerror instead of window.addEventListener('error')\n // is that we are using this handler in the Loader Script, to handle buffered errors consistently\n GLOBAL_OBJ.onerror = function (\n msg,\n url,\n line,\n column,\n error,\n ) {\n const handlerData = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalErrorInstrumentationHandler };\n//# sourceMappingURL=globalError.js.map\n","import { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnUnhandledRejectionHandler = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalUnhandledRejectionInstrumentationHandler(\n handler,\n) {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')\n // is that we are using this handler in the Loader Script, to handle buffered rejections consistently\n GLOBAL_OBJ.onunhandledrejection = function (e) {\n const handlerData = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalUnhandledRejectionInstrumentationHandler };\n//# sourceMappingURL=globalUnhandledRejection.js.map\n","/**\n * Parse a sample rate from a given value.\n * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).\n * If a string is passed, we try to convert it to a number.\n *\n * Any invalid sample rate will return `undefined`.\n */\nfunction parseSampleRate(sampleRate) {\n if (typeof sampleRate === 'boolean') {\n return Number(sampleRate);\n }\n\n const rate = typeof sampleRate === 'string' ? parseFloat(sampleRate) : sampleRate;\n if (typeof rate !== 'number' || isNaN(rate) || rate < 0 || rate > 1) {\n return undefined;\n }\n\n return rate;\n}\n\nexport { parseSampleRate };\n//# sourceMappingURL=parseSampleRate.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { isMatchingPattern } from './string.js';\n\nfunction logIgnoredSpan(droppedSpan) {\n debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \\`ignoreSpans\\`.`);\n}\n\n/**\n * Check if a span should be ignored based on the ignoreSpans configuration.\n */\nfunction shouldIgnoreSpan(\n span,\n ignoreSpans,\n) {\n if (!ignoreSpans?.length || !span.description) {\n return false;\n }\n\n for (const pattern of ignoreSpans) {\n if (isStringOrRegExp(pattern)) {\n if (isMatchingPattern(span.description, pattern)) {\n DEBUG_BUILD && logIgnoredSpan(span);\n return true;\n }\n continue;\n }\n\n if (!pattern.name && !pattern.op) {\n continue;\n }\n\n const nameMatches = pattern.name ? isMatchingPattern(span.description, pattern.name) : true;\n const opMatches = pattern.op ? span.op && isMatchingPattern(span.op, pattern.op) : true;\n\n // This check here is only correct because we can guarantee that we ran `isMatchingPattern`\n // for at least one of `nameMatches` and `opMatches`. So in contrary to how this looks,\n // not both op and name actually have to match. This is the most efficient way to check\n // for all combinations of name and op patterns.\n if (nameMatches && opMatches) {\n DEBUG_BUILD && logIgnoredSpan(span);\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Takes a list of spans, and a span that was dropped, and re-parents the child spans of the dropped span to the parent of the dropped span, if possible.\n * This mutates the spans array in place!\n */\nfunction reparentChildSpans(spans, dropSpan) {\n const droppedSpanParentId = dropSpan.parent_span_id;\n const droppedSpanId = dropSpan.span_id;\n\n // This should generally not happen, as we do not apply this on root spans\n // but to be safe, we just bail in this case\n if (!droppedSpanParentId) {\n return;\n }\n\n for (const span of spans) {\n if (span.parent_span_id === droppedSpanId) {\n span.parent_span_id = droppedSpanParentId;\n }\n }\n}\n\nfunction isStringOrRegExp(value) {\n return typeof value === 'string' || value instanceof RegExp;\n}\n\nexport { reparentChildSpans, shouldIgnoreSpan };\n//# sourceMappingURL=should-ignore-span.js.map\n","import { getSentryCarrier } from '../carrier.js';\nimport { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nfunction envelopeContainsItemType(envelope, types) {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input) {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input) {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope) {\n const [envHeaders, items] = envelope;\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(env) {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(decodeUTF8(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates envelope item for a single span\n */\nfunction createSpanEnvelopeItem(spanJson) {\n const spanHeaders = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(attachment) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n return [\n {\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n },\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n profile_chunk: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n raw_security: 'security',\n log: 'log_item',\n metric: 'metric',\n trace_metric: 'metric',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent?.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dynamicSamplingContext,\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext.js';\nimport { dsnToString } from './utils/dsn.js';\nimport { getSdkMetadataForEnvelopeHeader, createEventEnvelopeHeaders, createEnvelope, createSpanEnvelopeItem } from './utils/envelope.js';\nimport { shouldIgnoreSpan } from './utils/should-ignore-span.js';\nimport { spanToJSON, showSpanDropWarning } from './utils/spanUtils.js';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n *\n * @internal, exported only for testing\n **/\nfunction _enhanceEventWithSdkInfo(event, newSdkInfo) {\n if (!newSdkInfo) {\n return event;\n }\n\n const eventSdkInfo = event.sdk || {};\n\n event.sdk = {\n ...eventSdkInfo,\n name: eventSdkInfo.name || newSdkInfo.name,\n version: eventSdkInfo.version || newSdkInfo.version,\n integrations: [...(event.sdk?.integrations || []), ...(newSdkInfo.integrations || [])],\n packages: [...(event.sdk?.packages || []), ...(newSdkInfo.packages || [])],\n settings:\n event.sdk?.settings || newSdkInfo.settings\n ? {\n ...event.sdk?.settings,\n ...newSdkInfo.settings,\n }\n : undefined,\n };\n\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjust a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n _enhanceEventWithSdkInfo(event, metadata?.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\n/**\n * Create envelope from Span item.\n *\n * Takes an optional client and runs spans through `beforeSendSpan` if available.\n */\nfunction createSpanEnvelope(spans, client) {\n function dscHasRequiredProps(dsc) {\n return !!dsc.trace_id && !!dsc.public_key;\n }\n\n // For the moment we'll obtain the DSC from the first span in the array\n // This might need to be changed if we permit sending multiple spans from\n // different segments in one envelope\n const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n\n const headers = {\n sent_at: new Date().toISOString(),\n ...(dscHasRequiredProps(dsc) && { trace: dsc }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {};\n\n const filteredSpans = ignoreSpans?.length\n ? spans.filter(span => !shouldIgnoreSpan(spanToJSON(span), ignoreSpans))\n : spans;\n const droppedSpans = spans.length - filteredSpans.length;\n\n if (droppedSpans) {\n client?.recordDroppedEvent('before_send', 'span', droppedSpans);\n }\n\n const convertToSpanJSON = beforeSendSpan\n ? (span) => {\n const spanJson = spanToJSON(span);\n const processedSpan = beforeSendSpan(spanJson);\n\n if (!processedSpan) {\n showSpanDropWarning();\n return spanJson;\n }\n\n return processedSpan;\n }\n : spanToJSON;\n\n const items = [];\n for (const span of filteredSpans) {\n const spanJson = convertToSpanJSON(span);\n if (spanJson) {\n items.push(createSpanEnvelopeItem(spanJson));\n }\n }\n\n return createEnvelope(headers, items);\n}\n\nexport { _enhanceEventWithSdkInfo, createEventEnvelope, createSessionEnvelope, createSpanEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { makeDsn, dsnToString } from './utils/dsn.js';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n const params = {\n sentry_version: SENTRY_API_VERSION,\n };\n\n if (dsn.publicKey) {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n params.sentry_key = dsn.publicKey;\n }\n\n if (sdkInfo) {\n params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;\n }\n\n return new URLSearchParams(params).toString();\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(dsnLike, dialogOptions) {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getClient } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { debug } from './utils/debug-logger.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preserve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach((currentInstance) => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(\n options,\n) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach((integration) => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n const resolvedUserIntegrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];\n } else {\n integrations = defaultIntegrations;\n }\n\n return filterDuplicates(integrations);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(client, integrations) {\n const integrationIndex = {};\n\n integrations.forEach((integration) => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nfunction afterSetupIntegrations(client, integrations) {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration?.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(client, integration, integrationIndex) {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && debug.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (!installedIntegrations.includes(integration.name) && typeof integration.setupOnce === 'function') {\n integration.setupOnce();\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) ;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) ;\n\n const processor = Object.assign((event, hint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && debug.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nfunction addIntegration(integration) {\n const client = getClient();\n\n if (!client) {\n DEBUG_BUILD && debug.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nfunction defineIntegration(fn) {\n return fn;\n}\n\nexport { addIntegration, afterSetupIntegrations, defineIntegration, getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","import { dsnToString } from '../utils/dsn.js';\nimport { createEnvelope } from '../utils/envelope.js';\n\n/**\n * Creates a log container envelope item for a list of logs.\n *\n * @param items - The logs to include in the envelope.\n * @returns The created log container envelope item.\n */\nfunction createLogContainerEnvelopeItem(items) {\n return [\n {\n type: 'log',\n item_count: items.length,\n content_type: 'application/vnd.sentry.items.log+json',\n },\n {\n items,\n },\n ];\n}\n\n/**\n * Creates an envelope for a list of logs.\n *\n * Logs from multiple traces can be included in the same envelope.\n *\n * @param logs - The logs to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nfunction createLogEnvelope(\n logs,\n metadata,\n tunnel,\n dsn,\n) {\n const headers = {};\n\n if (metadata?.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n return createEnvelope(headers, [createLogContainerEnvelopeItem(logs)]);\n}\n\nexport { createLogContainerEnvelopeItem, createLogEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { serializeAttributes } from '../attributes.js';\nimport { getGlobalSingleton } from '../carrier.js';\nimport { getCurrentScope, getClient, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { debug, consoleSandbox } from '../utils/debug-logger.js';\nimport { isParameterizedString } from '../utils/is.js';\nimport { getCombinedScopeData } from '../utils/scopeData.js';\nimport { _getSpanForScope } from '../utils/spanOnScope.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { _getTraceInfoFromScope } from '../utils/trace-info.js';\nimport { SEVERITY_TEXT_TO_SEVERITY_NUMBER } from './constants.js';\nimport { createLogEnvelope } from './envelope.js';\n\nconst MAX_LOG_BUFFER_SIZE = 100;\n\n/**\n * Sets a log attribute if the value exists and the attribute key is not already present.\n *\n * @param logAttributes - The log attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setLogAttribute(\n logAttributes,\n key,\n value,\n setEvenIfPresent = true,\n) {\n if (value && (!logAttributes[key] || setEvenIfPresent)) {\n logAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized log event and adds it to the log buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedLog - The serialized log event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureSerializedLog(client, serializedLog) {\n const bufferMap = _getBufferMap();\n const logBuffer = _INTERNAL_getLogBuffer(client);\n\n if (logBuffer === undefined) {\n bufferMap.set(client, [serializedLog]);\n } else {\n if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) {\n _INTERNAL_flushLogsBuffer(client, logBuffer);\n bufferMap.set(client, [serializedLog]);\n } else {\n bufferMap.set(client, [...logBuffer, serializedLog]);\n }\n }\n}\n\n/**\n * Captures a log event and sends it to Sentry.\n *\n * @param log - The log event to capture.\n * @param scope - A scope. Uses the current scope if not provided.\n * @param client - A client. Uses the current client if not provided.\n * @param captureSerializedLog - A function to capture the serialized log.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureLog(\n beforeLog,\n currentScope = getCurrentScope(),\n captureSerializedLog = _INTERNAL_captureSerializedLog,\n) {\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture log.');\n return;\n }\n\n const { release, environment, enableLogs = false, beforeSendLog } = client.getOptions();\n if (!enableLogs) {\n DEBUG_BUILD && debug.warn('logging option not enabled, log will not be captured.');\n return;\n }\n\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n\n const processedLogAttributes = {\n ...beforeLog.attributes,\n };\n\n const {\n user: { id, email, username },\n attributes: scopeAttributes = {},\n } = getCombinedScopeData(getIsolationScope(), currentScope);\n\n setLogAttribute(processedLogAttributes, 'user.id', id, false);\n setLogAttribute(processedLogAttributes, 'user.email', email, false);\n setLogAttribute(processedLogAttributes, 'user.name', username, false);\n\n setLogAttribute(processedLogAttributes, 'sentry.release', release);\n setLogAttribute(processedLogAttributes, 'sentry.environment', environment);\n\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setLogAttribute(processedLogAttributes, 'sentry.sdk.name', name);\n setLogAttribute(processedLogAttributes, 'sentry.sdk.version', version);\n\n const replay = client.getIntegrationByName\n\n('Replay');\n\n const replayId = replay?.getReplayId(true);\n setLogAttribute(processedLogAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n // We send this so we can identify cases where the replayId is attached but the replay itself might not have been sent to Sentry\n setLogAttribute(processedLogAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n const beforeLogMessage = beforeLog.message;\n if (isParameterizedString(beforeLogMessage)) {\n const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;\n if (__sentry_template_values__?.length) {\n processedLogAttributes['sentry.message.template'] = __sentry_template_string__;\n }\n __sentry_template_values__.forEach((param, index) => {\n processedLogAttributes[`sentry.message.parameter.${index}`] = param;\n });\n }\n\n const span = _getSpanForScope(currentScope);\n // Add the parent span ID to the log attributes for trace context\n setLogAttribute(processedLogAttributes, 'sentry.trace.parent_span_id', span?.spanContext().spanId);\n\n const processedLog = { ...beforeLog, attributes: processedLogAttributes };\n\n client.emit('beforeCaptureLog', processedLog);\n\n // We need to wrap this in `consoleSandbox` to avoid recursive calls to `beforeSendLog`\n const log = beforeSendLog ? consoleSandbox(() => beforeSendLog(processedLog)) : processedLog;\n if (!log) {\n client.recordDroppedEvent('before_send', 'log_item', 1);\n DEBUG_BUILD && debug.warn('beforeSendLog returned null, log will not be captured.');\n return;\n }\n\n const { level, message, attributes: logAttributes = {}, severityNumber } = log;\n\n const serializedLog = {\n timestamp: timestampInSeconds(),\n level,\n body: message,\n trace_id: traceContext?.trace_id,\n severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],\n attributes: {\n ...serializeAttributes(scopeAttributes),\n ...serializeAttributes(logAttributes, true),\n },\n };\n\n captureSerializedLog(client, serializedLog);\n\n client.emit('afterCaptureLog', log);\n}\n\n/**\n * Flushes the logs buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeLogBuffer - A log buffer. Uses the log buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) {\n const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];\n if (logBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the log buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushLogs');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the log buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the log buffer for.\n * @returns The log buffer for the given client.\n */\nfunction _INTERNAL_getLogBuffer(client) {\n return _getBufferMap().get(client);\n}\n\nfunction _getBufferMap() {\n // The reference to the Client <> LogBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToLogBufferMap', () => new WeakMap());\n}\n\nexport { _INTERNAL_captureLog, _INTERNAL_captureSerializedLog, _INTERNAL_flushLogsBuffer, _INTERNAL_getLogBuffer };\n//# sourceMappingURL=internal.js.map\n","import { dsnToString } from '../utils/dsn.js';\nimport { createEnvelope } from '../utils/envelope.js';\n\n/**\n * Creates a metric container envelope item for a list of metrics.\n *\n * @param items - The metrics to include in the envelope.\n * @returns The created metric container envelope item.\n */\nfunction createMetricContainerEnvelopeItem(items) {\n return [\n {\n type: 'trace_metric',\n item_count: items.length,\n content_type: 'application/vnd.sentry.items.trace-metric+json',\n } ,\n {\n items,\n },\n ];\n}\n\n/**\n * Creates an envelope for a list of metrics.\n *\n * Metrics from multiple traces can be included in the same envelope.\n *\n * @param metrics - The metrics to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nfunction createMetricEnvelope(\n metrics,\n metadata,\n tunnel,\n dsn,\n) {\n const headers = {};\n\n if (metadata?.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n return createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics)]);\n}\n\nexport { createMetricContainerEnvelopeItem, createMetricEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { serializeAttributes } from '../attributes.js';\nimport { getGlobalSingleton } from '../carrier.js';\nimport { getCurrentScope, getClient, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getCombinedScopeData } from '../utils/scopeData.js';\nimport { _getSpanForScope } from '../utils/spanOnScope.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { _getTraceInfoFromScope } from '../utils/trace-info.js';\nimport { createMetricEnvelope } from './envelope.js';\n\nconst MAX_METRIC_BUFFER_SIZE = 1000;\n\n/**\n * Sets a metric attribute if the value exists and the attribute key is not already present.\n *\n * @param metricAttributes - The metric attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setMetricAttribute(\n metricAttributes,\n key,\n value,\n setEvenIfPresent = true,\n) {\n if (value && (setEvenIfPresent || !(key in metricAttributes))) {\n metricAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized metric event and adds it to the metric buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedMetric - The serialized metric event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureSerializedMetric(client, serializedMetric) {\n const bufferMap = _getBufferMap();\n const metricBuffer = _INTERNAL_getMetricBuffer(client);\n\n if (metricBuffer === undefined) {\n bufferMap.set(client, [serializedMetric]);\n } else {\n if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {\n _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n bufferMap.set(client, [serializedMetric]);\n } else {\n bufferMap.set(client, [...metricBuffer, serializedMetric]);\n }\n }\n}\n\n/**\n * Options for capturing a metric internally.\n */\n\n/**\n * Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)\n */\nfunction _enrichMetricAttributes(beforeMetric, client, user) {\n const { release, environment } = client.getOptions();\n\n const processedMetricAttributes = {\n ...beforeMetric.attributes,\n };\n\n // Add user attributes\n setMetricAttribute(processedMetricAttributes, 'user.id', user.id, false);\n setMetricAttribute(processedMetricAttributes, 'user.email', user.email, false);\n setMetricAttribute(processedMetricAttributes, 'user.name', user.username, false);\n\n // Add Sentry metadata\n setMetricAttribute(processedMetricAttributes, 'sentry.release', release);\n setMetricAttribute(processedMetricAttributes, 'sentry.environment', environment);\n\n // Add SDK metadata\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.name', name);\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.version', version);\n\n // Add replay metadata\n const replay = client.getIntegrationByName\n\n('Replay');\n\n const replayId = replay?.getReplayId(true);\n setMetricAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n setMetricAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n return {\n ...beforeMetric,\n attributes: processedMetricAttributes,\n };\n}\n\n/**\n * Creates a serialized metric ready to be sent to Sentry.\n */\nfunction _buildSerializedMetric(\n metric,\n client,\n currentScope,\n scopeAttributes,\n) {\n // Get trace context\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n const span = _getSpanForScope(currentScope);\n const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n const spanId = span ? span.spanContext().spanId : undefined;\n\n return {\n timestamp: timestampInSeconds(),\n trace_id: traceId ?? '',\n span_id: spanId,\n name: metric.name,\n type: metric.type,\n unit: metric.unit,\n value: metric.value,\n attributes: {\n ...serializeAttributes(scopeAttributes),\n ...serializeAttributes(metric.attributes, 'skip-undefined'),\n },\n };\n}\n\n/**\n * Captures a metric event and sends it to Sentry.\n *\n * @param metric - The metric event to capture.\n * @param options - Options for capturing the metric.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureMetric(beforeMetric, options) {\n const currentScope = options?.scope ?? getCurrentScope();\n const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture metric.');\n return;\n }\n\n const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n\n if (!metricsEnabled) {\n DEBUG_BUILD && debug.warn('metrics option not enabled, metric will not be captured.');\n return;\n }\n\n // Enrich metric with contextual attributes\n const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);\n const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);\n\n client.emit('processMetric', enrichedMetric);\n\n // todo(v11): Remove the experimental `beforeSendMetric`\n // eslint-disable-next-line deprecation/deprecation\n const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n\n if (!processedMetric) {\n DEBUG_BUILD && debug.log('`beforeSendMetric` returned `null`, will not send metric.');\n return;\n }\n\n const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);\n\n DEBUG_BUILD && debug.log('[Metric]', serializedMetric);\n\n captureSerializedMetric(client, serializedMetric);\n\n client.emit('afterCaptureMetric', processedMetric);\n}\n\n/**\n * Flushes the metrics buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) {\n const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n if (metricBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the metric buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushMetrics');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the metric buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the metric buffer for.\n * @returns The metric buffer for the given client.\n */\nfunction _INTERNAL_getMetricBuffer(client) {\n return _getBufferMap().get(client);\n}\n\nfunction _getBufferMap() {\n // The reference to the Client <> MetricBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToMetricBufferMap', () => new WeakMap());\n}\n\nexport { _INTERNAL_captureMetric, _INTERNAL_captureSerializedMetric, _INTERNAL_flushMetricsBuffer, _INTERNAL_getMetricBuffer };\n//# sourceMappingURL=internal.js.map\n","import { resolvedSyncPromise, rejectedSyncPromise } from './syncpromise.js';\n\nconst SENTRY_BUFFER_FULL_ERROR = Symbol.for('SentryBufferFullError');\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit = 100) {\n const buffer = new Set();\n\n function isReady() {\n return buffer.size < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n buffer.delete(task);\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n buffer.add(task);\n void task.then(\n () => remove(task),\n () => remove(task),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n if (!buffer.size) {\n return resolvedSyncPromise(true);\n }\n\n // We want to resolve even if one of the promises rejects\n const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true);\n\n if (!timeout) {\n return drainPromise;\n }\n\n const promises = [drainPromise, new Promise(resolve => setTimeout(() => resolve(false), timeout))];\n\n // Promise.race will resolve to the first promise that resolves or rejects\n // So if the drainPromise resolves, the timeout promise will be ignored\n return Promise.race(promises);\n }\n\n return {\n get $() {\n return Array.from(buffer);\n },\n add,\n drain,\n };\n}\n\nexport { SENTRY_BUFFER_FULL_ERROR, makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","import { safeDateNow } from './randomSafeContext.js';\n\n// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = safeDateNow()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, dataCategory) {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, dataCategory, now = safeDateNow()) {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = safeDateNow(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers?.['x-sentry-rate-limits'];\n const retryAfterHeader = headers?.['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5) ;\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { forEachEnvelopeItem, envelopeItemTypeToDataCategory, createEnvelope, serializeEnvelope, envelopeContainsItemType } from '../utils/envelope.js';\nimport { makePromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from '../utils/promisebuffer.js';\nimport { isRateLimited, updateRateLimits } from '../utils/ratelimit.js';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n options.recordDroppedEvent('ratelimit_backoff', dataCategory);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return Promise.resolve({});\n }\n\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n // Don't record outcomes for client reports - we don't want to create a feedback loop if client reports themselves fail to send\n if (envelopeContainsItemType(filteredEnvelope, ['client_report'])) {\n DEBUG_BUILD && debug.warn(`Dropping client report. Will not send outcomes (reason: ${reason}).`);\n return;\n }\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type));\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && debug.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n DEBUG_BUILD && debug.error('Encountered error running transport request:', error);\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error === SENTRY_BUFFER_FULL_ERROR) {\n DEBUG_BUILD && debug.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return Promise.resolve({});\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","/**\n * Get a list of possible event messages from a Sentry event.\n */\nfunction getPossibleEventMessages(event) {\n const possibleMessages = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n try {\n // @ts-expect-error Try catching to save bundle size\n const lastException = event.exception.values[event.exception.values.length - 1];\n if (lastException?.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n } catch {\n // ignore errors here\n }\n\n return possibleMessages;\n}\n\nexport { getPossibleEventMessages };\n//# sourceMappingURL=eventUtils.js.map\n","import { SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_PROFILE_ID } from '../semanticAttributes.js';\n\n/**\n * Converts a transaction event to a span JSON object.\n */\nfunction convertTransactionEventToSpanJson(event) {\n const { trace_id, parent_span_id, span_id, status, origin, data, op } = event.contexts?.trace ?? {};\n\n return {\n data: data ?? {},\n description: event.transaction,\n op,\n parent_span_id,\n span_id: span_id ?? '',\n start_timestamp: event.start_timestamp ?? 0,\n status,\n timestamp: event.timestamp,\n trace_id: trace_id ?? '',\n origin,\n profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID] ,\n exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] ,\n measurements: event.measurements,\n is_segment: true,\n };\n}\n\n/**\n * Converts a span JSON object to a transaction event.\n */\nfunction convertSpanJsonToTransactionEvent(span) {\n return {\n type: 'transaction',\n timestamp: span.timestamp,\n start_timestamp: span.start_timestamp,\n transaction: span.description,\n contexts: {\n trace: {\n trace_id: span.trace_id,\n span_id: span.span_id,\n parent_span_id: span.parent_span_id,\n op: span.op,\n status: span.status,\n origin: span.origin,\n data: {\n ...span.data,\n ...(span.profile_id && { [SEMANTIC_ATTRIBUTE_PROFILE_ID]: span.profile_id }),\n ...(span.exclusive_time && { [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: span.exclusive_time }),\n },\n },\n },\n measurements: span.measurements,\n };\n}\n\nexport { convertSpanJsonToTransactionEvent, convertTransactionEventToSpanJson };\n//# sourceMappingURL=transactionEvent.js.map\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { getTraceContextFromScope, getCurrentScope, getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegration, afterSetupIntegrations, setupIntegrations } from './integration.js';\nimport { _INTERNAL_flushLogsBuffer } from './logs/internal.js';\nimport { _INTERNAL_flushMetricsBuffer } from './metrics/internal.js';\nimport { updateSession } from './session.js';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext.js';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base.js';\nimport { createClientReportEnvelope } from './utils/clientreport.js';\nimport { debug } from './utils/debug-logger.js';\nimport { makeDsn, dsnToString } from './utils/dsn.js';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils/envelope.js';\nimport { getPossibleEventMessages } from './utils/eventUtils.js';\nimport { isParameterizedString, isPrimitive, isThenable, isPlainObject } from './utils/is.js';\nimport { merge } from './utils/merge.js';\nimport { uuid4, checkOrSetAlreadyCaught } from './utils/misc.js';\nimport { parseSampleRate } from './utils/parseSampleRate.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\nimport { makePromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from './utils/promisebuffer.js';\nimport { safeMathRandom } from './utils/randomSafeContext.js';\nimport { shouldIgnoreSpan, reparentChildSpans } from './utils/should-ignore-span.js';\nimport { showSpanDropWarning } from './utils/spanUtils.js';\nimport { rejectedSyncPromise } from './utils/syncpromise.js';\nimport { convertTransactionEventToSpanJson, convertSpanJsonToTransactionEvent } from './utils/transactionEvent.js';\n\n/* eslint-disable max-lines */\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\nconst MISSING_RELEASE_FOR_SESSION_ERROR = 'Discarded session because of missing or non-string release';\n\nconst INTERNAL_ERROR_SYMBOL = Symbol.for('SentryInternalError');\nconst DO_NOT_SEND_EVENT_SYMBOL = Symbol.for('SentryDoNotSendEventError');\n\n// Default interval for flushing logs and metrics (5 seconds)\nconst DEFAULT_FLUSH_INTERVAL = 5000;\n\nfunction _makeInternalError(message) {\n return {\n message,\n [INTERNAL_ERROR_SYMBOL]: true,\n };\n}\n\nfunction _makeDoNotSendEventError(message) {\n return {\n message,\n [DO_NOT_SEND_EVENT_SYMBOL]: true,\n };\n}\n\nfunction _isInternalError(error) {\n return !!error && typeof error === 'object' && INTERNAL_ERROR_SYMBOL in error;\n}\n\nfunction _isDoNotSendEventError(error) {\n return !!error && typeof error === 'object' && DO_NOT_SEND_EVENT_SYMBOL in error;\n}\n\n/**\n * Sets up weight-based flushing for logs or metrics.\n * This helper function encapsulates the common pattern of:\n * 1. Tracking accumulated weight of items\n * 2. Flushing when weight exceeds threshold (800KB)\n * 3. Flushing after timeout period from the first item\n *\n * Uses closure variables to track weight and timeout state.\n */\nfunction setupWeightBasedFlushing\n\n(\n client,\n afterCaptureHook,\n flushHook,\n estimateSizeFn,\n flushFn,\n) {\n // Track weight and timeout in closure variables\n let weight = 0;\n let flushTimeout;\n let isTimerActive = false;\n\n // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n client.on(flushHook, () => {\n weight = 0;\n clearTimeout(flushTimeout);\n isTimerActive = false;\n });\n\n // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n client.on(afterCaptureHook, (item) => {\n weight += estimateSizeFn(item);\n\n // We flush the buffer if it exceeds 0.8 MB\n // The weight is a rough estimate, so we flush way before the payload gets too big.\n if (weight >= 800000) {\n flushFn(client);\n } else if (!isTimerActive) {\n // Only start timer if one isn't already running.\n // This prevents flushing being delayed by items that arrive close to the timeout limit\n // and thus resetting the flushing timeout and delaying items being flushed.\n isTimerActive = true;\n flushTimeout = setTimeout(() => {\n flushFn(client);\n // Note: isTimerActive is reset by the flushHook handler above, not here,\n // to avoid race conditions when new items arrive during the flush.\n }, DEFAULT_FLUSH_INTERVAL);\n }\n });\n\n client.on('flush', () => {\n flushFn(client);\n });\n}\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link Client._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends Client {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass Client {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n\n /** Number of calls being processed */\n\n /** Holds flushable */\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {\n this._options = options;\n this._integrations = {};\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE);\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && debug.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(\n this._dsn,\n options.tunnel,\n options._metadata ? options._metadata.sdk : undefined,\n );\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n\n // Backfill enableLogs option from _experiments.enableLogs\n // TODO(v11): Remove or change default value\n // eslint-disable-next-line deprecation/deprecation\n this._options.enableLogs = this._options.enableLogs ?? this._options._experiments?.enableLogs;\n\n // Setup log flushing with weight and timeout tracking\n if (this._options.enableLogs) {\n setupWeightBasedFlushing(this, 'afterCaptureLog', 'flushLogs', estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer);\n }\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const enableMetrics = this._options.enableMetrics ?? this._options._experiments?.enableMetrics ?? true;\n\n // Setup metric flushing with weight and timeout tracking\n if (enableMetrics) {\n setupWeightBasedFlushing(\n this,\n 'afterCaptureMetric',\n 'flushMetrics',\n estimateMetricSizeInBytes,\n _INTERNAL_flushMetricsBuffer,\n );\n }\n }\n\n /**\n * Captures an exception event and sends it to Sentry.\n *\n * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureException(exception, hint, scope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && debug.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n this._process(\n () =>\n this.eventFromException(exception, hintWithEventId)\n .then(event => this._captureEvent(event, hintWithEventId, scope))\n .then(res => res),\n 'error',\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a message event and sends it to Sentry.\n *\n * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureMessage(\n message,\n level,\n hint,\n currentScope,\n ) {\n const hintWithEventId = {\n event_id: uuid4(),\n ...hint,\n };\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n const isMessage = isPrimitive(message);\n const promisedEvent = isMessage\n ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n : this.eventFromException(message, hintWithEventId);\n\n this._process(\n () => promisedEvent.then(event => this._captureEvent(event, hintWithEventId, currentScope)),\n isMessage ? 'unknown' : 'error',\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a manually created event and sends it to Sentry.\n *\n * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureEvent(event, hint, currentScope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && debug.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;\n const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;\n const dataCategory = getDataCategoryByType(event.type);\n\n this._process(\n () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope),\n dataCategory,\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a session.\n */\n captureSession(session) {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry. This method is not available on all clients.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n * @param scope An optional scope containing event metadata.\n * @returns A string representing the id of the check in.\n */\n\n /**\n * Get the current Dsn.\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * Get the current options.\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * Get the SDK metadata.\n * @see SdkMetadata\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * Returns the transport that is used by the client.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will\n * cause the client to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n async flush(timeout) {\n const transport = this._transport;\n if (!transport) {\n return true;\n }\n\n this.emit('flush');\n\n const clientFinished = await this._isClientDoneProcessing(timeout);\n const transportFlushed = await transport.flush(timeout);\n\n return clientFinished && transportFlushed;\n }\n\n /**\n * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}.\n *\n * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause\n * the client to wait until all events are sent before disabling itself.\n * @returns {Promise} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if\n * it doesn't.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n async close(timeout) {\n const result = await this.flush(timeout);\n this.getOptions().enabled = false;\n this.emit('close');\n return result;\n }\n\n /**\n * Get all installed event processors.\n */\n getEventProcessors() {\n return this._eventProcessors;\n }\n\n /**\n * Adds an event processor that applies to any event processed by this client.\n */\n addEventProcessor(eventProcessor) {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * Initialize this client.\n * Call this after the client was set on a scope.\n */\n init() {\n if (\n this._isEnabled() ||\n // Force integrations to be setup even if no DSN was set when we have\n // Spotlight enabled. This is particularly important for browser as we\n // don't support the `spotlight` option there and rely on the users\n // adding the `spotlightBrowserIntegration()` to their integrations which\n // wouldn't get initialized with the check below when there's no DSN set.\n this._options.integrations.some(({ name }) => name.startsWith('Spotlight'))\n ) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed.\n */\n getIntegrationByName(integrationName) {\n return this._integrations[integrationName] ;\n }\n\n /**\n * Add an integration to the client.\n * This can be used to e.g. lazy load integrations.\n * In most cases, this should not be necessary,\n * and you're better off just passing the integrations via `integrations: []` at initialization time.\n * However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so.\n */\n addIntegration(integration) {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * Send a fully prepared event to Sentry.\n */\n sendEvent(event, hint = {}) {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));\n }\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env).then(sendResponse => this.emit('afterSendEvent', event, sendResponse));\n }\n\n /**\n * Send a session or session aggregrates to Sentry.\n */\n sendSession(session) {\n // Backfill release and environment on session\n const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options;\n if ('aggregates' in session) {\n const sessionAttrs = session.attrs || {};\n if (!sessionAttrs.release && !clientReleaseOption) {\n DEBUG_BUILD && debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n sessionAttrs.release = sessionAttrs.release || clientReleaseOption;\n sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption;\n session.attrs = sessionAttrs;\n } else {\n if (!session.release && !clientReleaseOption) {\n DEBUG_BUILD && debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n session.release = session.release || clientReleaseOption;\n session.environment = session.environment || clientEnvironmentOption;\n }\n\n this.emit('beforeSendSession', session);\n\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env);\n }\n\n /**\n * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry).\n */\n recordDroppedEvent(reason, category, count = 1) {\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && debug.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /* eslint-disable @typescript-eslint/unified-signatures */\n /**\n * Register a callback for whenever a span is started.\n * Receives the span as argument.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n\n /**\n * Register a hook on this client.\n */\n on(hook, callback) {\n const hookCallbacks = (this._hooks[hook] = this._hooks[hook] || new Set());\n\n // Wrap the callback in a function so that registering the same callback instance multiple\n // times results in the callback being called multiple times.\n // @ts-expect-error - The `callback` type is correct and must be a function due to the\n // individual, specific overloads of this function.\n // eslint-disable-next-line @typescript-eslint/ban-types\n const uniqueCallback = (...args) => callback(...args);\n\n hookCallbacks.add(uniqueCallback);\n\n // This function returns a callback execution handler that, when invoked,\n // deregisters a callback. This is crucial for managing instances where callbacks\n // need to be unregistered to prevent self-referencing in callback closures,\n // ensuring proper garbage collection.\n return () => {\n hookCallbacks.delete(uniqueCallback);\n };\n }\n\n /** Fire a hook whenever a span starts. */\n\n /**\n * Emit a hook that was previously registered via `on()`.\n */\n emit(hook, ...rest) {\n const callbacks = this._hooks[hook];\n if (callbacks) {\n callbacks.forEach(callback => callback(...rest));\n }\n }\n\n /**\n * Send an envelope to Sentry.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n async sendEnvelope(envelope) {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n try {\n return await this._transport.send(envelope);\n } catch (reason) {\n DEBUG_BUILD && debug.error('Error while sending envelope:', reason);\n return {};\n }\n }\n\n DEBUG_BUILD && debug.error('Transport disabled');\n return {};\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n _setupIntegrations() {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n // initially, set `crashed` based on the event level and update from exceptions if there are any later on\n let crashed = event.level === 'fatal';\n let errored = false;\n const exceptions = event.exception?.values;\n\n if (exceptions) {\n errored = true;\n // reset crashed to false if there are exceptions, to ensure `mechanism.handled` is respected.\n crashed = false;\n\n for (const ex of exceptions) {\n if (ex.mechanism?.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n async _isClientDoneProcessing(timeout) {\n let ticked = 0;\n\n // if no timeout is provided, we wait \"forever\" until everything is processed\n while (!timeout || ticked < timeout) {\n await new Promise(resolve => setTimeout(resolve, 1));\n\n if (!this._numProcessing) {\n return true;\n }\n ticked++;\n }\n\n return false;\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations?.length) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n if (!event.type) {\n isolationScope.setLastEventId(event.event_id || hint.event_id);\n }\n\n return prepareEvent(options, event, hint, currentScope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n this.emit('postprocessEvent', evt, hint);\n\n evt.contexts = {\n trace: getTraceContextFromScope(currentScope),\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(\n event,\n hint = {},\n currentScope = getCurrentScope(),\n isolationScope = getIsolationScope(),\n ) {\n if (DEBUG_BUILD && isErrorEvent(event)) {\n debug.log(`Captured error event \\`${getPossibleEventMessages(event)[0] || ''}\\``);\n }\n\n return this._processEvent(event, hint, currentScope, isolationScope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n if (_isDoNotSendEventError(reason)) {\n debug.log(reason.message);\n } else if (_isInternalError(reason)) {\n debug.warn(reason.message);\n } else {\n debug.warn(reason);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate);\n if (isError && typeof parsedSampleRate === 'number' && safeMathRandom() > parsedSampleRate) {\n this.recordDroppedEvent('sample_rate', 'error');\n return rejectedSyncPromise(\n _makeDoNotSendEventError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n const dataCategory = getDataCategoryByType(event.type);\n\n return this._prepareEvent(event, hint, currentScope, isolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory);\n throw _makeDoNotSendEventError('An event processor returned `null`, will not send event.');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(this, options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw _makeDoNotSendEventError(`${beforeSendLabel} returned \\`null\\`, will not send event.`);\n }\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (isError && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (_isDoNotSendEventError(reason) || _isInternalError(reason)) {\n throw reason;\n }\n\n this.captureException(reason, {\n mechanism: {\n handled: false,\n type: 'internal',\n },\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw _makeInternalError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(taskProducer, dataCategory) {\n this._numProcessing++;\n\n void this._promiseBuffer.add(taskProducer).then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n\n if (reason === SENTRY_BUFFER_FULL_ERROR) {\n this.recordDroppedEvent('queue_overflow', dataCategory);\n }\n\n return reason;\n },\n );\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.entries(outcomes).map(([key, quantity]) => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity,\n };\n });\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n DEBUG_BUILD && debug.log('Flushing outcomes...');\n\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && debug.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && debug.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && debug.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n */\n\n}\n\nfunction getDataCategoryByType(type) {\n return type === 'replay_event' ? 'replay' : type || 'error';\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw _makeInternalError(invalidValueError);\n }\n return event;\n },\n e => {\n throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw _makeInternalError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n client,\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction, beforeSendSpan, ignoreSpans } = options;\n let processedEvent = event;\n\n if (isErrorEvent(processedEvent) && beforeSend) {\n return beforeSend(processedEvent, hint);\n }\n\n if (isTransactionEvent(processedEvent)) {\n // Avoid processing if we don't have to\n if (beforeSendSpan || ignoreSpans) {\n // 1. Process root span\n const rootSpanJson = convertTransactionEventToSpanJson(processedEvent);\n\n // 1.1 If the root span should be ignored, drop the whole transaction\n if (ignoreSpans?.length && shouldIgnoreSpan(rootSpanJson, ignoreSpans)) {\n // dropping the whole transaction!\n return null;\n }\n\n // 1.2 If a `beforeSendSpan` callback is defined, process the root span\n if (beforeSendSpan) {\n const processedRootSpanJson = beforeSendSpan(rootSpanJson);\n if (!processedRootSpanJson) {\n showSpanDropWarning();\n } else {\n // update event with processed root span values\n processedEvent = merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson));\n }\n }\n\n // 2. Process child spans\n if (processedEvent.spans) {\n const processedSpans = [];\n\n const initialSpans = processedEvent.spans;\n\n for (const span of initialSpans) {\n // 2.a If the child span should be ignored, reparent it to the root span\n if (ignoreSpans?.length && shouldIgnoreSpan(span, ignoreSpans)) {\n reparentChildSpans(initialSpans, span);\n continue;\n }\n\n // 2.b If a `beforeSendSpan` callback is defined, process the child span\n if (beforeSendSpan) {\n const processedSpan = beforeSendSpan(span);\n if (!processedSpan) {\n showSpanDropWarning();\n processedSpans.push(span);\n } else {\n processedSpans.push(processedSpan);\n }\n } else {\n processedSpans.push(span);\n }\n }\n\n const droppedSpans = processedEvent.spans.length - processedSpans.length;\n if (droppedSpans) {\n client.recordDroppedEvent('before_send', 'span', droppedSpans);\n }\n\n processedEvent.spans = processedSpans;\n }\n }\n\n if (beforeSendTransaction) {\n if (processedEvent.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = processedEvent.spans.length;\n processedEvent.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(processedEvent , hint);\n }\n }\n\n return processedEvent;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/**\n * Estimate the size of a metric in bytes.\n *\n * @param metric - The metric to estimate the size of.\n * @returns The estimated size of the metric in bytes.\n */\nfunction estimateMetricSizeInBytes(metric) {\n let weight = 0;\n\n // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n if (metric.name) {\n weight += metric.name.length * 2;\n }\n\n // Add weight for number\n weight += 8;\n\n return weight + estimateAttributesSizeInBytes(metric.attributes);\n}\n\n/**\n * Estimate the size of a log in bytes.\n *\n * @param log - The log to estimate the size of.\n * @returns The estimated size of the log in bytes.\n */\nfunction estimateLogSizeInBytes(log) {\n let weight = 0;\n\n // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n if (log.message) {\n weight += log.message.length * 2;\n }\n\n return weight + estimateAttributesSizeInBytes(log.attributes);\n}\n\n/**\n * Estimate the size of attributes in bytes.\n *\n * @param attributes - The attributes object to estimate the size of.\n * @returns The estimated size of the attributes in bytes.\n */\nfunction estimateAttributesSizeInBytes(attributes) {\n if (!attributes) {\n return 0;\n }\n\n let weight = 0;\n\n Object.values(attributes).forEach(value => {\n if (Array.isArray(value)) {\n weight += value.length * estimatePrimitiveSizeInBytes(value[0]);\n } else if (isPrimitive(value)) {\n weight += estimatePrimitiveSizeInBytes(value);\n } else {\n // For objects values, we estimate the size of the object as 100 bytes\n weight += 100;\n }\n });\n\n return weight;\n}\n\nfunction estimatePrimitiveSizeInBytes(value) {\n if (typeof value === 'string') {\n return value.length * 2;\n } else if (typeof value === 'number') {\n return 8;\n } else if (typeof value === 'boolean') {\n return 4;\n }\n\n return 0;\n}\n\nexport { Client };\n//# sourceMappingURL=client.js.map\n","import { isParameterizedString, isError, isPlainObject, isErrorEvent } from './is.js';\nimport { addExceptionMechanism, addExceptionTypeValue } from './misc.js';\nimport { normalizeToSize } from './normalize.js';\nimport { extractExceptionKeysForMessage } from './object.js';\n\n/**\n * Extracts stack frames from the error.stack string\n */\nfunction parseStackFrames(stackParser, error) {\n return stackParser(error.stack || '', 1);\n}\n\nfunction hasSentryFetchUrlHost(error) {\n return isError(error) && '__sentry_fetch_url_host__' in error && typeof error.__sentry_fetch_url_host__ === 'string';\n}\n\n/**\n * Enhances the error message with the hostname for better Sentry error reporting.\n * This allows third-party packages to still match on the original error message,\n * while Sentry gets the enhanced version with context.\n *\n * Only used internally\n * @hidden\n */\nfunction _enhanceErrorWithSentryInfo(error) {\n // If the error has a __sentry_fetch_url_host__ property (added by fetch instrumentation),\n // enhance the error message with the hostname.\n if (hasSentryFetchUrlHost(error)) {\n return `${error.message} (${error.__sentry_fetch_url_host__})`;\n }\n\n return error.message;\n}\n\n/**\n * Extracts stack frames from the error and builds a Sentry Exception\n */\nfunction exceptionFromError(stackParser, error) {\n const exception = {\n type: error.name || error.constructor.name,\n value: _enhanceErrorWithSentryInfo(error),\n };\n\n const frames = parseStackFrames(stackParser, error);\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n return exception;\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj) {\n for (const prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (value instanceof Error) {\n return value;\n }\n }\n }\n\n return undefined;\n}\n\nfunction getMessageForObject(exception) {\n if ('name' in exception && typeof exception.name === 'string') {\n let message = `'${exception.name}' captured as exception`;\n\n if ('message' in exception && typeof exception.message === 'string') {\n message += ` with message '${exception.message}'`;\n }\n\n return message;\n } else if ('message' in exception && typeof exception.message === 'string') {\n return exception.message;\n }\n\n const keys = extractExceptionKeysForMessage(exception);\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as exception with message \\`${exception.message}\\``;\n }\n\n const className = getObjectClassName(exception);\n\n return `${\n className && className !== 'Object' ? `'${className}'` : 'Object'\n } captured as exception with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch {\n // ignore errors here\n }\n}\n\nfunction getException(\n client,\n mechanism,\n exception,\n hint,\n) {\n if (isError(exception)) {\n return [exception, undefined];\n }\n\n // Mutate this!\n mechanism.synthetic = true;\n\n if (isPlainObject(exception)) {\n const normalizeDepth = client?.getOptions().normalizeDepth;\n const extras = { ['__serialized__']: normalizeToSize(exception, normalizeDepth) };\n\n const errorFromProp = getErrorPropertyFromObject(exception);\n if (errorFromProp) {\n return [errorFromProp, extras];\n }\n\n const message = getMessageForObject(exception);\n const ex = hint?.syntheticException || new Error(message);\n ex.message = message;\n\n return [ex, extras];\n }\n\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n const ex = hint?.syntheticException || new Error(exception );\n ex.message = `${exception}`;\n\n return [ex, undefined];\n}\n\n/**\n * Builds and Event from a Exception\n * @hidden\n */\nfunction eventFromUnknownInput(\n client,\n stackParser,\n exception,\n hint,\n) {\n const providedMechanism = hint?.data && (hint.data ).mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n const [ex, extras] = getException(client, mechanism, exception, hint);\n\n const event = {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n\n if (extras) {\n event.extra = extras;\n }\n\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, mechanism);\n\n return {\n ...event,\n event_id: hint?.event_id,\n };\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const event = {\n event_id: hint?.event_id,\n level,\n };\n\n if (attachStacktrace && hint?.syntheticException) {\n const frames = parseStackFrames(stackParser, hint.syntheticException);\n if (frames.length) {\n event.exception = {\n values: [\n {\n value: message,\n stacktrace: { frames },\n },\n ],\n };\n addExceptionMechanism(event, { synthetic: true });\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nexport { _enhanceErrorWithSentryInfo, eventFromMessage, eventFromUnknownInput, exceptionFromError, parseStackFrames };\n//# sourceMappingURL=eventbuilder.js.map\n","import { getCurrentScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { debug, consoleSandbox } from './utils/debug-logger.js';\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n debug.enable();\n } else {\n // use `console.warn` rather than `debug.warn` since by non-debug bundles have all `debug.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n client.init();\n return client;\n}\n\n/**\n * Make the given client the current client.\n */\nfunction setCurrentClient(client) {\n getCurrentScope().setClient(client);\n}\n\nexport { initAndBind, setCurrentClient };\n//# sourceMappingURL=sdk.js.map\n","import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_URL_FULL, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes.js';\n\n// Curious about `thismessage:/`? See: https://www.rfc-editor.org/rfc/rfc2557.html\n// > When the methods above do not yield an absolute URI, a base URL\n// > of \"thismessage:/\" MUST be employed. This base URL has been\n// > defined for the sole purpose of resolving relative references\n// > within a multipart/related structure when no other base URI is\n// > specified.\n//\n// We need to provide a base URL to `parseStringToURLObject` because the fetch API gives us a\n// relative URL sometimes.\n//\n// This is the only case where we need to provide a base URL to `parseStringToURLObject`\n// because the relative URL is not valid on its own.\nconst DEFAULT_BASE_URL = 'thismessage:/';\n\n/**\n * Checks if the URL object is relative\n *\n * @param url - The URL object to check\n * @returns True if the URL object is relative, false otherwise\n */\nfunction isURLObjectRelative(url) {\n return 'isRelative' in url;\n}\n\n/**\n * Parses string to a URL object\n *\n * @param url - The URL to parse\n * @returns The parsed URL object or undefined if the URL is invalid\n */\nfunction parseStringToURLObject(url, urlBase) {\n const isRelative = url.indexOf('://') <= 0 && url.indexOf('//') !== 0;\n const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : undefined);\n try {\n // Use `canParse` to short-circuit the URL constructor if it's not a valid URL\n // This is faster than trying to construct the URL and catching the error\n // Node 20+, Chrome 120+, Firefox 115+, Safari 17+\n if ('canParse' in URL && !(URL ).canParse(url, base)) {\n return undefined;\n }\n\n const fullUrlObject = new URL(url, base);\n if (isRelative) {\n // Because we used a fake base URL, we need to return a relative URL object.\n // We cannot return anything about the origin, host, etc. because it will refer to the fake base URL.\n return {\n isRelative,\n pathname: fullUrlObject.pathname,\n search: fullUrlObject.search,\n hash: fullUrlObject.hash,\n };\n }\n return fullUrlObject;\n } catch {\n // empty body\n }\n\n return undefined;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlStringFromUrlObject(url) {\n if (isURLObjectRelative(url)) {\n return url.pathname;\n }\n\n const newUrl = new URL(url);\n newUrl.search = '';\n newUrl.hash = '';\n if (['80', '443'].includes(newUrl.port)) {\n newUrl.port = '';\n }\n if (newUrl.password) {\n newUrl.password = '%filtered%';\n }\n if (newUrl.username) {\n newUrl.username = '%filtered%';\n }\n\n return newUrl.toString();\n}\n\nfunction getHttpSpanNameFromUrlObject(\n urlObject,\n kind,\n request,\n routeName,\n) {\n const method = request?.method?.toUpperCase() ?? 'GET';\n const route = routeName\n ? routeName\n : urlObject\n ? kind === 'client'\n ? getSanitizedUrlStringFromUrlObject(urlObject)\n : urlObject.pathname\n : '/';\n\n return `${method} ${route}`;\n}\n\n/**\n * Takes a parsed URL object and returns a set of attributes for the span\n * that represents the HTTP request for that url. This is used for both server\n * and client http spans.\n *\n * Follows https://opentelemetry.io/docs/specs/semconv/http/.\n *\n * @param urlObject - see {@link parseStringToURLObject}\n * @param kind - The type of HTTP operation (server or client)\n * @param spanOrigin - The origin of the span\n * @param request - The request object, see {@link PartialRequest}\n * @param routeName - The name of the route, must be low cardinality\n * @returns The span name and attributes for the HTTP operation\n */\nfunction getHttpSpanDetailsFromUrlObject(\n urlObject,\n kind,\n spanOrigin,\n request,\n routeName,\n) {\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n };\n\n if (routeName) {\n // This is based on https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name\n attributes[kind === 'server' ? 'http.route' : 'url.template'] = routeName;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n }\n\n if (request?.method) {\n attributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] = request.method.toUpperCase();\n }\n\n if (urlObject) {\n if (urlObject.search) {\n attributes['url.query'] = urlObject.search;\n }\n if (urlObject.hash) {\n attributes['url.fragment'] = urlObject.hash;\n }\n if (urlObject.pathname) {\n attributes['url.path'] = urlObject.pathname;\n if (urlObject.pathname === '/') {\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n }\n }\n\n if (!isURLObjectRelative(urlObject)) {\n attributes[SEMANTIC_ATTRIBUTE_URL_FULL] = urlObject.href;\n if (urlObject.port) {\n attributes['url.port'] = urlObject.port;\n }\n if (urlObject.protocol) {\n attributes['url.scheme'] = urlObject.protocol;\n }\n if (urlObject.hostname) {\n attributes[kind === 'server' ? 'server.address' : 'url.domain'] = urlObject.hostname;\n }\n }\n }\n\n return [getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName), attributes];\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url) {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n return (urlPath.split(/[?#]/, 1) )[0];\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlString(url) {\n const { protocol, host, path } = url;\n\n const filteredHost =\n host\n // Always filter out authority\n ?.replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '') || '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\n/**\n * Strips the content from a data URL, returning a placeholder with the MIME type.\n *\n * Data URLs can be very long (e.g. base64 encoded scripts for Web Workers),\n * with little valuable information, often leading to envelopes getting dropped due\n * to size limit violations. Therefore, we strip data URLs and replace them with a\n * placeholder.\n *\n * @param url - The URL to process\n * @param includeDataPrefix - If true, includes the first 10 characters of the data stream\n * for debugging (e.g., to identify magic bytes like WASM's AGFzbQ).\n * Defaults to true.\n * @returns For data URLs, returns a short format like `data:text/javascript;base64,SGVsbG8gV2... [truncated]`.\n * For non-data URLs, returns the original URL unchanged.\n */\nfunction stripDataUrlContent(url, includeDataPrefix = true) {\n if (url.startsWith('data:')) {\n // Match the MIME type (everything after 'data:' until the first ';' or ',')\n const match = url.match(/^data:([^;,]+)/);\n const mimeType = match ? match[1] : 'text/plain';\n const isBase64 = url.includes(';base64,');\n\n // Find where the actual data starts (after the comma)\n const dataStart = url.indexOf(',');\n let dataPrefix = '';\n if (includeDataPrefix && dataStart !== -1) {\n const data = url.slice(dataStart + 1);\n // Include first 10 chars of data to help identify content (e.g., magic bytes)\n dataPrefix = data.length > 10 ? `${data.slice(0, 10)}... [truncated]` : data;\n }\n\n return `data:${mimeType}${isBase64 ? ',base64' : ''}${dataPrefix ? `,${dataPrefix}` : ''}`;\n }\n return url;\n}\n\nexport { getHttpSpanDetailsFromUrlObject, getSanitizedUrlString, getSanitizedUrlStringFromUrlObject, isURLObjectRelative, parseStringToURLObject, parseUrl, stripDataUrlContent, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","import { parseStringToURLObject, isURLObjectRelative } from './url.js';\n\n/**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\nfunction isSentryRequestUrl(url, client) {\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url, tunnel) {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url, dsn) {\n // Requests to Sentry's ingest endpoint must have a `sentry_key` in the query string\n // This is equivalent to the public_key which is required in the DSN\n // see https://develop.sentry.dev/sdk/overview/#parsing-the-dsn\n // Therefore, a request to the same host and with a `sentry_key` in the query string\n // can be considered a request to the ingest endpoint.\n const urlParts = parseStringToURLObject(url);\n if (!urlParts || isURLObjectRelative(urlParts)) {\n return false;\n }\n\n return dsn ? urlParts.host.includes(dsn.host) && /(^|&|\\?)sentry_key=/.test(urlParts.search) : false;\n}\n\nfunction removeTrailingSlash(str) {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\nexport { isSentryRequestUrl };\n//# sourceMappingURL=isSentryRequestUrl.js.map\n","// By default, we want to infer the IP address, unless this is explicitly set to `null`\n// We do this after all other processing is done\n// If `ip_address` is explicitly set to `null` or a value, we leave it as is\n\n/**\n * @internal\n * @deprecated -- set ip inferral via via SDK metadata options on client instead.\n */\nfunction addAutoIpAddressToUser(objWithMaybeUser) {\n if (objWithMaybeUser.user?.ip_address === undefined) {\n objWithMaybeUser.user = {\n ...objWithMaybeUser.user,\n ip_address: '{{auto}}',\n };\n }\n}\n\n/**\n * @internal\n */\nfunction addAutoIpAddressToSession(session) {\n if ('aggregates' in session) {\n if (session.attrs?.['ip_address'] === undefined) {\n session.attrs = {\n ...session.attrs,\n ip_address: '{{auto}}',\n };\n }\n } else {\n if (session.ipAddress === undefined) {\n session.ipAddress = '{{auto}}';\n }\n }\n}\n\nexport { addAutoIpAddressToSession, addAutoIpAddressToUser };\n//# sourceMappingURL=ipAddress.js.map\n","import { SDK_VERSION } from './version.js';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nfunction applySdkMetadata(options, name, names = [name], source = 'npm') {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n\nexport { applySdkMetadata };\n//# sourceMappingURL=sdkMetadata.js.map\n","/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nfunction debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options?.maxWait ? Math.max(options.maxWait, wait) : 0;\n const setTimeoutImpl = options?.setTimeoutImpl || setTimeout;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeoutImpl(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeoutImpl(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n\nexport { debounce };\n//# sourceMappingURL=debounce.js.map\n","import { getClient, getIsolationScope } from './currentScopes.js';\nimport { consoleSandbox } from './utils/debug-logger.js';\nimport { dateTimestampInSeconds } from './utils/time.js';\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n */\nfunction addBreadcrumb(breadcrumb, hint) {\n const client = getClient();\n const isolationScope = getIsolationScope();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint))\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n\nexport { addBreadcrumb };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { getClient } from '../currentScopes.js';\nimport { defineIntegration } from '../integration.js';\nimport { getOriginalFunction } from '../utils/object.js';\n\nlet originalFunctionToString;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n Function.prototype.toString = function ( ...args) {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() ) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) ;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nconst functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\nexport { functionToStringIntegration };\n//# sourceMappingURL=functiontostring.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getPossibleEventMessages } from '../utils/eventUtils.js';\nimport { getEventDescription } from '../utils/misc.js';\nimport { stringMatchesSomePattern } from '../utils/string.js';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.\n /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker\n /^Can't find variable: gmo$/, // Error from Google Search App https://issuetracker.google.com/issues/396043331\n /^undefined is not an object \\(evaluating 'a\\.[A-Z]'\\)$/, // Random error that happens but not actionable or noticeable to end-users.\n 'can\\'t redefine non-configurable property \"solana\"', // Probably a browser extension or custom browser (Brave) throwing this error\n \"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)\", // Error thrown by GTM, seemingly not affecting end-users\n \"Can't find variable: _AutofillCallbackHandler\", // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/\n /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\\d+, MethodName:simulateEvent, ParamCount:\\d+$/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps\n /^Java exception was raised during method invocation$/, // error from Facebook Mobile browser (https://github.com/getsentry/sentry-javascript/issues/15065)\n];\n\n/** Options for the EventFilters integration */\n\nconst INTEGRATION_NAME = 'EventFilters';\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n * - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n * - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n * - Top level Sentry.init option (`ignoreTransactions`)\n * - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n */\nconst eventFiltersIntegration = defineIntegration((options = {}) => {\n let mergedOptions;\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const clientOptions = client.getOptions();\n mergedOptions = _mergeOptions(options, clientOptions);\n },\n processEvent(event, _hint, client) {\n if (!mergedOptions) {\n const clientOptions = client.getOptions();\n mergedOptions = _mergeOptions(options, clientOptions);\n }\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n});\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n * - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n * - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n * - Top level Sentry.init option (`ignoreTransactions`)\n * - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n *\n * @deprecated this integration was renamed and will be removed in a future major version.\n * Use `eventFiltersIntegration` instead.\n */\nconst inboundFiltersIntegration = defineIntegration(((options = {}) => {\n return {\n ...eventFiltersIntegration(options),\n name: 'InboundFilters',\n };\n}) );\n\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n };\n}\n\nfunction _shouldDropEvent(event, options) {\n if (!event.type) {\n // Filter errors\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isUselessError(event)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${getEventDescription(\n event,\n )}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n } else if (event.type === 'transaction') {\n // Filter transactions\n\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n if (!ignoreErrors?.length) {\n return false;\n }\n\n return getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event, ignoreTransactions) {\n if (!ignoreTransactions?.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n if (!denyUrls?.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n if (!allowUrls?.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n // If there are linked exceptions or exception aggregates we only want to match against the top frame of the \"root\" (the main exception)\n // The root always comes last in linked exceptions\n const rootException = [...(event.exception?.values ?? [])]\n .reverse()\n .find(value => value.mechanism?.parent_id === undefined && value.stacktrace?.frames?.length);\n const frames = rootException?.stacktrace?.frames;\n return frames ? _getLastValidUrl(frames) : null;\n } catch {\n DEBUG_BUILD && debug.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nfunction _isUselessError(event) {\n // We only want to consider events for dropping that actually have recorded exception values.\n if (!event.exception?.values?.length) {\n return false;\n }\n\n return (\n // No top-level message\n !event.message &&\n // There are no exception values that have a stacktrace, a non-generic-Error type or value\n !event.exception.values.some(value => value.stacktrace || (value.type && value.type !== 'Error') || value.value)\n );\n}\n\nexport { eventFiltersIntegration, inboundFiltersIntegration };\n//# sourceMappingURL=eventFilters.js.map\n","import { isInstanceOf } from './is.js';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nfunction applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation,\n parser,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception?.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException ,\n key,\n event.exception.values,\n originalException,\n 0,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error,\n key,\n prevExceptions,\n exception,\n exceptionId,\n) {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key] );\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key] ,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError );\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError ,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception, exceptionId) {\n exception.mechanism = {\n handled: true,\n type: 'auto.core.linked_errors',\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception,\n source,\n exceptionId,\n parentId,\n) {\n exception.mechanism = {\n handled: true,\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\nexport { applyAggregateErrorsToEvent };\n//# sourceMappingURL=aggregate-errors.js.map\n","import { CONSOLE_LEVELS, originalConsoleMethods } from '../utils/debug-logger.js';\nimport { fill } from '../utils/object.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addConsoleInstrumentationHandler(handler) {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole() {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod) {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args) {\n const handlerData = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log?.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\nexport { addConsoleInstrumentationHandler };\n//# sourceMappingURL=console.js.map\n","/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (\n level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n ) ;\n}\n\nexport { severityLevelFromString };\n//# sourceMappingURL=severity.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getFramesFromEvent } from '../utils/stacktrace.js';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && debug.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) ;\n\n/**\n * Deduplication filter.\n */\nconst dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = getFramesFromEvent(currentEvent);\n let previousFrames = getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameA = previousFrames[i];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event) {\n return event.exception?.values?.[0];\n}\n\nexport { _shouldDropEvent, dedupeIntegration };\n//# sourceMappingURL=dedupe.js.map\n","import { getCurrentScope, getIsolationScope } from '../currentScopes.js';\nimport { defineIntegration } from '../integration.js';\nimport { GEN_AI_CONVERSATION_ID_ATTRIBUTE } from '../semanticAttributes.js';\n\nconst INTEGRATION_NAME = 'ConversationId';\n\nconst _conversationIdIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n client.on('spanStart', (span) => {\n const scopeData = getCurrentScope().getScopeData();\n const isolationScopeData = getIsolationScope().getScopeData();\n\n const conversationId = scopeData.conversationId || isolationScopeData.conversationId;\n\n if (conversationId) {\n span.setAttribute(GEN_AI_CONVERSATION_ID_ATTRIBUTE, conversationId);\n }\n });\n },\n };\n}) ;\n\n/**\n * Automatically applies conversation ID from scope to spans.\n *\n * This integration reads the conversation ID from the current or isolation scope\n * and applies it to spans when they start. This ensures the conversation ID is\n * available for all AI-related operations.\n */\nconst conversationIdIntegration = defineIntegration(_conversationIdIntegration);\n\nexport { conversationIdIntegration };\n//# sourceMappingURL=conversationId.js.map\n","/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nfunction getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {\n // NOTE: undefined defaults to 'info' in Sentry\n if (statusCode === undefined) {\n return undefined;\n } else if (statusCode >= 400 && statusCode < 500) {\n return 'warning';\n } else if (statusCode >= 500) {\n return 'error';\n } else {\n return undefined;\n }\n}\n\nexport { getBreadcrumbLogLevelFromHttpStatusCode };\n//# sourceMappingURL=breadcrumb-log-level.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n return 'history' in WINDOW && !!WINDOW.history;\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nconst supportsFetch = _isFetchSupported;\n\nfunction _isFetchSupported() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n // Deno requires a valid URL so '' cannot be used as an argument\n new Request('data:,');\n new Response();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFunction(func) {\n return func && /^function\\s+\\w+\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!_isFetchSupported()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFunction(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow?.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFunction(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD && debug.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!_isFetchSupported()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nexport { isNativeFunction, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsHistory, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { getClient } from '../currentScopes.js';\nimport { isError, isRequest } from '../utils/is.js';\nimport { fill, addNonEnumerableProperty } from '../utils/object.js';\nimport { supportsNativeFetch } from '../utils/supports.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addFetchInstrumentationHandler(\n handler,\n skipNativeFetchCheck,\n) {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck));\n}\n\n/**\n * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.\n * The handler will resolve the request body and emit the actual `endTimestamp`, so that the\n * span can be updated accordingly.\n *\n * Only used internally\n * @hidden\n */\nfunction addFetchEndInstrumentationHandler(handler) {\n const type = 'fetch-body-resolved';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {\n if (skipNativeFetchCheck && !supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function (...args) {\n // We capture the error right here and not in the Promise error callback because Safari (and probably other\n // browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n const virtualError = new Error();\n\n const { method, url } = parseFetchArgs(args);\n const handlerData = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: timestampInSeconds() * 1000,\n // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation\n virtualError,\n headers: getHeadersFromFetchArgs(args),\n };\n\n // if there is no callback, fetch is instrumented directly\n if (!onFetchResolved) {\n triggerHandlers('fetch', {\n ...handlerData,\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n async (response) => {\n if (onFetchResolved) {\n onFetchResolved(response);\n } else {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n }\n\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n error,\n });\n\n if (isError(error) && error.stack === undefined) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n error.stack = virtualError.stack;\n addNonEnumerableProperty(error, 'framesToPop', 1);\n }\n\n // We enhance fetch error messages with hostname information based on the configuration.\n // Possible messages we handle here:\n // * \"Failed to fetch\" (chromium)\n // * \"Load failed\" (webkit)\n // * \"NetworkError when attempting to fetch resource.\" (firefox)\n const client = getClient();\n const enhanceOption = client?.getOptions().enhanceFetchErrorMessages ?? 'always';\n const shouldEnhance = enhanceOption !== false;\n\n if (\n shouldEnhance &&\n error instanceof TypeError &&\n (error.message === 'Failed to fetch' ||\n error.message === 'Load failed' ||\n error.message === 'NetworkError when attempting to fetch resource.')\n ) {\n try {\n const url = new URL(handlerData.fetchData.url);\n const hostname = url.host;\n\n if (enhanceOption === 'always') {\n // Modify the error message directly\n error.message = `${error.message} (${hostname})`;\n } else {\n // Store hostname as non-enumerable property for Sentry-only enhancement\n // This preserves the original error message for third-party packages\n addNonEnumerableProperty(error, '__sentry_fetch_url_host__', hostname);\n }\n } catch {\n // ignore it if errors happen here\n }\n }\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nasync function resolveResponse(res, onFinishedResolving) {\n if (res?.body) {\n const body = res.body;\n const responseReader = body.getReader();\n\n // Define a maximum duration after which we just cancel\n const maxFetchDurationTimeout = setTimeout(\n () => {\n body.cancel().then(null, () => {\n // noop\n });\n },\n 90 * 1000, // 90s\n );\n\n let readingActive = true;\n while (readingActive) {\n let chunkTimeout;\n try {\n // abort reading if read op takes more than 5s\n chunkTimeout = setTimeout(() => {\n body.cancel().then(null, () => {\n // noop on error\n });\n }, 5000);\n\n // This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`\n const { done } = await responseReader.read();\n\n clearTimeout(chunkTimeout);\n\n if (done) {\n onFinishedResolving();\n readingActive = false;\n }\n } catch {\n readingActive = false;\n } finally {\n clearTimeout(chunkTimeout);\n }\n }\n\n clearTimeout(maxFetchDurationTimeout);\n\n responseReader.releaseLock();\n body.cancel().then(null, () => {\n // noop on error\n });\n }\n}\n\nfunction streamHandler(response) {\n // clone response for awaiting stream\n let clonedResponseForResolving;\n try {\n clonedResponseForResolving = response.clone();\n } catch {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n resolveResponse(clonedResponseForResolving, () => {\n triggerHandlers('fetch-body-resolved', {\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n });\n}\n\nfunction hasProp(obj, prop) {\n return !!obj && typeof obj === 'object' && !!(obj )[prop];\n}\n\nfunction getUrlFromResource(resource) {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nfunction parseFetchArgs(fetchArgs) {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [resource, options] = fetchArgs ;\n\n return {\n url: getUrlFromResource(resource),\n method: hasProp(options, 'method')\n ? String(options.method).toUpperCase()\n : // Request object as first argument\n isRequest(resource) && hasProp(resource, 'method')\n ? String(resource.method).toUpperCase()\n : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg ),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\nfunction getHeadersFromFetchArgs(fetchArgs) {\n const [requestArgument, optionsArgument] = fetchArgs;\n\n try {\n if (\n typeof optionsArgument === 'object' &&\n optionsArgument !== null &&\n 'headers' in optionsArgument &&\n optionsArgument.headers\n ) {\n return new Headers(optionsArgument.headers );\n }\n\n if (isRequest(requestArgument)) {\n return new Headers(requestArgument.headers);\n }\n } catch {\n // noop\n }\n\n return;\n}\n\nexport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, parseFetchArgs };\n//# sourceMappingURL=fetch.js.map\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `debug` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // This comment is used to identify this line in the CDN bundle build step and replace this with \"return 'cdn';\"\n /* __SENTRY_SDK_SOURCE__ */ return 'npm';\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isBrowserBundle } from './env.js';\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the `debug` singleton, or b) put your function elsewhere.\n */\n\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @param existingModule module to use for requiring\n * @returns possibly required module\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction loadModule(moduleName, existingModule = module) {\n let mod;\n\n try {\n mod = dynamicRequire(existingModule, moduleName);\n } catch {\n // no-empty\n }\n\n if (!mod) {\n try {\n const { cwd } = dynamicRequire(existingModule, 'process');\n mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`) ;\n } catch {\n // no-empty\n }\n }\n\n return mod;\n}\n\nexport { isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { isNodeEnv } from './node.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Returns true if we are in the browser.\n */\nfunction isBrowser() {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer() {\n const process = (GLOBAL_OBJ ).process;\n return process?.type === 'renderer';\n}\n\nexport { isBrowser };\n//# sourceMappingURL=isBrowser.js.map\n","import { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, withScope, addExceptionTypeValue, addExceptionMechanism, captureException, getLocationHref } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nlet ignoreOnError = 0;\n\n/**\n * @hidden\n */\nfunction shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nfunction ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nfunction wrap(\n fn,\n options\n\n = {},\n) {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n function isFunction(fn) {\n return typeof fn === 'function';\n }\n\n if (!isFunction(fn)) {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = (fn ).__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n // Wrap the function itself\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function ( ...args) {\n try {\n // Also wrap arguments that are themselves functions\n const wrappedArguments = args.map(arg => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n // no need to add a mechanism here, we already add it via an event processor above\n captureException(ex);\n });\n\n throw ex;\n }\n } ;\n\n // Wrap the wrapped function in a proxy, to ensure any other properties of the original function remain available\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property ] = fn[property ];\n }\n }\n } catch {\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n }\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name');\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get() {\n return fn.name;\n },\n });\n }\n } catch {\n // This may throw if e.g. the descriptor does not exist, or a browser does not allow redefining `name`.\n // to save some bytes we simply try-catch this\n }\n\n return sentryWrapped;\n}\n\n/**\n * Get HTTP request data from the current page.\n */\nfunction getHttpRequestData() {\n // grab as much info as exists and add it to the event\n const url = getLocationHref();\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = {\n url,\n headers,\n };\n\n return request;\n}\n\nexport { WINDOW, getHttpRequestData, ignoreNextOnError, shouldIgnoreOnError, wrap };\n//# sourceMappingURL=helpers.js.map\n","import { isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, addExceptionMechanism, isParameterizedString, getClient, normalizeToSize, extractExceptionKeysForMessage, _INTERNAL_enhanceErrorWithSentryInfo, resolvedSyncPromise } from '@sentry/core';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nfunction exceptionFromError(stackParser, ex) {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception = {\n type: extractType(ex),\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\nfunction eventFromPlainObject(\n stackParser,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const client = getClient();\n const normalizeDepth = client?.getOptions().normalizeDepth;\n\n // If we can, we extract an exception from the object properties\n const errorFromProp = getErrorPropertyFromObject(exception);\n\n const extra = {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n };\n\n if (errorFromProp) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, errorFromProp)],\n },\n extra,\n };\n }\n\n const event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n } ,\n ],\n },\n extra,\n } ;\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\nfunction eventFromError(stackParser, ex) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nfunction parseStackFrames(\n stackParser,\n ex,\n) {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const skipLines = getSkipFirstStackStringLines(ex);\n const framesToPop = getPopFirstTopFrames(ex);\n\n try {\n return stackParser(stacktrace, skipLines, framesToPop);\n } catch {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\n/**\n * Certain known React errors contain links that would be falsely\n * parsed as frames. This function check for these errors and\n * returns number of the stack string lines to skip.\n */\nfunction getSkipFirstStackStringLines(ex) {\n if (ex && reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n\n return 0;\n}\n\n/**\n * If error has `framesToPop` property, it means that the\n * creator tells us the first x frames will be useless\n * and should be discarded. Typically error from wrapper function\n * which don't point to the actual location in the developer's code.\n *\n * Example: https://github.com/zertosh/invariant/blob/master/invariant.js#L46\n */\nfunction getPopFirstTopFrames(ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n return 0;\n}\n\n// https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Exception\n// @ts-expect-error - WebAssembly.Exception is a valid class\nfunction isWebAssemblyException(exception) {\n // Check for support\n // @ts-expect-error - WebAssembly.Exception is a valid class\n if (typeof WebAssembly !== 'undefined' && typeof WebAssembly.Exception !== 'undefined') {\n // @ts-expect-error - WebAssembly.Exception is a valid class\n return exception instanceof WebAssembly.Exception;\n } else {\n return false;\n }\n}\n\n/**\n * Extracts from errors what we use as the exception `type` in error events.\n *\n * Usually, this is the `name` property on Error objects but WASM errors need to be treated differently.\n */\nfunction extractType(ex) {\n const name = ex?.name;\n\n // The name for WebAssembly.Exception Errors needs to be extracted differently.\n // Context: https://github.com/getsentry/sentry-javascript/issues/13787\n if (!name && isWebAssemblyException(ex)) {\n // Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;\n return hasTypeInMessage ? ex.message[0] : 'WebAssembly.Exception';\n }\n\n return name;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex) {\n const message = ex?.message;\n\n if (isWebAssemblyException(ex)) {\n // For Node 18, Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n if (Array.isArray(ex.message) && ex.message.length == 2) {\n return ex.message[1];\n }\n return 'wasm exception';\n }\n\n if (!message) {\n return 'No error message';\n }\n\n if (message.error && typeof message.error.message === 'string') {\n return _INTERNAL_enhanceErrorWithSentryInfo(message.error);\n }\n\n return _INTERNAL_enhanceErrorWithSentryInfo(ex);\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nfunction eventFromException(\n stackParser,\n exception,\n hint,\n attachStacktrace,\n) {\n const syntheticException = hint?.syntheticException || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint?.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = hint?.syntheticException || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint?.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nfunction eventFromUnknownInput(\n stackParser,\n exception,\n syntheticException,\n attachStacktrace,\n isUnhandledRejection,\n) {\n let event;\n\n if (isErrorEvent(exception ) && (exception ).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception ;\n return eventFromError(stackParser, errorEvent.error );\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception )) {\n const domException = exception ;\n\n if ('stack' in (exception )) {\n event = eventFromError(stackParser, exception );\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception , syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\nfunction eventFromString(\n stackParser,\n message,\n syntheticException,\n attachStacktrace,\n) {\n const event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n addExceptionMechanism(event, { synthetic: true });\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception,\n { isUnhandledRejection },\n) {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch {\n // ignore errors here\n }\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj) {\n for (const prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (value instanceof Error) {\n return value;\n }\n }\n }\n\n return undefined;\n}\n\nexport { eventFromException, eventFromMessage, eventFromUnknownInput, exceptionFromError, extractMessage, extractType };\n//# sourceMappingURL=eventbuilder.js.map\n","import { Client, getSDKSource, applySdkMetadata, _INTERNAL_flushLogsBuffer, _INTERNAL_flushMetricsBuffer, addAutoIpAddressToSession } from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass BrowserClient extends Client {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const opts = applyDefaultOptions(options);\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n // Only allow IP inferral by Relay if sendDefaultPii is true\n if (opts._metadata?.sdk) {\n opts._metadata.sdk.settings = {\n infer_ip: opts.sendDefaultPii ? 'auto' : 'never',\n // purposefully allowing already passed settings to override the default\n ...opts._metadata.sdk.settings,\n };\n }\n\n super(opts);\n\n const {\n sendDefaultPii,\n sendClientReports,\n enableLogs,\n _experiments,\n enableMetrics: enableMetricsOption,\n } = this._options;\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const enableMetrics = enableMetricsOption ?? _experiments?.enableMetrics ?? true;\n\n // Flush logs and metrics when page becomes hidden (e.g., tab switch, navigation)\n // todo(v11): Remove the experimental flag\n if (WINDOW.document && (sendClientReports || enableLogs || enableMetrics)) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n if (sendClientReports) {\n this._flushOutcomes();\n }\n if (enableLogs) {\n _INTERNAL_flushLogsBuffer(this);\n }\n\n if (enableMetrics) {\n _INTERNAL_flushMetricsBuffer(this);\n }\n }\n });\n }\n\n if (sendDefaultPii) {\n this.on('beforeSendSession', addAutoIpAddressToSession);\n }\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\n/** Exported only for tests. */\nfunction applyDefaultOptions(optionsArg) {\n return {\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...optionsArg,\n };\n}\n\nexport { BrowserClient, applyDefaultOptions };\n//# sourceMappingURL=client.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { GLOBAL_OBJ } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ\n\n;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\n","const getRating = (value, thresholds) => {\n if (value > thresholds[1]) {\n return 'poor';\n }\n if (value > thresholds[0]) {\n return 'needs-improvement';\n }\n return 'good';\n};\n\nconst bindReporter = (\n callback,\n metric,\n thresholds,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue ?? 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n metric.rating = getRating(metric.value, thresholds);\n callback(metric);\n }\n }\n }\n };\n};\n\nexport { bindReporter };\n//# sourceMappingURL=bindReporter.js.map\n","import { WINDOW } from '../../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// sentry-specific change:\n// add optional param to not check for responseStart (see comment below)\nconst getNavigationEntry = (checkResponseStart = true) => {\n const navigationEntry = WINDOW.performance?.getEntriesByType?.('navigation')[0];\n // Check to ensure the `responseStart` property is present and valid.\n // In some cases a zero value is reported by the browser (for\n // privacy/security reasons), and in other cases (bugs) the value is\n // negative or is larger than the current page time. Ignore these cases:\n // - https://github.com/GoogleChrome/web-vitals/issues/137\n // - https://github.com/GoogleChrome/web-vitals/issues/162\n // - https://github.com/GoogleChrome/web-vitals/issues/275\n if (\n // sentry-specific change:\n // We don't want to check for responseStart for our own use of `getNavigationEntry`\n !checkResponseStart ||\n (navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now())\n ) {\n return navigationEntry;\n }\n};\n\nexport { getNavigationEntry };\n//# sourceMappingURL=getNavigationEntry.js.map\n","import { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return navEntry?.activationStart ?? 0;\n};\n\nexport { getActivationStart };\n//# sourceMappingURL=getActivationStart.js.map\n","import { WINDOW } from '../../../types.js';\n\n/**\n * web-vitals 5.1.0 switched listeners to be added on the window rather than the document.\n * Instead of having to check for window/document every time we add a listener, we can use this function.\n */\nfunction addPageListener(type, listener, options) {\n if (WINDOW.document) {\n WINDOW.addEventListener(type, listener, options);\n }\n}\n/**\n * web-vitals 5.1.0 switched listeners to be removed from the window rather than the document.\n * Instead of having to check for window/document every time we remove a listener, we can use this function.\n */\nfunction removePageListener(type, listener, options) {\n if (WINDOW.document) {\n WINDOW.removeEventListener(type, listener, options);\n }\n}\n\nexport { addPageListener, removePageListener };\n//# sourceMappingURL=globalListeners.js.map\n","import { WINDOW } from '../../../types.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { addPageListener, removePageListener } from './globalListeners.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nlet firstHiddenTime = -1;\nconst onHiddenFunctions = new Set();\n\nconst initHiddenTime = () => {\n // If the document is hidden when this code runs, assume it was always\n // hidden and the page was loaded in the background, with the one exception\n // that visibility state is always 'hidden' during prerendering, so we have\n // to ignore that case until prerendering finishes (see: `prerenderingchange`\n // event logic below).\n return WINDOW.document?.visibilityState === 'hidden' && !WINDOW.document?.prerendering ? 0 : Infinity;\n};\n\nconst onVisibilityUpdate = (event) => {\n // Handle changes to hidden state\n if (isPageHidden(event) && firstHiddenTime > -1) {\n // Sentry-specific change: Also call onHidden callbacks for pagehide events\n // to support older browsers (Safari <14.4) that don't properly fire visibilitychange\n if (event.type === 'visibilitychange' || event.type === 'pagehide') {\n for (const onHiddenFunction of onHiddenFunctions) {\n onHiddenFunction();\n }\n }\n\n // If the document is 'hidden' and no previous hidden timestamp has been\n // set (so is infinity), update it based on the current event data.\n if (!isFinite(firstHiddenTime)) {\n // If the event is a 'visibilitychange' event, it means the page was\n // visible prior to this change, so the event timestamp is the first\n // hidden time.\n // However, if the event is not a 'visibilitychange' event, then it must\n // be a 'prerenderingchange' or 'pagehide' event, and the fact that the document is\n // still 'hidden' from the above check means the tab was activated\n // in a background state and so has always been hidden.\n firstHiddenTime = event.type === 'visibilitychange' ? event.timeStamp : 0;\n\n // We no longer need the `prerenderingchange` event listener now we've\n // set an initial init time so remove that\n // (we'll keep the visibilitychange and pagehide ones for onHiddenFunction above)\n removePageListener('prerenderingchange', onVisibilityUpdate, true);\n }\n }\n};\n\nconst getVisibilityWatcher = () => {\n if (WINDOW.document && firstHiddenTime < 0) {\n // Check if we have a previous hidden `visibility-state` performance entry.\n const activationStart = getActivationStart();\n const firstVisibilityStateHiddenTime = !WINDOW.document.prerendering\n ? globalThis.performance\n .getEntriesByType('visibility-state')\n .filter(e => e.name === 'hidden' && e.startTime > activationStart)[0]?.startTime\n : undefined;\n\n // Prefer that, but if it's not available and the document is hidden when\n // this code runs, assume it was hidden since navigation start. This isn't\n // a perfect heuristic, but it's the best we can do until the\n // `visibility-state` performance entry becomes available in all browsers.\n firstHiddenTime = firstVisibilityStateHiddenTime ?? initHiddenTime();\n // Listen for visibility changes so we can handle things like bfcache\n // restores and/or prerender without having to examine individual\n // timestamps in detail and also for onHidden function calls.\n addPageListener('visibilitychange', onVisibilityUpdate, true);\n\n // Sentry-specific change: Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe. This is also required for older\n // Safari versions (<14.4) that we still support.\n addPageListener('pagehide', onVisibilityUpdate, true);\n\n // IMPORTANT: when a page is prerendering, its `visibilityState` is\n // 'hidden', so in order to account for cases where this module checks for\n // visibility during prerendering, an additional check after prerendering\n // completes is also required.\n addPageListener('prerenderingchange', onVisibilityUpdate, true);\n }\n\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n onHidden(cb) {\n onHiddenFunctions.add(cb);\n },\n };\n};\n\n/**\n * Check if the page is hidden, uses the `pagehide` event for older browsers support that we used to have in `onHidden` function.\n * Some browsers we still support (Safari <14.4) don't fully support `visibilitychange`\n * or have known bugs w.r.t the `visibilitychange` event.\n * // TODO (v11): If we decide to drop support for Safari 14.4, we can use the logic from web-vitals 4.2.4\n */\nfunction isPageHidden(event) {\n return event.type === 'pagehide' || WINDOW.document?.visibilityState === 'hidden';\n}\n\nexport { getVisibilityWatcher };\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nconst generateUniqueID = () => {\n return `v5-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\n//# sourceMappingURL=generateUniqueID.js.map\n","import { WINDOW } from '../../../types.js';\nimport { generateUniqueID } from './generateUniqueID.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nconst initMetric = (name, value = -1) => {\n const navEntry = getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document?.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else if (WINDOW.document?.wasDiscarded) {\n navigationType = 'restore';\n } else if (navEntry.type) {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n // Use `entries` type specific for the metric.\n const entries = [];\n\n return {\n name,\n value,\n rating: 'good' , // If needed, will be updated when reported. `const` to keep the type from widening to `string`.\n delta: 0,\n entries,\n id: generateUniqueID(),\n navigationType,\n };\n};\n\nexport { initMetric };\n//# sourceMappingURL=initMetric.js.map\n","/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst instanceMap = new WeakMap();\n\n/**\n * A function that accepts and identity object and a class object and returns\n * either a new instance of that class or an existing instance, if the\n * identity object was previously used.\n */\nfunction initUnique(identityObj, ClassObj) {\n try {\n if (!instanceMap.get(identityObj)) {\n instanceMap.set(identityObj, new ClassObj());\n }\n return instanceMap.get(identityObj) ;\n } catch (e) {\n // --- START Sentry-custom code (try/catch wrapping) ---\n // Fix for cases where identityObj is not a valid key for WeakMap (sometimes a problem in Safari)\n // Just return a new instance without caching it in instanceMap\n return new ClassObj();\n }\n // --- END Sentry-custom code ---\n}\n\nexport { initUnique };\n//# sourceMappingURL=initUnique.js.map\n","/* eslint-disable jsdoc/require-jsdoc */\n/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nclass LayoutShiftManager {constructor() { LayoutShiftManager.prototype.__init.call(this);LayoutShiftManager.prototype.__init2.call(this); }\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n __init() {this._sessionValue = 0;}\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n __init2() {this._sessionEntries = [];}\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _processEntry(entry) {\n // Only count layout shifts without recent user input.\n if (entry.hadRecentInput) return;\n\n const firstSessionEntry = this._sessionEntries[0];\n // This previously used `this._sessionEntries.at(-1)` but that is ES2022. We support ES2021 and earlier.\n const lastSessionEntry = this._sessionEntries[this._sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry\n // and less than 5 seconds after the first entry in the session,\n // include the entry in the current session. Otherwise, start a new\n // session.\n if (\n this._sessionValue &&\n firstSessionEntry &&\n lastSessionEntry &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n this._sessionValue += entry.value;\n this._sessionEntries.push(entry);\n } else {\n this._sessionValue = entry.value;\n this._sessionEntries = [entry];\n }\n\n this._onAfterProcessingUnexpectedShift?.(entry);\n }\n}\n\nexport { LayoutShiftManager };\n//# sourceMappingURL=LayoutShiftManager.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nconst observe = (\n type,\n callback,\n opts = {},\n) => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n // Delay by a microtask to workaround a bug in Safari where the\n // callback is invoked immediately, rather than in a separate task.\n // See: https://github.com/GoogleChrome/web-vitals/issues/277\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => {\n callback(list.getEntries() );\n });\n });\n po.observe({ type, buffered: true, ...opts });\n return po;\n }\n } catch {\n // Do nothing.\n }\n return;\n};\n\nexport { observe };\n//# sourceMappingURL=observe.js.map\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst runOnce = (cb) => {\n let called = false;\n return () => {\n if (!called) {\n cb();\n called = true;\n }\n };\n};\n\nexport { runOnce };\n//# sourceMappingURL=runOnce.js.map\n","import { WINDOW } from '../../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nconst whenActivated = (callback) => {\n if (WINDOW.document?.prerendering) {\n addEventListener('prerenderingchange', () => callback(), true);\n } else {\n callback();\n }\n};\n\nexport { whenActivated };\n//# sourceMappingURL=whenActivated.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { whenActivated } from './lib/whenActivated.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for FCP. See https://web.dev/articles/fcp#what_is_a_good_fcp_score */\nconst FCPThresholds = [1800, 3000];\n\n/**\n * Calculates the [FCP](https://web.dev/articles/fcp) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `paint` performance entry used to determine the value. The reported\n * value is a `DOMHighResTimeStamp`.\n */\nconst onFCP = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FCP');\n let report;\n\n const handleEntries = (entries) => {\n for (const entry of entries) {\n if (entry.name === 'first-contentful-paint') {\n po.disconnect();\n\n // Only report if the page wasn't hidden prior to the first paint.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n // The activationStart reference is used because FCP should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the FCP, this time should be clamped at 0.\n metric.value = Math.max(entry.startTime - getActivationStart(), 0);\n metric.entries.push(entry);\n report(true);\n }\n }\n }\n };\n\n const po = observe('paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges);\n }\n });\n};\n\nexport { FCPThresholds, onFCP };\n//# sourceMappingURL=onFCP.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { initUnique } from './lib/initUnique.js';\nimport { LayoutShiftManager } from './lib/LayoutShiftManager.js';\nimport { observe } from './lib/observe.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { onFCP } from './onFCP.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score */\nconst CLSThresholds = [0.1, 0.25];\n\n/**\n * Calculates the [CLS](https://web.dev/articles/cls) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/articles/cls#layout_shift_score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onCLS = (onReport, opts = {}) => {\n // Start monitoring FCP so we can only report CLS if FCP is also reported.\n // Note: this is done to match the current behavior of CrUX.\n onFCP(\n runOnce(() => {\n const metric = initMetric('CLS', 0);\n let report;\n const visibilityWatcher = getVisibilityWatcher();\n\n const layoutShiftManager = initUnique(opts, LayoutShiftManager);\n\n const handleEntries = (entries) => {\n for (const entry of entries) {\n layoutShiftManager._processEntry(entry);\n }\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (layoutShiftManager._sessionValue > metric.value) {\n metric.value = layoutShiftManager._sessionValue;\n metric.entries = layoutShiftManager._sessionEntries;\n report();\n }\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges);\n\n visibilityWatcher.onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n\n // Queue a task to report (if nothing else triggers a report first).\n // This allows CLS to be reported as soon as FCP fires when\n // `reportAllChanges` is true.\n WINDOW?.setTimeout?.(report);\n }\n }),\n );\n};\n\nexport { CLSThresholds, onCLS };\n//# sourceMappingURL=getCLS.js.map\n","import { observe } from '../observe.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries) => {\n entries.forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nconst getInteractionCount = () => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nconst initInteractionCountPolyfill = () => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } );\n};\n\nexport { getInteractionCount, initInteractionCountPolyfill };\n//# sourceMappingURL=interactionCountPolyfill.js.map\n","import { getInteractionCount } from './polyfills/interactionCountPolyfill.js';\n\n/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n// Used to store the interaction count after a bfcache restore, since p98\n// interaction latencies should only consider the current navigation.\nlet prevInteractionCount = 0;\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = () => {\n return getInteractionCount() - prevInteractionCount;\n};\n\n/**\n *\n */\nclass InteractionManager {constructor() { InteractionManager.prototype.__init.call(this);InteractionManager.prototype.__init2.call(this); }\n /**\n * A list of longest interactions on the page (by latency) sorted so the\n * longest one is first. The list is at most MAX_INTERACTIONS_TO_CONSIDER\n * long.\n */\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n __init() {this._longestInteractionList = [];}\n\n /**\n * A mapping of longest interactions by their interaction ID.\n * This is used for faster lookup.\n */\n // eslint-disable-next-line @sentry-internal/sdk/no-class-field-initializers, @typescript-eslint/explicit-member-accessibility\n __init2() {this._longestInteractionMap = new Map();}\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility, jsdoc/require-jsdoc\n _resetInteractions() {\n prevInteractionCount = getInteractionCount();\n this._longestInteractionList.length = 0;\n this._longestInteractionMap.clear();\n }\n\n /**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _estimateP98LongestInteraction() {\n const candidateInteractionIndex = Math.min(\n this._longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return this._longestInteractionList[candidateInteractionIndex];\n }\n\n /**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _processEntry(entry) {\n this._onBeforeProcessingEntry?.(entry);\n\n // Skip further processing for entries that cannot be INP candidates.\n if (!(entry.interactionId || entry.entryType === 'first-input')) return;\n\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = this._longestInteractionList.at(-1);\n\n let interaction = this._longestInteractionMap.get(entry.interactionId);\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n interaction ||\n this._longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n // If the above conditions are false, `minLongestInteraction` will be set.\n entry.duration > minLongestInteraction._latency\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (interaction) {\n // If the new entry has a longer duration, replace the old entries,\n // otherwise add to the array.\n if (entry.duration > interaction._latency) {\n interaction.entries = [entry];\n interaction._latency = entry.duration;\n } else if (entry.duration === interaction._latency && entry.startTime === interaction.entries[0].startTime) {\n interaction.entries.push(entry);\n }\n } else {\n interaction = {\n id: entry.interactionId,\n entries: [entry],\n _latency: entry.duration,\n };\n this._longestInteractionMap.set(interaction.id, interaction);\n this._longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n this._longestInteractionList.sort((a, b) => b._latency - a._latency);\n if (this._longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) {\n const removedInteractions = this._longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER);\n\n for (const interaction of removedInteractions) {\n this._longestInteractionMap.delete(interaction.id);\n }\n }\n\n // Call any post-processing on the interaction\n this._onAfterProcessingINPCandidate?.(interaction);\n }\n }\n}\n\nexport { InteractionManager };\n//# sourceMappingURL=InteractionManager.js.map\n","import { WINDOW } from '../../../types.js';\nimport { addPageListener, removePageListener } from './globalListeners.js';\nimport { runOnce } from './runOnce.js';\n\n/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Runs the passed callback during the next idle period, or immediately\n * if the browser's visibility state is (or becomes) hidden.\n */\nconst whenIdleOrHidden = (cb) => {\n const rIC = WINDOW.requestIdleCallback || WINDOW.setTimeout;\n\n // If the document is hidden, run the callback immediately, otherwise\n // race an idle callback with the next `visibilitychange` event.\n if (WINDOW.document?.visibilityState === 'hidden') {\n cb();\n } else {\n // eslint-disable-next-line no-param-reassign\n cb = runOnce(cb);\n addPageListener('visibilitychange', cb, { once: true, capture: true });\n // sentry: we use pagehide instead of directly listening to visibilitychange\n // because some browsers we still support (Safari <14.4) don't fully support\n // `visibilitychange` or have known bugs w.r.t the `visibilitychange` event.\n // TODO(v11): remove this once we drop support for Safari <14.4\n addPageListener('pagehide', cb, { once: true, capture: true });\n rIC(() => {\n cb();\n // Remove the above event listener since no longer required.\n // See: https://github.com/GoogleChrome/web-vitals/issues/622\n removePageListener('visibilitychange', cb, { capture: true });\n // TODO(v11): remove this once we drop support for Safari <14.4\n removePageListener('pagehide', cb, { capture: true });\n });\n }\n};\n\nexport { whenIdleOrHidden };\n//# sourceMappingURL=whenIdleOrHidden.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { initUnique } from './lib/initUnique.js';\nimport { InteractionManager } from './lib/InteractionManager.js';\nimport { observe } from './lib/observe.js';\nimport { initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill.js';\nimport { whenActivated } from './lib/whenActivated.js';\nimport { whenIdleOrHidden } from './lib/whenIdleOrHidden.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score */\nconst INPThresholds = [200, 500];\n\n// The default `durationThreshold` used across this library for observing\n// `event` entries via PerformanceObserver.\nconst DEFAULT_DURATION_THRESHOLD = 40;\n\n/**\n * Calculates the [INP](https://web.dev/articles/inp) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed\n * to control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 will not\n * be reported. To avoid reporting no interactions in these cases, the library\n * will fall back to the input delay of the first interaction. Note that this\n * will not affect your 75th percentile INP value unless that value is also\n * less than 40 (well below the recommended\n * [good](https://web.dev/articles/inp#what_is_a_good_inp_score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onINP = (onReport, opts = {}) => {\n // Return if the browser doesn't support all APIs needed to measure INP.\n if (!(globalThis.PerformanceEventTiming && 'interactionId' in PerformanceEventTiming.prototype)) {\n return;\n }\n\n const visibilityWatcher = getVisibilityWatcher();\n\n whenActivated(() => {\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report;\n\n const interactionManager = initUnique(opts, InteractionManager);\n\n const handleEntries = (entries) => {\n // Queue the `handleEntries()` callback in the next idle task.\n // This is needed to increase the chances that all event entries that\n // occurred between the user interaction and the next paint\n // have been dispatched. Note: there is currently an experiment\n // running in Chrome (EventTimingKeypressAndCompositionInteractionId)\n // 123+ that if rolled out fully may make this no longer necessary.\n whenIdleOrHidden(() => {\n for (const entry of entries) {\n interactionManager._processEntry(entry);\n }\n\n const inp = interactionManager._estimateP98LongestInteraction();\n\n if (inp && inp._latency !== metric.value) {\n metric.value = inp._latency;\n metric.entries = inp.entries;\n report();\n }\n });\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold ?? DEFAULT_DURATION_THRESHOLD,\n });\n\n report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n visibilityWatcher.onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n }\n });\n};\n\nexport { INPThresholds, onINP };\n//# sourceMappingURL=getINP.js.map\n","/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nclass LCPEntryManager {\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility, jsdoc/require-jsdoc\n _processEntry(entry) {\n this._onBeforeProcessingEntry?.(entry);\n }\n}\n\nexport { LCPEntryManager };\n//# sourceMappingURL=LCPEntryManager.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { addPageListener, removePageListener } from './lib/globalListeners.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { initUnique } from './lib/initUnique.js';\nimport { LCPEntryManager } from './lib/LCPEntryManager.js';\nimport { observe } from './lib/observe.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { whenActivated } from './lib/whenActivated.js';\nimport { whenIdleOrHidden } from './lib/whenIdleOrHidden.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */\nconst LCPThresholds = [2500, 4000];\n\n/**\n * Calculates the [LCP](https://web.dev/articles/lcp) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called any time a new `largest-contentful-paint`\n * performance entry is dispatched, or once the final value of the metric has\n * been determined.\n */\nconst onLCP = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const lcpEntryManager = initUnique(opts, LCPEntryManager);\n\n const handleEntries = (entries) => {\n // If reportAllChanges is set then call this function for each entry,\n // otherwise only consider the last one.\n if (!opts.reportAllChanges) {\n // eslint-disable-next-line no-param-reassign\n entries = entries.slice(-1);\n }\n\n for (const entry of entries) {\n lcpEntryManager._processEntry(entry);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was prerendered. But in cases\n // where `activationStart` occurs after the LCP, this time should be\n // clamped at 0.\n metric.value = Math.max(entry.startTime - getActivationStart(), 0);\n metric.entries = [entry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges);\n\n // Ensure this logic only runs once, since it can be triggered from\n // any of three different event listeners below.\n const stopListening = runOnce(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n report(true);\n });\n\n // Need a separate wrapper to ensure the `runOnce` function above is\n // common for all three functions\n const stopListeningWrapper = (event) => {\n if (event.isTrusted) {\n // Wrap the listener in an idle callback so it's run in a separate\n // task to reduce potential INP impact.\n // https://github.com/GoogleChrome/web-vitals/issues/383\n whenIdleOrHidden(stopListening);\n removePageListener(event.type, stopListeningWrapper, {\n capture: true,\n });\n }\n };\n\n // Stop listening after input or visibilitychange.\n // Note: while scrolling is an input that stops LCP observation, it's\n // unreliable since it can be programmatically generated.\n // See: https://github.com/GoogleChrome/web-vitals/issues/75\n for (const type of ['keydown', 'click', 'visibilitychange']) {\n addPageListener(type, stopListeningWrapper, {\n capture: true,\n });\n }\n }\n });\n};\n\nexport { LCPThresholds, onLCP };\n//# sourceMappingURL=getLCP.js.map\n","import { debug, getFunctionName } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { onCLS } from './web-vitals/getCLS.js';\nimport { onINP } from './web-vitals/getINP.js';\nimport { onLCP } from './web-vitals/getLCP.js';\nimport { observe } from './web-vitals/lib/observe.js';\nimport { onTTFB } from './web-vitals/onTTFB.js';\n\nconst handlers = {};\nconst instrumented = {};\n\nlet _previousCls;\nlet _previousLcp;\nlet _previousTtfb;\nlet _previousInp;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nfunction addClsInstrumentationHandler(\n callback,\n stopOnCallback = false,\n) {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nfunction addLcpInstrumentationHandler(\n callback,\n stopOnCallback = false,\n) {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a TTFD metric is available.\n */\nfunction addTtfbInstrumentationHandler(callback) {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addInpInstrumentationHandler(callback) {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addPerformanceInstrumentationHandler(\n type,\n callback,\n) {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers?.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n debug.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls() {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n // We want the callback to be called whenever the CLS value updates.\n // By default, the callback is only called when the tab goes to the background.\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentLcp() {\n return onLCP(\n metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n },\n // We want the callback to be called whenever the LCP value updates.\n // By default, the callback is only called when the tab goes to the background.\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentTtfb() {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp() {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type,\n callback,\n instrumentFn,\n previousValue,\n stopOnCallback = false,\n) {\n addHandler(type, callback);\n\n let stopListening;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type) {\n const options = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type, handler) {\n handlers[type] = handlers[type] || [];\n handlers[type].push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type,\n callback,\n stopListening,\n) {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n\n/**\n * Check if a PerformanceEntry is a PerformanceEventTiming by checking for the `duration` property.\n */\nfunction isPerformanceEventTiming(entry) {\n return 'duration' in entry;\n}\n\nexport { addClsInstrumentationHandler, addInpInstrumentationHandler, addLcpInstrumentationHandler, addPerformanceInstrumentationHandler, addTtfbInstrumentationHandler, isPerformanceEventTiming };\n//# sourceMappingURL=instrument.js.map\n","import { addHandler, maybeInstrument, triggerHandlers, fill, addNonEnumerableProperty, uuid4 } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID;\nlet lastCapturedEventType;\nlet lastCapturedEventTargetId;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addClickKeypressInstrumentationHandler(handler) {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nfunction instrumentDOM() {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target) => {\n const globalObject = WINDOW ;\n const proto = globalObject[target]?.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto?.hasOwnProperty?.('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function ( type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = (this.__sentry_instrumentation_handlers__ =\n this.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener) {\n return function ( type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = this.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete this.__sentry_instrumentation_handlers__;\n }\n }\n } catch {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event) {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target )._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType, target) {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target?.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler,\n globalListener = false,\n) {\n return (event) => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event) {\n try {\n return event.target ;\n } catch {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n\nexport { addClickKeypressInstrumentationHandler, instrumentDOM };\n//# sourceMappingURL=dom.js.map\n","import { addHandler, maybeInstrument, triggerHandlers, supportsHistory, fill } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nlet lastHref;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addHistoryInstrumentationHandler(handler) {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\n/**\n * Exported just for testing\n */\nfunction instrumentHistory() {\n // The `popstate` event may also be triggered on `pushState`, but it may not always reliably be emitted by the browser\n // Which is why we also monkey-patch methods below, in addition to this\n WINDOW.addEventListener('popstate', () => {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n\n if (from === to) {\n return;\n }\n\n const handlerData = { from, to } ;\n triggerHandlers('history', handlerData);\n });\n\n // Just guard against this not being available, in weird environments\n if (!supportsHistory()) {\n return;\n }\n\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n const from = lastHref;\n\n // Ensure the URL is absolute\n // this can be either a path, then it is relative to the current origin\n // or a full URL of the current origin - other origins are not allowed\n // See: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#url\n // coerce to string (this is what pushState does)\n const to = getAbsoluteUrl(String(url));\n\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n\n if (from === to) {\n return originalHistoryFunction.apply(this, args);\n }\n\n const handlerData = { from, to } ;\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nfunction getAbsoluteUrl(urlOrPath) {\n try {\n const url = new URL(urlOrPath, WINDOW.location.origin);\n return url.toString();\n } catch {\n // fallback, just do nothing\n return urlOrPath;\n }\n}\n\nexport { addHistoryInstrumentationHandler, instrumentHistory };\n//# sourceMappingURL=history.js.map\n","import { isNativeFunction, debug } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './types.js';\n\n/**\n * We generally want to use window.fetch / window.setTimeout.\n * However, in some cases this may be wrapped (e.g. by Zone.js for Angular),\n * so we try to get an unpatched version of this from a sandboxed iframe.\n */\n\nconst cachedImplementations = {};\n\n/**\n * Get the native implementation of a browser function.\n *\n * This can be used to ensure we get an unwrapped version of a function, in cases where a wrapped function can lead to problems.\n *\n * The following methods can be retrieved:\n * - `setTimeout`: This can be wrapped by e.g. Angular, causing change detection to be triggered.\n * - `fetch`: This can be wrapped by e.g. ad-blockers, causing an infinite loop when a request is blocked.\n */\nfunction getNativeImplementation(\n name,\n) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n\n let impl = WINDOW[name] ;\n\n // Fast path to avoid DOM I/O\n if (isNativeFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(WINDOW) );\n }\n\n const document = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow?.[name]) {\n impl = contentWindow[name] ;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n // Could not create sandbox iframe, just use window.xxx\n DEBUG_BUILD && debug.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `, e);\n }\n }\n\n // Sanity check: This _should_ not happen, but if it does, we just skip caching...\n // This can happen e.g. in tests where fetch may not be available in the env, or similar.\n if (!impl) {\n return impl;\n }\n\n return (cachedImplementations[name] = impl.bind(WINDOW) );\n}\n\n/** Clear a cached implementation. */\nfunction clearCachedImplementation(name) {\n cachedImplementations[name] = undefined;\n}\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nfunction fetch(...rest) {\n return getNativeImplementation('fetch')(...rest);\n}\n\n/**\n * Get an unwrapped `setTimeout` method.\n * This ensures that even if e.g. Angular wraps `setTimeout`, we get the native implementation,\n * avoiding triggering change detection.\n */\nfunction setTimeout(...rest) {\n return getNativeImplementation('setTimeout')(...rest);\n}\n\nexport { clearCachedImplementation, fetch, getNativeImplementation, setTimeout };\n//# sourceMappingURL=getNativeImplementation.js.map\n","import { addHandler, maybeInstrument, timestampInSeconds, isString, triggerHandlers } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addXhrInstrumentationHandler(handler) {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nfunction instrumentXHR() {\n if (!(WINDOW ).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.open = new Proxy(xhrproto.open, {\n apply(\n originalOpen,\n xhrOpenThisArg,\n xhrOpenArgArray\n\n,\n ) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your XHR call did not\n // have a stack trace. If you are using HttpClient integration,\n // this is the expected behavior, as we are using this virtual error to capture\n // the location of your XHR call, and group your HttpClient events accordingly.\n const virtualError = new Error();\n\n const startTimestamp = timestampInSeconds() * 1000;\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : undefined;\n const url = parseXhrUrlArg(xhrOpenArgArray[1]);\n\n if (!method || !url) {\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n }\n\n xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n xhrOpenThisArg.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (xhrOpenThisArg.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhrOpenThisArg.status;\n } catch {\n /* do nothing */\n }\n\n const handlerData = {\n endTimestamp: timestampInSeconds() * 1000,\n startTimestamp,\n xhr: xhrOpenThisArg,\n virtualError,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === 'function') {\n xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, {\n apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) {\n onreadystatechangeHandler();\n return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray);\n },\n });\n } else {\n xhrOpenThisArg.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, {\n apply(\n originalSetRequestHeader,\n setRequestHeaderThisArg,\n setRequestHeaderArgArray,\n ) {\n const [header, value] = setRequestHeaderArgArray;\n\n const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray);\n },\n });\n\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.send = new Proxy(xhrproto.send, {\n apply(originalSend, sendThisArg, sendArgArray) {\n const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(sendThisArg, sendArgArray);\n }\n\n if (sendArgArray[0] !== undefined) {\n sentryXhrData.body = sendArgArray[0];\n }\n\n const handlerData = {\n startTimestamp: timestampInSeconds() * 1000,\n xhr: sendThisArg,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(sendThisArg, sendArgArray);\n },\n });\n}\n\n/**\n * Parses the URL argument of a XHR method to a string.\n *\n * See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open#url\n * url: A string or any other object with a stringifier — including a URL object — that provides the URL of the resource to send the request to.\n *\n * @param url - The URL argument of an XHR method\n * @returns The parsed URL string or undefined if the URL is invalid\n */\nfunction parseXhrUrlArg(url) {\n if (isString(url)) {\n return url;\n }\n\n try {\n // If the passed in argument is not a string, it should have a `toString` method as a stringifier.\n // If that fails, we just return undefined (like in IE11 where URL is not available)\n return (url ).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n\nexport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler, instrumentXHR };\n//# sourceMappingURL=xhr.js.map\n","import { debug } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\n\n// Symbol used by e.g. the Replay integration to store original body on Request objects\nconst ORIGINAL_REQ_BODY = Symbol.for('sentry__originalRequestBody');\n\n/**\n * Serializes FormData.\n *\n * This is a bit simplified, but gives us a decent estimate.\n * This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'.\n *\n */\nfunction serializeFormData(formData) {\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\n/** Get the string representation of a body. */\nfunction getBodyString(body, _debug = debug) {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof URLSearchParams) {\n return [body.toString()];\n }\n\n if (body instanceof FormData) {\n return [serializeFormData(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch (error) {\n DEBUG_BUILD && _debug.error(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && _debug.log('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/**\n * Parses the fetch arguments to extract the request payload.\n *\n * In case of a Request object, this function attempts to retrieve the original body by looking for a Sentry-patched symbol.\n */\nfunction getFetchRequestArgBody(fetchArgs = []) {\n // Second argument with body options takes precedence\n if (fetchArgs.length >= 2 && fetchArgs[1] && typeof fetchArgs[1] === 'object' && 'body' in fetchArgs[1]) {\n return (fetchArgs[1] ).body;\n }\n\n if (fetchArgs.length >= 1 && fetchArgs[0] instanceof Request) {\n const request = fetchArgs[0];\n /* The Request interface's body is a ReadableStream, which we cannot directly access.\n Some integrations (e.g. Replay) patch the Request object to store the original body. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n const originalBody = (request )[ORIGINAL_REQ_BODY];\n if (originalBody !== undefined) {\n return originalBody;\n }\n\n return undefined; // Fall back to returning undefined (as we don't want to return a ReadableStream)\n }\n\n return undefined;\n}\n\n/**\n * Parses XMLHttpRequest response headers into a Record.\n * Extracted from replay internals to be reusable.\n */\nfunction parseXhrResponseHeaders(xhr) {\n let headers;\n try {\n headers = xhr.getAllResponseHeaders();\n } catch (error) {\n DEBUG_BUILD && debug.error(error, 'Failed to get xhr response headers', xhr);\n return {};\n }\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc, line) => {\n const [key, value] = line.split(': ') ;\n if (value) {\n acc[key.toLowerCase()] = value;\n }\n return acc;\n }, {});\n}\n\nexport { ORIGINAL_REQ_BODY, getBodyString, getFetchRequestArgBody, parseXhrResponseHeaders, serializeFormData };\n//# sourceMappingURL=networkUtils.js.map\n","import { createTransport, makePromiseBuffer } from '@sentry/core';\nimport { getNativeImplementation, clearCachedImplementation } from '@sentry-internal/browser-utils';\n\nconst DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE = 40;\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeImplementation('fetch'),\n) {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n async function makeRequest(request) {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'strict-origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. when finishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n try {\n // Note: We do not need to suppress tracing here, because we are using the native fetch, instead of our wrapped one.\n const response = await nativeFetch(options.url, requestOptions);\n\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n } catch (e) {\n clearCachedImplementation('fetch');\n throw e;\n } finally {\n pendingBodySize -= requestSize;\n pendingCount--;\n }\n }\n\n return createTransport(\n options,\n makeRequest,\n makePromiseBuffer(options.bufferSize || DEFAULT_BROWSER_TRANSPORT_BUFFER_SIZE),\n );\n}\n\nexport { makeFetchTransport };\n//# sourceMappingURL=fetch.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { createStackParser, UNKNOWN_FUNCTION } from '@sentry/core';\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename, func, lineno, colno) {\n const frame = {\n filename,\n function: func === '' ? UNKNOWN_FUNCTION : func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// This regex matches frames that have no function name (ie. are at the top level of a module).\n// For example \"at http://localhost:5000//script.js:1:126\"\n// Frames _with_ function names usually look as follows: \"at commitLayoutEffects (react-dom.development.js:23426:1)\"\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\n\n// This regex matches all the frames that have a function name.\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\n\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// Matches stack frames with data URIs instead of filename so we can still get the function name\n// Example: \"at dynamicFn (data:application/javascript,export function dynamicFn() {...\"\nconst chromeDataUriRegex = /at (.+?) ?\\(data:(.+?),/;\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn = line => {\n const dataUriMatch = line.match(chromeDataUriRegex);\n if (dataUriMatch) {\n return {\n filename: ``,\n function: dataUriMatch[1],\n };\n }\n\n // If the stack line has no function name, we need to parse it differently\n const noFnParts = chromeRegexNoFnName.exec(line) ;\n\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(filename, UNKNOWN_FUNCTION, +line, +col);\n }\n\n const parts = chromeRegex.exec(line) ;\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nconst chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko = line => {\n const parts = geckoREgex.exec(line) ;\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst geckoStackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs = line => {\n const parts = winjsRegex.exec(line) ;\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst winjsStackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10 = line => {\n const parts = opera10Regex.exec(line) ;\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera10StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11 = line => {\n const parts = opera11Regex.exec(line) ;\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nconst opera11StackLineParser = [OPERA11_PRIORITY, opera11];\n\nconst defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser];\n\nconst defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func, filename) => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? (func.split('@')[0] ) : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser };\n//# sourceMappingURL=stack-parsers.js.map\n","import { defineIntegration, addConsoleInstrumentationHandler, addFetchInstrumentationHandler, getClient, safeJoin, severityLevelFromString, addBreadcrumb, debug, htmlTreeAsString, getComponentName, getBreadcrumbLogLevelFromHttpStatusCode, parseUrl, getEventDescription } from '@sentry/core';\nimport { addClickKeypressInstrumentationHandler, addXhrInstrumentationHandler, addHistoryInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n // TODO(v11): Remove this functionality and use `consoleIntegration` from @sentry/core instead.\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) ;\n\nconst breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client) {\n return function addSentryBreadcrumb(event) {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creates a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client,\n dom,\n) {\n return function _innerDomBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n debug.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event ;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client) {\n return function _consoleBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client) {\n return function _xhrBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data = {\n method,\n url,\n status_code,\n };\n\n const hint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'xhr',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint );\n\n addBreadcrumb(breadcrumb, hint);\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client) {\n return function _fetchBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n ({\n method: handlerData.fetchData.method,\n url: handlerData.fetchData.url,\n });\n\n if (handlerData.error) {\n const data = handlerData.fetchData;\n const hint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n } ;\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint );\n\n addBreadcrumb(breadcrumb, hint);\n } else {\n const response = handlerData.response ;\n const data = {\n ...handlerData.fetchData,\n status_code: response?.status,\n };\n\n handlerData.fetchData.request_body_size;\n handlerData.fetchData.response_body_size;\n response?.status;\n\n const hint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint );\n\n addBreadcrumb(breadcrumb, hint);\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client) {\n return function _historyBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom?.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event) {\n return !!event && !!(event ).target;\n}\n\nexport { breadcrumbsIntegration };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { defineIntegration, fill, getFunctionName, getOriginalFunction } from '@sentry/core';\nimport { WINDOW, wrap } from '../helpers.js';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'BrowserApiErrors';\n\nconst _browserApiErrorsIntegration = ((options = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n unregisterOriginalCallbacks: false,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(target => _wrapEventTarget(target, _options));\n }\n },\n };\n}) ;\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n */\nconst browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\nfunction _wrapTimeFunction(original) {\n return function ( ...args) {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n handled: false,\n type: `auto.browser.browserapierrors.${getFunctionName(original)}`,\n },\n });\n return original.apply(this, args);\n };\n}\n\nfunction _wrapRAF(original) {\n return function ( callback) {\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'auto.browser.browserapierrors.requestAnimationFrame',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend) {\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n fill(xhr, prop, function (original) {\n const wrapOptions = {\n mechanism: {\n data: {\n handler: getFunctionName(original),\n },\n handled: false,\n type: `auto.browser.browserapierrors.xhr.${prop}`,\n },\n };\n\n // If Instrument integration has been called before BrowserApiErrors, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target, integrationOptions) {\n const globalObject = WINDOW ;\n const proto = globalObject[target]?.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto?.hasOwnProperty?.('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function ( eventName, fn, options) {\n try {\n if (isEventListenerObject(fn)) {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'auto.browser.browserapierrors.handleEvent',\n },\n });\n }\n } catch {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n if (integrationOptions.unregisterOriginalCallbacks) {\n unregisterOriginalCallback(this, eventName, fn);\n }\n\n return original.apply(this, [\n eventName,\n wrap(fn, {\n mechanism: {\n data: {\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'auto.browser.browserapierrors.addEventListener',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(proto, 'removeEventListener', function (originalRemoveEventListener)\n\n {\n return function ( eventName, fn, options) {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n try {\n const originalEventHandler = (fn ).__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, fn, options);\n };\n });\n}\n\nfunction isEventListenerObject(obj) {\n return typeof (obj ).handleEvent === 'function';\n}\n\nfunction unregisterOriginalCallback(target, eventName, fn) {\n if (\n target &&\n typeof target === 'object' &&\n 'removeEventListener' in target &&\n typeof target.removeEventListener === 'function'\n ) {\n target.removeEventListener(eventName, fn);\n }\n}\n\nexport { browserApiErrorsIntegration };\n//# sourceMappingURL=browserapierrors.js.map\n","import { defineIntegration, debug, startSession, captureSession } from '@sentry/core';\nimport { addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * When added, automatically creates sessions which allow you to track adoption and crashes (crash free rate) in your Releases in Sentry.\n * More information: https://docs.sentry.io/product/releases/health/\n *\n * Note: In order for session tracking to work, you need to set up Releases: https://docs.sentry.io/product/releases/\n */\nconst browserSessionIntegration = defineIntegration(() => {\n return {\n name: 'BrowserSession',\n setupOnce() {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD &&\n debug.warn('Using the `browserSessionIntegration` in non-browser environments is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n },\n };\n});\n\nexport { browserSessionIntegration };\n//# sourceMappingURL=browsersession.js.map\n","import { defineIntegration, addGlobalErrorInstrumentationHandler, getClient, captureEvent, debug, addGlobalUnhandledRejectionInstrumentationHandler, isPrimitive, getLocationHref, UNKNOWN_FUNCTION, isString, stripDataUrlContent } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) ;\n\nconst globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\nfunction _installGlobalOnErrorHandler(client) {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event = _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.global_handlers.onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client) {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.global_handlers.onunhandledrejection',\n },\n });\n });\n}\n\n/**\n *\n */\nfunction _getUnhandledRejectionError(error) {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in (error )) {\n return (error ).reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n if ('detail' in (error ) && 'reason' in (error ).detail) {\n return (error ).detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason) {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\nfunction _enhanceEventWithInitialFrame(\n event,\n url,\n line,\n column,\n) {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = column;\n const lineno = line;\n const filename = getFilenameFromUrl(url) ?? getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: UNKNOWN_FUNCTION,\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n DEBUG_BUILD && debug.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions() {\n const client = getClient();\n const options = client?.getOptions() || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nfunction getFilenameFromUrl(url) {\n if (!isString(url) || url.length === 0) {\n return undefined;\n }\n\n // Strip data URL content to avoid long base64 strings in stack frames\n // (e.g. when initializing a Worker with a base64 encoded script)\n // Don't include data prefix for filenames as it's not useful for stack traces\n // Wrap with < > to indicate it's a placeholder\n if (url.startsWith('data:')) {\n return `<${stripDataUrlContent(url, false)}>`;\n }\n\n return url;\n}\n\nexport { _eventFromRejectionWithPrimitive, _getUnhandledRejectionError, globalHandlersIntegration };\n//# sourceMappingURL=globalhandlers.js.map\n","import { defineIntegration } from '@sentry/core';\nimport { WINDOW, getHttpRequestData } from '../helpers.js';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nconst httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext',\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n const headers = {\n ...reqData.headers,\n ...event.request?.headers,\n };\n\n event.request = {\n ...reqData,\n ...event.request,\n headers,\n };\n },\n };\n});\n\nexport { httpContextIntegration };\n//# sourceMappingURL=httpcontext.js.map\n","import { defineIntegration, applyAggregateErrorsToEvent } from '@sentry/core';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) ;\n\n/**\n * Aggregrate linked errors in an event.\n */\nconst linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\nexport { linkedErrorsIntegration };\n//# sourceMappingURL=linkederrors.js.map\n","import { consoleSandbox, getLocationHref } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * Returns true if the SDK is running in an embedded browser extension.\n * Stand-alone browser extensions (which do not share the same data as the main browser page) are fine.\n */\nfunction checkAndWarnIfIsEmbeddedBrowserExtension() {\n if (_isEmbeddedBrowserExtension()) {\n if (DEBUG_BUILD) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(\n '[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',\n );\n });\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction _isEmbeddedBrowserExtension() {\n if (typeof WINDOW.window === 'undefined') {\n // No need to show the error if we're not in a browser window environment (e.g. service workers)\n return false;\n }\n\n const _window = WINDOW ;\n\n // Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine\n // see: https://github.com/getsentry/sentry-javascript/issues/12668\n if (_window.nw) {\n return false;\n }\n\n const extensionObject = _window['chrome'] || _window['browser'];\n\n if (!extensionObject?.runtime?.id) {\n return false;\n }\n\n const href = getLocationHref();\n const extensionProtocols = ['chrome-extension', 'moz-extension', 'ms-browser-extension', 'safari-web-extension'];\n\n // Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage\n const isDedicatedExtensionPage =\n WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}://`));\n\n return !isDedicatedExtensionPage;\n}\n\nexport { checkAndWarnIfIsEmbeddedBrowserExtension };\n//# sourceMappingURL=detectBrowserExtension.js.map\n","import { inboundFiltersIntegration, functionToStringIntegration, conversationIdIntegration, dedupeIntegration, getIntegrationsToSetup, stackParserFromStackParserOptions, initAndBind } from '@sentry/core';\nimport { BrowserClient } from './client.js';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs.js';\nimport { browserApiErrorsIntegration } from './integrations/browserapierrors.js';\nimport { browserSessionIntegration } from './integrations/browsersession.js';\nimport { globalHandlersIntegration } from './integrations/globalhandlers.js';\nimport { httpContextIntegration } from './integrations/httpcontext.js';\nimport { linkedErrorsIntegration } from './integrations/linkederrors.js';\nimport { spotlightBrowserIntegration } from './integrations/spotlight.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\nimport { checkAndWarnIfIsEmbeddedBrowserExtension } from './utils/detectBrowserExtension.js';\n\n/** Get the default integrations for the browser SDK. */\nfunction getDefaultIntegrations(_options) {\n /**\n * Note: Please make sure this stays in sync with Angular SDK, which re-exports\n * `getDefaultIntegrations` but with an adjusted set of integrations.\n */\n return [\n // TODO(v11): Replace with `eventFiltersIntegration` once we remove the deprecated `inboundFiltersIntegration`\n // eslint-disable-next-line deprecation/deprecation\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n conversationIdIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n browserSessionIntegration(),\n ];\n}\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nfunction init(options = {}) {\n const shouldDisableBecauseIsBrowserExtenstion =\n !options.skipBrowserExtensionCheck && checkAndWarnIfIsEmbeddedBrowserExtension();\n\n let defaultIntegrations =\n options.defaultIntegrations == null ? getDefaultIntegrations() : options.defaultIntegrations;\n\n const clientOptions = {\n ...options,\n enabled: shouldDisableBecauseIsBrowserExtenstion ? false : options.enabled,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup({\n integrations: options.integrations,\n defaultIntegrations,\n }),\n transport: options.transport || makeFetchTransport,\n };\n return initAndBind(BrowserClient, clientOptions);\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction forceLoad() {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction onLoad(callback) {\n callback();\n}\n\nexport { forceLoad, getDefaultIntegrations, init, onLoad };\n//# sourceMappingURL=sdk.js.map\n","import { GLOBAL_OBJ, normalize, fill, htmlTreeAsString, browserPerformanceTimeOrigin, debug as debug$1, severityLevelFromString, captureException, addBreadcrumb, uuid4, getClient, getLocationHref, getCurrentScope, getActiveSpan, getDynamicSamplingContextFromSpan, isSentryRequestUrl, stringMatchesSomePattern, addEventProcessor, debounce as debounce$1, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, prepareEvent, getIsolationScope, updateRateLimits, isRateLimited, setContext, getRootSpan, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isBrowser, parseSampleRate, consoleSandbox } from '@sentry/core';\nimport { setTimeout as setTimeout$3, addPerformanceInstrumentationHandler, addLcpInstrumentationHandler, addClsInstrumentationHandler, addInpInstrumentationHandler, serializeFormData, getFetchRequestArgBody, getBodyString, SENTRY_XHR_DATA_KEY, parseXhrResponseHeaders, addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nconst WINDOW = GLOBAL_OBJ ;\n\nconst REPLAY_SESSION_KEY = 'sentryReplaySession';\nconst REPLAY_EVENT_NAME = 'replay_event';\nconst UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nconst SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nconst SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms\n\n/** Default flush delays */\nconst DEFAULT_FLUSH_MIN_DELAY = 5000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nconst DEFAULT_FLUSH_MAX_DELAY = 5500;\n\n/* How long to wait for error checkouts */\nconst BUFFER_CHECKOUT_TIME = 60000;\n\nconst RETRY_BASE_INTERVAL = 5000;\nconst RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nconst NETWORK_BODY_MAX_SIZE = 150000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nconst CONSOLE_ARG_MAX_SIZE = 5000;\n\n/* Min. time to wait before we consider something a slow click. */\nconst SLOW_CLICK_THRESHOLD = 3000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nconst SLOW_CLICK_SCROLL_TIMEOUT = 300;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nconst REPLAY_MAX_EVENT_BUFFER_SIZE = 20000000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nconst MIN_REPLAY_DURATION = 4999;\n\n/*\nThe max. allowed value that the minReplayDuration can be set to.\nThis needs to be below 60s, so we don't unintentionally drop buffered replays that are longer than 60s.\n*/\nconst MIN_REPLAY_DURATION_LIMIT = 50000;\n\n/** The max. length of a replay. */\nconst MAX_REPLAY_DURATION = 3600000; // 60 minutes in ms;\n\nvar __defProp$1 = Object.defineProperty;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nvar NodeType$2 = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType$2 || {});\nfunction isElement$1(n2) {\n return n2.nodeType === n2.ELEMENT_NODE;\n}\nfunction isShadowRoot(n2) {\n const host = n2?.host;\n return Boolean(host?.shadowRoot === n2);\n}\nfunction isNativeShadowDom(shadowRoot) {\n return Object.prototype.toString.call(shadowRoot) === \"[object ShadowRoot]\";\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(\" background-clip: text;\") && !cssText.includes(\" -webkit-background-clip: text;\")) {\n cssText = cssText.replace(\n /\\sbackground-clip:\\s*text;/g,\n \" -webkit-background-clip: text; background-clip: text;\"\n );\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3) return cssText;\n const statement = [\"@import\", `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === \"\") {\n statement.push(`layer`);\n } else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(\" \") + \";\";\n}\nfunction stringifyStylesheet(s2) {\n try {\n const rules2 = s2.rules || s2.cssRules;\n return rules2 ? fixBrowserCompatibilityIssuesInCSS(\n Array.from(rules2, stringifyRule).join(\"\")\n ) : null;\n } catch (error) {\n return null;\n }\n}\nfunction fixAllCssProperty(rule) {\n let styles = \"\";\n for (let i2 = 0; i2 < rule.style.length; i2++) {\n const styleDeclaration = rule.style;\n const attribute = styleDeclaration[i2];\n const isImportant = styleDeclaration.getPropertyPriority(attribute);\n styles += `${attribute}:${styleDeclaration.getPropertyValue(attribute)}${isImportant ? ` !important` : \"\"};`;\n }\n return `${rule.selectorText} { ${styles} }`;\n}\nfunction stringifyRule(rule) {\n let importStringified;\n if (isCSSImportRule(rule)) {\n try {\n importStringified = // for same-origin stylesheets,\n // we can access the imported stylesheet rules directly\n stringifyStylesheet(rule.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement\n escapeImportStatement(rule);\n } catch (error) {\n }\n } else if (isCSSStyleRule(rule)) {\n let cssText = rule.cssText;\n const needsSafariColonFix = rule.selectorText.includes(\":\");\n const needsAllFix = typeof rule.style[\"all\"] === \"string\" && rule.style[\"all\"];\n if (needsAllFix) {\n cssText = fixAllCssProperty(rule);\n }\n if (needsSafariColonFix) {\n cssText = fixSafariColons(cssText);\n }\n if (needsSafariColonFix || needsAllFix) {\n return cssText;\n }\n }\n return importStringified || rule.cssText;\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, \"$1\\\\$2\");\n}\nfunction isCSSImportRule(rule) {\n return \"styleSheet\" in rule;\n}\nfunction isCSSStyleRule(rule) {\n return \"selectorText\" in rule;\n}\nclass Mirror {\n constructor() {\n __publicField$1(this, \"idNodeMap\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"nodeMetaMap\", /* @__PURE__ */ new WeakMap());\n }\n getId(n2) {\n if (!n2) return -1;\n const id = this.getMeta(n2)?.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n2) {\n return this.nodeMetaMap.get(n2) || null;\n }\n // removes the node from idNodeMap\n // doesn't remove the node from nodeMetaMap\n removeNodeFromMap(n2) {\n const id = this.getId(n2);\n this.idNodeMap.delete(id);\n if (n2.childNodes) {\n n2.childNodes.forEach(\n (childNode) => this.removeNodeFromMap(childNode)\n );\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n2, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n2);\n this.nodeMetaMap.set(n2, meta);\n }\n replace(id, n2) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta) this.nodeMetaMap.set(n2, meta);\n }\n this.idNodeMap.set(id, n2);\n }\n reset() {\n this.idNodeMap = /* @__PURE__ */ new Map();\n this.nodeMetaMap = /* @__PURE__ */ new WeakMap();\n }\n}\nfunction createMirror$2() {\n return new Mirror();\n}\nfunction shouldMaskInput({\n maskInputOptions,\n tagName,\n type\n}) {\n if (tagName === \"OPTION\") {\n tagName = \"SELECT\";\n }\n return Boolean(\n maskInputOptions[tagName.toLowerCase()] || type && maskInputOptions[type] || type === \"password\" || // Default to \"text\" option for inputs without a \"type\" attribute defined\n tagName === \"INPUT\" && !type && maskInputOptions[\"text\"]\n );\n}\nfunction maskInputValue({\n isMasked,\n element,\n value,\n maskInputFn\n}) {\n let text = value || \"\";\n if (!isMasked) {\n return text;\n }\n if (maskInputFn) {\n text = maskInputFn(text, element);\n }\n return \"*\".repeat(text.length);\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nfunction toUpperCase(str) {\n return str.toUpperCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = \"__rrweb_original__\";\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;\n const pixelBuffer = new Uint32Array(\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n originalGetImageData.call(\n ctx,\n x,\n y,\n Math.min(chunkSize, canvas.width - x),\n Math.min(chunkSize, canvas.height - y)\n ).data.buffer\n );\n if (pixelBuffer.some((pixel) => pixel !== 0)) return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute(\"data-rr-is-password\") ? \"password\" : type ? (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n toLowerCase(type)\n ) : null;\n}\nfunction getInputValue(el, tagName, type) {\n if (tagName === \"INPUT\" && (type === \"radio\" || type === \"checkbox\")) {\n return el.getAttribute(\"value\") || \"\";\n }\n return el.value;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n } catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return match?.[1] ?? null;\n}\nconst cachedImplementations$1 = {};\nfunction getImplementation$1(name) {\n const cached = cachedImplementations$1[name];\n if (cached) {\n return cached;\n }\n const document2 = window.document;\n let impl = window[name];\n if (document2 && typeof document2.createElement === \"function\") {\n try {\n const sandbox = document2.createElement(\"iframe\");\n sandbox.hidden = true;\n document2.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl = // eslint-disable-next-line @typescript-eslint/unbound-method\n contentWindow[name];\n }\n document2.head.removeChild(sandbox);\n } catch (e2) {\n }\n }\n return cachedImplementations$1[name] = impl.bind(\n window\n );\n}\nfunction setTimeout$2(...rest) {\n return getImplementation$1(\"setTimeout\")(...rest);\n}\nfunction clearTimeout$1(...rest) {\n return getImplementation$1(\"clearTimeout\")(...rest);\n}\nfunction getIframeContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n } catch (e2) {\n }\n}\nlet _id = 1;\nconst tagNameRegex = new RegExp(\"[^a-z0-9-_:]\");\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName$1(element) {\n if (element instanceof HTMLFormElement) {\n return \"form\";\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return \"div\";\n }\n return processedTagName;\n}\nfunction extractOrigin(url) {\n let origin = \"\";\n if (url.indexOf(\"//\") > -1) {\n origin = url.split(\"/\").slice(0, 3).join(\"/\");\n } else {\n origin = url.split(\"/\")[0];\n }\n origin = origin.split(\"?\")[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction filterCSSPropertiesFromInlineStyle(cssText, ignoredProperties) {\n if (!cssText || ignoredProperties.size === 0) {\n return cssText;\n }\n try {\n const properties = cssText.split(\";\");\n const filteredProperties = [];\n for (let property of properties) {\n property = property.trim();\n if (!property) continue;\n const colonIndex = property.indexOf(\":\");\n if (colonIndex === -1) {\n filteredProperties.push(property);\n continue;\n }\n const propertyName = property.slice(0, colonIndex).trim();\n if (!ignoredProperties.has(propertyName)) {\n filteredProperties.push(property);\n }\n }\n return filteredProperties.join(\"; \") + (filteredProperties.length > 0 && cssText.endsWith(\";\") ? \";\" : \"\");\n } catch (error) {\n console.warn(\"Error filtering CSS properties:\", error);\n return cssText;\n }\n}\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || \"\").replace(\n URL_IN_CSS_REF,\n (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || \"\";\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === \"/\") {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split(\"/\");\n const parts = filePath.split(\"/\");\n stack.pop();\n for (const part of parts) {\n if (part === \".\") {\n continue;\n } else if (part === \"..\") {\n stack.pop();\n } else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join(\"/\")}${maybeQuote})`;\n }\n );\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === \"\") {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars2;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars2 = match[0];\n pos += chars2.length;\n return chars2;\n }\n return \"\";\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === \",\") {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n } else {\n let descriptorsStr = \"\";\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c2 = attributeValue.charAt(pos);\n if (c2 === \"\") {\n output.push((url + descriptorsStr).trim());\n break;\n } else if (!inParens) {\n if (c2 === \",\") {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n } else if (c2 === \"(\") {\n inParens = true;\n }\n } else {\n if (c2 === \")\") {\n inParens = false;\n }\n }\n descriptorsStr += c2;\n pos += 1;\n }\n }\n }\n return output.join(\", \");\n}\nconst cachedDocument = /* @__PURE__ */ new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === \"\") {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === \"svg\" || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a2 = cachedDocument.get(doc);\n if (!a2) {\n a2 = doc.createElement(\"a\");\n cachedDocument.set(doc, a2);\n }\n if (!customHref) {\n customHref = \"\";\n } else if (customHref.startsWith(\"blob:\") || customHref.startsWith(\"data:\")) {\n return customHref;\n }\n a2.setAttribute(\"href\", customHref);\n return a2.href;\n}\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn, ignoreCSSAttributes) {\n if (!value) {\n return value;\n }\n if (name === \"src\" || name === \"href\" && !(tagName === \"use\" && value[0] === \"#\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"xlink:href\" && value[0] !== \"#\") {\n return absoluteToDoc(doc, value);\n } else if (name === \"background\" && (tagName === \"table\" || tagName === \"td\" || tagName === \"th\")) {\n return absoluteToDoc(doc, value);\n } else if (name === \"srcset\") {\n return getAbsoluteSrcsetString(doc, value);\n } else if (name === \"style\") {\n let processedStyle = absoluteToStylesheet(value, getHref(doc));\n if (ignoreCSSAttributes && ignoreCSSAttributes.size > 0) {\n processedStyle = filterCSSPropertiesFromInlineStyle(\n processedStyle,\n ignoreCSSAttributes\n );\n }\n return processedStyle;\n } else if (tagName === \"object\" && name === \"data\") {\n return absoluteToDoc(doc, value);\n }\n if (typeof maskAttributeFn === \"function\") {\n return maskAttributeFn(name, value, element);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return (tagName === \"video\" || tagName === \"audio\") && name === \"autoplay\";\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n try {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === \"string\") {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n } else {\n for (let eIndex = element.classList.length; eIndex--; ) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n } catch (e2) {\n }\n return false;\n}\nfunction elementClassMatchesRegex(el, regex) {\n for (let eIndex = el.classList.length; eIndex--; ) {\n const className = el.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n return false;\n}\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\n if (!node) return -1;\n if (node.nodeType !== node.ELEMENT_NODE) return -1;\n if (distance > limit) return -1;\n if (matchPredicate(node)) return distance;\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\n}\nfunction createMatchPredicate(className, selector) {\n return (node) => {\n const el = node;\n if (el === null) return false;\n try {\n if (className) {\n if (typeof className === \"string\") {\n if (el.matches(`.${className}`)) return true;\n } else if (elementClassMatchesRegex(el, className)) {\n return true;\n }\n }\n if (selector && el.matches(selector)) return true;\n return false;\n } catch {\n return false;\n }\n };\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\n try {\n const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;\n if (el === null) return false;\n if (el.tagName === \"INPUT\") {\n const autocomplete = el.getAttribute(\"autocomplete\");\n const disallowedAutocompleteValues = [\n \"current-password\",\n \"new-password\",\n \"cc-number\",\n \"cc-exp\",\n \"cc-exp-month\",\n \"cc-exp-year\",\n \"cc-csc\"\n ];\n if (disallowedAutocompleteValues.includes(autocomplete)) {\n return true;\n }\n }\n let maskDistance = -1;\n let unmaskDistance = -1;\n if (maskAllText) {\n unmaskDistance = distanceToMatch(\n el,\n createMatchPredicate(unmaskTextClass, unmaskTextSelector)\n );\n if (unmaskDistance < 0) {\n return true;\n }\n maskDistance = distanceToMatch(\n el,\n createMatchPredicate(maskTextClass, maskTextSelector),\n unmaskDistance >= 0 ? unmaskDistance : Infinity\n );\n } else {\n maskDistance = distanceToMatch(\n el,\n createMatchPredicate(maskTextClass, maskTextSelector)\n );\n if (maskDistance < 0) {\n return false;\n }\n unmaskDistance = distanceToMatch(\n el,\n createMatchPredicate(unmaskTextClass, unmaskTextSelector),\n maskDistance >= 0 ? maskDistance : Infinity\n );\n }\n return maskDistance >= 0 ? unmaskDistance >= 0 ? maskDistance <= unmaskDistance : true : unmaskDistance >= 0 ? false : !!maskAllText;\n } catch (e2) {\n }\n return !!maskAllText;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n } catch (error) {\n return;\n }\n if (readyState !== \"complete\") {\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener(\"load\", () => {\n clearTimeout$1(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = \"about:blank\";\n if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === \"\") {\n setTimeout$2(listener, 0);\n return iframeEl.addEventListener(\"load\", listener);\n }\n iframeEl.addEventListener(\"load\", listener);\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n let fired = false;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n } catch (error) {\n return;\n }\n if (styleSheetLoaded) return;\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, styleSheetLoadTimeout);\n link.addEventListener(\"load\", () => {\n clearTimeout$1(timer);\n fired = true;\n listener();\n });\n}\nfunction serializeNode(n2, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskAttributeFn,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskTextFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n ignoreCSSAttributes\n } = options;\n const rootId = getRootId(doc, mirror2);\n switch (n2.nodeType) {\n case n2.DOCUMENT_NODE:\n if (n2.compatMode !== \"CSS1Compat\") {\n return {\n type: NodeType$2.Document,\n childNodes: [],\n compatMode: n2.compatMode\n // probably \"BackCompat\"\n };\n } else {\n return {\n type: NodeType$2.Document,\n childNodes: []\n };\n }\n case n2.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType$2.DocumentType,\n name: n2.name,\n publicId: n2.publicId,\n systemId: n2.systemId,\n rootId\n };\n case n2.ELEMENT_NODE:\n return serializeElementNode(n2, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskAttributeFn,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n ignoreCSSAttributes\n });\n case n2.TEXT_NODE:\n return serializeTextNode(n2, {\n doc,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId\n });\n case n2.CDATA_SECTION_NODE:\n return {\n type: NodeType$2.CDATA,\n textContent: \"\",\n rootId\n };\n case n2.COMMENT_NODE:\n return {\n type: NodeType$2.Comment,\n textContent: n2.textContent || \"\",\n rootId\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror2) {\n if (!mirror2.hasNode(doc)) return void 0;\n const docId = mirror2.getId(doc);\n return docId === 1 ? void 0 : docId;\n}\nfunction serializeTextNode(n2, options) {\n const {\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId\n } = options;\n const parentTagName = n2.parentNode && n2.parentNode.tagName;\n let textContent = n2.textContent;\n const isStyle = parentTagName === \"STYLE\" ? true : void 0;\n const isScript = parentTagName === \"SCRIPT\" ? true : void 0;\n const isTextarea = parentTagName === \"TEXTAREA\" ? true : void 0;\n if (isStyle && textContent) {\n try {\n if (n2.nextSibling || n2.previousSibling) {\n } else if (n2.parentNode.sheet?.cssRules) {\n textContent = stringifyStylesheet(\n n2.parentNode.sheet\n );\n }\n } catch (err) {\n console.warn(\n `Cannot get CSS styles from text's parentNode. Error: ${err}`,\n n2\n );\n }\n textContent = absoluteToStylesheet(textContent, getHref(options.doc));\n }\n if (isScript) {\n textContent = \"SCRIPT_PLACEHOLDER\";\n }\n const forceMask = needMaskingText(\n n2,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n maskAllText\n );\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\n textContent = maskTextFn ? maskTextFn(textContent, n2.parentElement) : textContent.replace(/[\\S]/g, \"*\");\n }\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\n textContent = maskInputFn ? maskInputFn(textContent, n2.parentNode) : textContent.replace(/[\\S]/g, \"*\");\n }\n if (parentTagName === \"OPTION\" && textContent) {\n const isInputMasked = shouldMaskInput({\n type: null,\n tagName: parentTagName,\n maskInputOptions\n });\n textContent = maskInputValue({\n isMasked: needMaskingText(\n n2,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n isInputMasked\n ),\n element: n2,\n value: textContent,\n maskInputFn\n });\n }\n return {\n type: NodeType$2.Text,\n textContent: textContent || \"\",\n isStyle,\n rootId\n };\n}\nfunction serializeElementNode(n2, options) {\n const {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskInputOptions = {},\n maskAttributeFn,\n maskInputFn,\n dataURLOptions = {},\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement = false,\n rootId,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n ignoreCSSAttributes\n } = options;\n const needBlock = _isBlockedElement(\n n2,\n blockClass,\n blockSelector,\n unblockSelector\n );\n const tagName = getValidTagName$1(n2);\n let attributes2 = {};\n const len = n2.attributes.length;\n for (let i2 = 0; i2 < len; i2++) {\n const attr = n2.attributes[i2];\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes2[attr.name] = transformAttribute(\n doc,\n tagName,\n toLowerCase(attr.name),\n attr.value,\n n2,\n maskAttributeFn,\n ignoreCSSAttributes\n );\n }\n }\n if (tagName === \"link\" && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s2) => {\n return s2.href === n2.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n attributes2.rel = null;\n attributes2.href = null;\n attributes2.crossorigin = null;\n attributes2._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === \"style\" && n2.sheet && // TODO: Currently we only try to get dynamic stylesheet when it is an empty style element\n !(n2.innerText || n2.textContent || \"\").trim().length) {\n const cssText = stringifyStylesheet(\n n2.sheet\n );\n if (cssText) {\n attributes2._cssText = absoluteToStylesheet(cssText, getHref(doc));\n }\n }\n if (tagName === \"input\" || tagName === \"textarea\" || tagName === \"select\" || tagName === \"option\") {\n const el = n2;\n const type = getInputType(el);\n const value = getInputValue(el, toUpperCase(tagName), type);\n const checked = el.checked;\n if (type !== \"submit\" && type !== \"button\" && value) {\n const forceMask = needMaskingText(\n el,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n shouldMaskInput({\n type,\n tagName: toUpperCase(tagName),\n maskInputOptions\n })\n );\n attributes2.value = maskInputValue({\n isMasked: forceMask,\n element: el,\n value,\n maskInputFn\n });\n }\n if (checked) {\n attributes2.checked = checked;\n }\n }\n if (tagName === \"option\") {\n if (n2.selected && !maskInputOptions[\"select\"]) {\n attributes2.selected = true;\n } else {\n delete attributes2.selected;\n }\n }\n if (tagName === \"canvas\" && recordCanvas) {\n if (n2.__context === \"2d\") {\n if (!is2DCanvasBlank(n2)) {\n attributes2.rr_dataURL = n2.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n }\n } else if (!(\"__context\" in n2)) {\n const canvasDataURL = n2.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n const blankCanvas = doc.createElement(\"canvas\");\n blankCanvas.width = n2.width;\n blankCanvas.height = n2.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes2.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === \"img\" && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement(\"canvas\");\n canvasCtx = canvasService.getContext(\"2d\");\n }\n const image = n2;\n const imageSrc = image.currentSrc || image.getAttribute(\"src\") || \"\";\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener(\"load\", recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes2.rr_dataURL = canvasService.toDataURL(\n dataURLOptions.type,\n dataURLOptions.quality\n );\n } catch (err) {\n if (image.crossOrigin !== \"anonymous\") {\n image.crossOrigin = \"anonymous\";\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n return;\n } else {\n console.warn(\n `Cannot inline img src=${imageSrc}! Error: ${err}`\n );\n }\n }\n if (image.crossOrigin === \"anonymous\") {\n priorCrossOrigin ? attributes2.crossOrigin = priorCrossOrigin : image.removeAttribute(\"crossorigin\");\n }\n };\n if (image.complete && image.naturalWidth !== 0) recordInlineImage();\n else image.addEventListener(\"load\", recordInlineImage);\n }\n if (tagName === \"audio\" || tagName === \"video\") {\n attributes2.rr_mediaState = n2.paused ? \"paused\" : \"played\";\n attributes2.rr_mediaCurrentTime = n2.currentTime;\n }\n if (!newlyAddedElement) {\n if (n2.scrollLeft) {\n attributes2.rr_scrollLeft = n2.scrollLeft;\n }\n if (n2.scrollTop) {\n attributes2.rr_scrollTop = n2.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height } = n2.getBoundingClientRect();\n attributes2 = {\n class: attributes2.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`\n };\n }\n if (tagName === \"iframe\" && !keepIframeSrcFn(attributes2.src)) {\n if (!needBlock && !getIframeContentDocument(n2)) {\n attributes2.rr_src = attributes2.src;\n }\n delete attributes2.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName)) isCustomElement = true;\n } catch (e2) {\n }\n return {\n type: NodeType$2.Element,\n tagName,\n attributes: attributes2,\n childNodes: [],\n isSVG: isSVGElement(n2) || void 0,\n needBlock,\n rootId,\n isCustom: isCustomElement\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === void 0 || maybeAttr === null) {\n return \"\";\n } else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType$2.Comment) {\n return true;\n } else if (sn.type === NodeType$2.Element) {\n if (slimDOMOptions.script && // script tag\n (sn.tagName === \"script\" || // (module)preload link\n sn.tagName === \"link\" && (sn.attributes.rel === \"preload\" || sn.attributes.rel === \"modulepreload\") || // prefetch link\n sn.tagName === \"link\" && sn.attributes.rel === \"prefetch\" && typeof sn.attributes.href === \"string\" && extractFileExtension(sn.attributes.href) === \"js\")) {\n return true;\n } else if (slimDOMOptions.headFavicon && (sn.tagName === \"link\" && sn.attributes.rel === \"shortcut icon\" || sn.tagName === \"meta\" && (lowerIfExists(sn.attributes.name).match(\n /^msapplication-tile(image|color)$/\n ) || lowerIfExists(sn.attributes.name) === \"application-name\" || lowerIfExists(sn.attributes.rel) === \"icon\" || lowerIfExists(sn.attributes.rel) === \"apple-touch-icon\" || lowerIfExists(sn.attributes.rel) === \"shortcut icon\"))) {\n return true;\n } else if (sn.tagName === \"meta\") {\n if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === \"pinterest\")) {\n return true;\n } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === \"robots\" || lowerIfExists(sn.attributes.name) === \"googlebot\" || lowerIfExists(sn.attributes.name) === \"bingbot\")) {\n return true;\n } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes[\"http-equiv\"] !== void 0) {\n return true;\n } else if (slimDOMOptions.headMetaAuthorship && (lowerIfExists(sn.attributes.name) === \"author\" || lowerIfExists(sn.attributes.name) === \"generator\" || lowerIfExists(sn.attributes.name) === \"framework\" || lowerIfExists(sn.attributes.name) === \"publisher\" || lowerIfExists(sn.attributes.name) === \"progid\" || lowerIfExists(sn.attributes.property).match(/^article:/) || lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n } else if (slimDOMOptions.headMetaVerification && (lowerIfExists(sn.attributes.name) === \"google-site-verification\" || lowerIfExists(sn.attributes.name) === \"yandex-verification\" || lowerIfExists(sn.attributes.name) === \"csrf-token\" || lowerIfExists(sn.attributes.name) === \"p:domain_verify\" || lowerIfExists(sn.attributes.name) === \"verify-v1\" || lowerIfExists(sn.attributes.name) === \"verification\" || lowerIfExists(sn.attributes.name) === \"shopify-checkout-api-token\")) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n2, options) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild = false,\n inlineStylesheet = true,\n maskInputOptions = {},\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions = {},\n inlineImages = false,\n recordCanvas = false,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout = 5e3,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout = 5e3,\n keepIframeSrcFn = () => false,\n newlyAddedElement = false,\n ignoreCSSAttributes\n } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n2, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n ignoreCSSAttributes\n });\n if (!_serializedNode) {\n console.warn(n2, \"not serialized\");\n return null;\n }\n let id;\n if (mirror2.hasNode(n2)) {\n id = mirror2.getId(n2);\n } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$2.Text && !_serializedNode.isStyle && !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, \"\").length) {\n id = IGNORED_NODE;\n } else {\n id = genId();\n }\n const serializedNode2 = Object.assign(_serializedNode, { id });\n mirror2.add(n2, serializedNode2);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n2);\n }\n let recordChild = !skipChild;\n if (serializedNode2.type === NodeType$2.Element) {\n recordChild = recordChild && !serializedNode2.needBlock;\n const shadowRoot = n2.shadowRoot;\n if (shadowRoot && isNativeShadowDom(shadowRoot))\n serializedNode2.isShadowHost = true;\n }\n if ((serializedNode2.type === NodeType$2.Document || serializedNode2.type === NodeType$2.Element) && recordChild) {\n if (slimDOMOptions.headWhitespace && serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"head\") {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n };\n const childNodes = n2.childNodes ? Array.from(n2.childNodes) : [];\n for (const childN of childNodes) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode2.childNodes.push(serializedChildNode);\n }\n }\n if (isElement$1(n2) && n2.shadowRoot) {\n for (const childN of Array.from(n2.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(n2.shadowRoot) && (serializedChildNode.isShadow = true);\n serializedNode2.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n2.parentNode && isShadowRoot(n2.parentNode) && isNativeShadowDom(n2.parentNode)) {\n serializedNode2.isShadow = true;\n }\n if (serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"iframe\" && !serializedNode2.needBlock) {\n onceIframeLoaded(\n n2,\n () => {\n const iframeDoc = getIframeContentDocument(n2);\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (serializedIframeNode) {\n onIframeLoad(\n n2,\n serializedIframeNode\n );\n }\n }\n },\n iframeLoadTimeout\n );\n }\n if (serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"img\" && !n2.complete && serializedNode2.needBlock) {\n const image = n2;\n const updateImageDimensions = () => {\n if (image.isConnected && !image.complete && onBlockedImageLoad) {\n try {\n const rect = image.getBoundingClientRect();\n if (rect.width > 0 && rect.height > 0) {\n onBlockedImageLoad(image, serializedNode2, rect);\n }\n } catch (error) {\n }\n }\n image.removeEventListener(\"load\", updateImageDimensions);\n };\n if (image.isConnected) {\n image.addEventListener(\"load\", updateImageDimensions);\n }\n }\n if (serializedNode2.type === NodeType$2.Element && serializedNode2.tagName === \"link\" && typeof serializedNode2.attributes.rel === \"string\" && (serializedNode2.attributes.rel === \"stylesheet\" || serializedNode2.attributes.rel === \"preload\" && typeof serializedNode2.attributes.href === \"string\" && extractFileExtension(serializedNode2.attributes.href) === \"css\")) {\n onceStylesheetLoaded(\n n2,\n () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n2, {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (serializedLinkNode) {\n onStylesheetLoad(\n n2,\n serializedLinkNode\n );\n }\n }\n },\n stylesheetLoadTimeout\n );\n }\n if (serializedNode2.type === NodeType$2.Element) {\n delete serializedNode2.needBlock;\n }\n return serializedNode2;\n}\nfunction snapshot(n2, options) {\n const {\n mirror: mirror2 = new Mirror(),\n blockClass = \"rr-block\",\n blockSelector = null,\n unblockSelector = null,\n maskAllText = false,\n maskTextClass = \"rr-mask\",\n unmaskTextClass = null,\n maskTextSelector = null,\n unmaskTextSelector = null,\n inlineStylesheet = true,\n inlineImages = false,\n recordCanvas = false,\n maskAllInputs = false,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOM = false,\n dataURLOptions,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([])\n } = options || {};\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true\n } : maskAllInputs === false ? {} : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === \"all\" ? (\n // if true: set of sensible options that should not throw away any information\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === \"all\",\n // destructive\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true\n }\n ) : slimDOM === false ? {} : slimDOM;\n return serializeNodeWithId(n2, {\n doc: n2,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onBlockedImageLoad,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n ignoreCSSAttributes\n });\n}\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = \"Please stop import mirror directly. Instead of that,\\r\\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\r\\nor you can use record.mirror to access the mirror instance during recording.\";\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n};\nif (typeof window !== \"undefined\" && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === \"map\") {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n}\nfunction throttle$1(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function(...args) {\n const now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n const remaining = wait - (now - previous);\n const context = this;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout$2(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout$1(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(\n target,\n key,\n isRevoked ? d : {\n set(value) {\n setTimeout$1(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n }\n }\n );\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === \"function\") {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original\n }\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n } catch {\n return () => {\n };\n }\n}\nlet nowTimestamp = Date.now;\nif (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {\n nowTimestamp = () => (/* @__PURE__ */ new Date()).getTime();\n}\nfunction getWindowScroll(win) {\n const doc = win.document;\n return {\n left: doc.scrollingElement ? doc.scrollingElement.scrollLeft : win.pageXOffset !== void 0 ? win.pageXOffset : doc?.documentElement.scrollLeft || doc?.body?.parentElement?.scrollLeft || doc?.body?.scrollLeft || 0,\n top: doc.scrollingElement ? doc.scrollingElement.scrollTop : win.pageYOffset !== void 0 ? win.pageYOffset : doc?.documentElement.scrollTop || doc?.body?.parentElement?.scrollTop || doc?.body?.scrollTop || 0\n };\n}\nfunction getWindowHeight() {\n return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;\n}\nfunction getWindowWidth() {\n return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;\n}\nfunction closestElementOfNode$1(node) {\n if (!node) {\n return null;\n }\n try {\n const el = node.nodeType === node.ELEMENT_NODE ? node : node.parentElement;\n return el;\n } catch (error) {\n return null;\n }\n}\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\n if (!node) {\n return false;\n }\n const el = closestElementOfNode$1(node);\n if (!el) {\n return false;\n }\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\n if (!checkAncestors) {\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\n return blockedPredicate(el) && !isUnblocked;\n }\n const blockDistance = distanceToMatch(el, blockedPredicate);\n let unblockDistance = -1;\n if (blockDistance < 0) {\n return false;\n }\n if (unblockSelector) {\n unblockDistance = distanceToMatch(\n el,\n createMatchPredicate(null, unblockSelector)\n );\n }\n if (blockDistance > -1 && unblockDistance < 0) {\n return true;\n }\n return blockDistance < unblockDistance;\n}\nfunction isSerialized(n2, mirror2) {\n return mirror2.getId(n2) !== -1;\n}\nfunction isIgnored(n2, mirror2) {\n return mirror2.getId(n2) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror2) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror2.getId(target);\n if (!mirror2.has(id)) {\n return true;\n }\n if (target.parentNode && target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror2);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill$1(win = window) {\n if (\"NodeList\" in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype.forEach;\n }\n if (\"DOMTokenList\" in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype.forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = (...args) => {\n let node = args[0];\n if (!(0 in args)) {\n throw new TypeError(\"1 argument is required\");\n }\n do {\n if (this === node) {\n return true;\n }\n } while (node = node && node.parentNode);\n return false;\n };\n }\n}\nfunction isSerializedIframe(n2, mirror2) {\n return Boolean(n2.nodeName === \"IFRAME\" && mirror2.getMeta(n2));\n}\nfunction isSerializedStylesheet(n2, mirror2) {\n return Boolean(\n n2.nodeName === \"LINK\" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute(\"rel\") === \"stylesheet\" && mirror2.getMeta(n2)\n );\n}\nfunction hasShadowRoot(n2) {\n return Boolean(n2?.shadowRoot);\n}\nclass StyleSheetMirror {\n constructor() {\n this.id = 1;\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n }\n getId(stylesheet) {\n return this.styleIDMap.get(stylesheet) ?? -1;\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n /**\n * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.\n */\n add(stylesheet, id) {\n if (this.has(stylesheet)) return this.getId(stylesheet);\n let newId;\n if (id === void 0) {\n newId = this.id++;\n } else newId = id;\n this.styleIDMap.set(stylesheet, newId);\n this.idStyleMap.set(newId, stylesheet);\n return newId;\n }\n getStyle(id) {\n return this.idStyleMap.get(id) || null;\n }\n reset() {\n this.styleIDMap = /* @__PURE__ */ new WeakMap();\n this.idStyleMap = /* @__PURE__ */ new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n2) {\n let shadowHost = null;\n if (n2.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE && n2.getRootNode().host)\n shadowHost = n2.getRootNode().host;\n return shadowHost;\n}\nfunction getRootShadowHost(n2) {\n let rootShadowHost = n2;\n let shadowHost;\n while (shadowHost = getShadowHost(rootShadowHost))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n2) {\n const doc = n2.ownerDocument;\n if (!doc) return false;\n const shadowHost = getRootShadowHost(n2);\n return doc.contains(shadowHost);\n}\nfunction inDom(n2) {\n const doc = n2.ownerDocument;\n if (!doc) return false;\n return doc.contains(n2) || shadowHostInDom(n2);\n}\nconst cachedImplementations = {};\nfunction getImplementation(name) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n const document2 = window.document;\n let impl = window[name];\n if (document2 && typeof document2.createElement === \"function\") {\n try {\n const sandbox = document2.createElement(\"iframe\");\n sandbox.hidden = true;\n document2.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl = // eslint-disable-next-line @typescript-eslint/unbound-method\n contentWindow[name];\n }\n document2.head.removeChild(sandbox);\n } catch (e2) {\n }\n }\n return cachedImplementations[name] = impl.bind(\n window\n );\n}\nfunction onRequestAnimationFrame(...rest) {\n return getImplementation(\"requestAnimationFrame\")(...rest);\n}\nfunction setTimeout$1(...rest) {\n return getImplementation(\"setTimeout\")(...rest);\n}\nfunction clearTimeout$2(...rest) {\n return getImplementation(\"clearTimeout\")(...rest);\n}\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\nvar MediaInteractions = /* @__PURE__ */ ((MediaInteractions2) => {\n MediaInteractions2[MediaInteractions2[\"Play\"] = 0] = \"Play\";\n MediaInteractions2[MediaInteractions2[\"Pause\"] = 1] = \"Pause\";\n MediaInteractions2[MediaInteractions2[\"Seeked\"] = 2] = \"Seeked\";\n MediaInteractions2[MediaInteractions2[\"VolumeChange\"] = 3] = \"VolumeChange\";\n MediaInteractions2[MediaInteractions2[\"RateChange\"] = 4] = \"RateChange\";\n return MediaInteractions2;\n})(MediaInteractions || {});\nfunction getIFrameContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n } catch (e2) {\n }\n}\nfunction getIFrameContentWindow(iframe) {\n try {\n return iframe.contentWindow;\n } catch (e2) {\n }\n}\nfunction isNodeInLinkedList(n2) {\n return \"__ln\" in n2;\n}\nclass DoubleLinkedList {\n constructor() {\n this.length = 0;\n this.head = null;\n this.tail = null;\n }\n get(position) {\n if (position >= this.length) {\n throw new Error(\"Position outside of list range\");\n }\n let current = this.head;\n for (let index = 0; index < position; index++) {\n current = current?.next || null;\n }\n return current;\n }\n addNode(n2) {\n const node = {\n value: n2,\n previous: null,\n next: null\n };\n n2.__ln = node;\n if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {\n const current = n2.previousSibling.__ln.next;\n node.next = current;\n node.previous = n2.previousSibling.__ln;\n n2.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {\n const current = n2.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n2.nextSibling.__ln;\n n2.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n } else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n if (node.next === null) {\n this.tail = node;\n }\n this.length++;\n }\n removeNode(n2) {\n const current = n2.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n } else {\n this.tail = null;\n }\n } else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n } else {\n this.tail = current.previous;\n }\n }\n if (n2.__ln) {\n delete n2.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n constructor() {\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.processMutations = (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n };\n this.emit = () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addedIds = /* @__PURE__ */ new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n2) => {\n let ns = n2;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n2) => {\n if (!n2.parentNode || !inDom(n2)) {\n return;\n }\n const parentId = isShadowRoot(n2.parentNode) ? this.mirror.getId(getShadowHost(n2)) : this.mirror.getId(n2.parentNode);\n const nextId = getNextId(n2);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n2);\n }\n const sn = serializeNodeWithId(n2, {\n doc: this.doc,\n mirror: this.mirror,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n maskAllText: this.maskAllText,\n unblockSelector: this.unblockSelector,\n maskTextClass: this.maskTextClass,\n unmaskTextClass: this.unmaskTextClass,\n maskTextSelector: this.maskTextSelector,\n unmaskTextSelector: this.unmaskTextSelector,\n skipChild: true,\n newlyAddedElement: true,\n inlineStylesheet: this.inlineStylesheet,\n maskInputOptions: this.maskInputOptions,\n maskAttributeFn: this.maskAttributeFn,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n dataURLOptions: this.dataURLOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isSerializedIframe(currentN, this.mirror) && !isBlocked(\n currentN,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n )) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(\n currentN\n );\n }\n if (hasShadowRoot(n2)) {\n this.shadowDomManager.addShadowRoot(n2.shadowRoot, this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n if (isBlocked(\n iframe,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n )) {\n return;\n }\n this.iframeManager.attachIframe(iframe, childSn);\n if (iframe.contentWindow) {\n this.canvasManager.addWindow(iframe.contentWindow);\n }\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (link, childSn) => {\n this.stylesheetManager.attachLinkElement(link, childSn);\n },\n onBlockedImageLoad: (_imageEl, serializedNode, { width, height }) => {\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: serializedNode.id,\n attributes: {\n style: {\n width: `${width}px`,\n height: `${height}px`\n }\n }\n }\n ]\n });\n },\n ignoreCSSAttributes: this.ignoreCSSAttributes\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn\n });\n addedIds.add(sn.id);\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n2 of this.movedSet) {\n if (isParentRemoved(this.removes, n2, this.mirror) && !this.movedSet.has(n2.parentNode)) {\n continue;\n }\n pushAdd(n2);\n }\n for (const n2 of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n2) && !isParentRemoved(this.removes, n2, this.mirror)) {\n pushAdd(n2);\n } else if (isAncestorInSet(this.movedSet, n2)) {\n pushAdd(n2);\n } else {\n this.droppedSet.add(n2);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(candidate.value.parentNode);\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n let tailNode = addList.tail;\n while (tailNode) {\n const _node = tailNode;\n tailNode = tailNode.previous;\n if (_node) {\n const parentId = this.mirror.getId(_node.value.parentNode);\n const nextId = getNextId(_node.value);\n if (nextId === -1) continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n } else {\n const unhandledNode = _node.value;\n if (unhandledNode.parentNode && unhandledNode.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = unhandledNode.parentNode.host;\n const parentId2 = this.mirror.getId(shadowHost);\n if (parentId2 !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts.map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value\n })).filter((text) => !addedIds.has(text.id)).filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes.map((attribute) => {\n const { attributes } = attribute;\n if (typeof attributes.style === \"string\") {\n const diffAsStr = JSON.stringify(attribute.styleDiff);\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n if (diffAsStr.length < attributes.style.length) {\n if ((diffAsStr + unchangedAsStr).split(\"var(\").length === attributes.style.split(\"var(\").length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes\n };\n }).filter((attribute) => !addedIds.has(attribute.id)).filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds\n };\n if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = /* @__PURE__ */ new WeakMap();\n this.removes = [];\n this.addedSet = /* @__PURE__ */ new Set();\n this.movedSet = /* @__PURE__ */ new Set();\n this.droppedSet = /* @__PURE__ */ new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n };\n this.processMutation = (m) => {\n if (isIgnored(m.target, this.mirror)) {\n return;\n }\n switch (m.type) {\n case \"characterData\": {\n const value = m.target.textContent;\n if (!isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n ) && value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n this.unmaskTextClass,\n this.unmaskTextSelector,\n this.maskAllText\n ) && value ? this.maskTextFn ? this.maskTextFn(value, closestElementOfNode$1(m.target)) : value.replace(/[\\S]/g, \"*\") : value,\n node: m.target\n });\n }\n break;\n }\n case \"attributes\": {\n const target = m.target;\n let attributeName = m.attributeName;\n let value = m.target.getAttribute(attributeName);\n if (attributeName === \"value\") {\n const type = getInputType(target);\n const tagName = target.tagName;\n value = getInputValue(target, tagName, type);\n const isInputMasked = shouldMaskInput({\n maskInputOptions: this.maskInputOptions,\n tagName,\n type\n });\n const forceMask = needMaskingText(\n m.target,\n this.maskTextClass,\n this.maskTextSelector,\n this.unmaskTextClass,\n this.unmaskTextSelector,\n isInputMasked\n );\n value = maskInputValue({\n isMasked: forceMask,\n element: target,\n value,\n maskInputFn: this.maskInputFn\n });\n }\n if (isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n ) || value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === \"IFRAME\" && attributeName === \"src\" && !this.keepIframeSrcFn(value)) {\n const iframeDoc = getIFrameContentDocument(\n target\n );\n if (!iframeDoc) {\n attributeName = \"rr_src\";\n } else {\n return;\n }\n }\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {}\n };\n this.attributes.push(item);\n this.attributeMap.set(m.target, item);\n }\n if (attributeName === \"type\" && target.tagName === \"INPUT\" && (m.oldValue || \"\").toLowerCase() === \"password\") {\n target.setAttribute(\"data-rr-is-password\", \"true\");\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(\n this.doc,\n toLowerCase(target.tagName),\n toLowerCase(attributeName),\n value,\n target,\n this.maskAttributeFn\n );\n if (attributeName === \"style\") {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc = document.implementation.createHTMLDocument();\n } catch (e2) {\n this.unattachedDoc = this.doc;\n }\n }\n const old = this.unattachedDoc.createElement(\"span\");\n if (m.oldValue) {\n old.setAttribute(\"style\", m.oldValue);\n }\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === \"\") {\n item.styleDiff[pname] = newValue;\n } else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\n } else {\n item._unchangedStyles[pname] = [newValue, newPriority];\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === \"\") {\n item.styleDiff[pname] = false;\n }\n }\n }\n }\n break;\n }\n case \"childList\": {\n if (isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n true\n )) {\n return;\n }\n m.addedNodes.forEach((n2) => this.genAdds(n2, m.target));\n m.removedNodes.forEach((n2) => {\n const nodeId = this.mirror.getId(n2);\n const parentId = isShadowRoot(m.target) ? this.mirror.getId(m.target.host) : this.mirror.getId(m.target);\n if (isBlocked(\n m.target,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n ) || isIgnored(n2, this.mirror) || !isSerialized(n2, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n2)) {\n deepDelete(this.addedSet, n2);\n this.droppedSet.add(n2);\n } else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n2) && this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n2);\n } else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0\n });\n }\n this.mapRemoves.push(n2);\n });\n break;\n }\n }\n };\n this.genAdds = (n2, target) => {\n if (this.processedNodeManager.inOtherBuffer(n2, this)) return;\n if (this.addedSet.has(n2) || this.movedSet.has(n2)) return;\n if (this.mirror.hasNode(n2)) {\n if (isIgnored(n2, this.mirror)) {\n return;\n }\n this.movedSet.add(n2);\n let targetId = null;\n if (target && this.mirror.hasNode(target)) {\n targetId = this.mirror.getId(target);\n }\n if (targetId && targetId !== -1) {\n this.movedMap[moveKey(this.mirror.getId(n2), targetId)] = true;\n }\n } else {\n this.addedSet.add(n2);\n this.droppedSet.delete(n2);\n }\n if (!isBlocked(\n n2,\n this.blockClass,\n this.blockSelector,\n this.unblockSelector,\n false\n )) {\n if (n2.childNodes) {\n n2.childNodes.forEach((childN) => this.genAdds(childN));\n }\n if (hasShadowRoot(n2)) {\n n2.shadowRoot.childNodes.forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n2);\n });\n }\n }\n };\n }\n init(options) {\n [\n \"mutationCb\",\n \"blockClass\",\n \"blockSelector\",\n \"unblockSelector\",\n \"maskAllText\",\n \"maskTextClass\",\n \"unmaskTextClass\",\n \"maskTextSelector\",\n \"unmaskTextSelector\",\n \"inlineStylesheet\",\n \"maskInputOptions\",\n \"maskAttributeFn\",\n \"maskTextFn\",\n \"maskInputFn\",\n \"keepIframeSrcFn\",\n \"recordCanvas\",\n \"inlineImages\",\n \"slimDOMOptions\",\n \"dataURLOptions\",\n \"doc\",\n \"mirror\",\n \"iframeManager\",\n \"stylesheetManager\",\n \"shadowDomManager\",\n \"canvasManager\",\n \"processedNodeManager\",\n \"ignoreCSSAttributes\"\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n2) {\n addsSet.delete(n2);\n n2.childNodes?.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n2, mirror2) {\n if (removes.length === 0) return false;\n return _isParentRemoved(removes, n2, mirror2);\n}\nfunction _isParentRemoved(removes, n2, mirror2) {\n let node = n2.parentNode;\n while (node) {\n const parentId = mirror2.getId(node);\n if (removes.some((r2) => r2.id === parentId)) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}\nfunction isAncestorInSet(set, n2) {\n if (set.size === 0) return false;\n return _isAncestorInSet(set, n2);\n}\nfunction _isAncestorInSet(set, n2) {\n const { parentNode } = n2;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return _isAncestorInSet(set, parentNode);\n}\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = void 0;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = (...rest) => {\n try {\n return cb(...rest);\n } catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return () => {\n };\n }\n throw error;\n }\n };\n return rrwebWrapped;\n};\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if (\"composedPath\" in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n } else if (\"path\" in event && event.path.length) {\n return event.path[0];\n }\n } catch {\n }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n let mutationObserverCtor = window.MutationObserver || /**\n * Some websites may disable MutationObserver by removing it from the window object.\n * If someone is using rrweb to build a browser extention or things like it, they\n * could not change the website's code but can have an opportunity to inject some\n * code before the website executing its JS logic.\n * Then they can do this to store the native MutationObserver:\n * window.__rrMutationObserver = MutationObserver\n */\n window.__rrMutationObserver;\n const angularZoneSymbol = window?.Zone?.__symbol__?.(\"MutationObserver\");\n if (angularZoneSymbol && window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(\n callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\n })\n );\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true\n });\n return observer;\n}\nfunction initMoveObserver({\n mousemoveCb,\n sampling,\n doc,\n mirror: mirror2\n}) {\n if (sampling.mousemove === false) {\n return () => {\n };\n }\n const threshold = typeof sampling.mousemove === \"number\" ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === \"number\" ? sampling.mousemoveCallback : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle$1(\n callbackWrapper(\n (source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(\n positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }),\n source\n );\n positions = [];\n timeBaseline = null;\n }\n ),\n callbackThreshold\n );\n const updatePosition = callbackWrapper(\n throttle$1(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror2.getId(target),\n timeOffset: nowTimestamp() - timeBaseline\n });\n wrappedCb(\n typeof DragEvent !== \"undefined\" && evt instanceof DragEvent ? IncrementalSource.Drag : evt instanceof MouseEvent ? IncrementalSource.MouseMove : IncrementalSource.TouchMove\n );\n }),\n threshold,\n {\n trailing: false\n }\n )\n );\n const handlers = [\n on(\"mousemove\", updatePosition, doc),\n on(\"touchmove\", updatePosition, doc),\n on(\"drag\", updatePosition, doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({\n mouseInteractionCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n sampling\n}) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;\n const handlers = [];\n let currentPointerType = null;\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n let pointerType = null;\n let thisEventKey = eventKey;\n if (\"pointerType\" in event) {\n switch (event.pointerType) {\n case \"mouse\":\n pointerType = PointerTypes.Mouse;\n break;\n case \"touch\":\n pointerType = PointerTypes.Touch;\n break;\n case \"pen\":\n pointerType = PointerTypes.Pen;\n break;\n }\n if (pointerType === PointerTypes.Touch) {\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n thisEventKey = \"TouchStart\";\n } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = \"TouchEnd\";\n }\n } else if (pointerType === PointerTypes.Pen) ;\n } else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if (thisEventKey.startsWith(\"Touch\") && pointerType === PointerTypes.Touch || thisEventKey.startsWith(\"Mouse\") && pointerType === PointerTypes.Mouse) {\n pointerType = null;\n }\n } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e2) {\n return;\n }\n const id = mirror2.getId(target);\n const { clientX, clientY } = e2;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[thisEventKey],\n id,\n x: clientX,\n y: clientY,\n ...pointerType !== null && { pointerType }\n });\n };\n };\n Object.keys(MouseInteractions).filter(\n (key) => Number.isNaN(Number(key)) && !key.endsWith(\"_Departed\") && disableMap[key] !== false\n ).forEach((eventKey) => {\n let eventName = toLowerCase(eventKey);\n const handler = getHandler(eventKey);\n if (window.PointerEvent) {\n switch (MouseInteractions[eventKey]) {\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n eventName = eventName.replace(\n \"mouse\",\n \"pointer\"\n );\n break;\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n return;\n }\n }\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({\n scrollCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n sampling\n}) {\n const updatePosition = callbackWrapper(\n throttle$1(\n callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n if (!target || isBlocked(\n target,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n )) {\n return;\n }\n const id = mirror2.getId(target);\n if (target === doc && doc.defaultView) {\n const scrollLeftTop = getWindowScroll(doc.defaultView);\n scrollCb({\n id,\n x: scrollLeftTop.left,\n y: scrollLeftTop.top\n });\n } else {\n scrollCb({\n id,\n x: target.scrollLeft,\n y: target.scrollTop\n });\n }\n }),\n sampling.scroll || 100\n )\n );\n return on(\"scroll\", updatePosition, doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(\n throttle$1(\n callbackWrapper(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height)\n });\n lastH = height;\n lastW = width;\n }\n }),\n 200\n )\n );\n return on(\"resize\", updateDimension, win);\n}\nconst INPUT_TAGS = [\"INPUT\", \"TEXTAREA\", \"SELECT\"];\nconst lastInputValueMap = /* @__PURE__ */ new WeakMap();\nfunction initInputObserver({\n inputCb,\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n ignoreClass,\n ignoreSelector,\n maskInputOptions,\n maskInputFn,\n sampling,\n userTriggeredOnInput,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector\n}) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const userTriggered = event.isTrusted;\n const tagName = target && toUpperCase(target.tagName);\n if (tagName === \"OPTION\") target = target.parentElement;\n if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(\n target,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n )) {\n return;\n }\n const el = target;\n if (el.classList.contains(ignoreClass) || ignoreSelector && el.matches(ignoreSelector)) {\n return;\n }\n const type = getInputType(target);\n let text = getInputValue(el, tagName, type);\n let isChecked = false;\n const isInputMasked = shouldMaskInput({\n maskInputOptions,\n tagName,\n type\n });\n const forceMask = needMaskingText(\n target,\n maskTextClass,\n maskTextSelector,\n unmaskTextClass,\n unmaskTextSelector,\n isInputMasked\n );\n if (type === \"radio\" || type === \"checkbox\") {\n isChecked = target.checked;\n }\n text = maskInputValue({\n isMasked: forceMask,\n element: target,\n value: text,\n maskInputFn\n });\n cbWithDedup(\n target,\n userTriggeredOnInput ? { text, isChecked, userTriggered } : { text, isChecked }\n );\n const name = target.name;\n if (type === \"radio\" && name && isChecked) {\n doc.querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`).forEach((el2) => {\n if (el2 !== target) {\n const text2 = maskInputValue({\n // share mask behavior of `target`\n isMasked: forceMask,\n element: el2,\n value: getInputValue(el2, tagName, type),\n maskInputFn\n });\n cbWithDedup(\n el2,\n userTriggeredOnInput ? { text: text2, isChecked: !isChecked, userTriggered: false } : { text: text2, isChecked: !isChecked }\n );\n }\n });\n }\n }\n function cbWithDedup(target, v2) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {\n lastInputValueMap.set(target, v2);\n const id = mirror2.getId(target);\n callbackWrapper(inputCb)({\n ...v2,\n id\n });\n }\n }\n const events = sampling.input === \"last\" ? [\"change\"] : [\"input\", \"change\"];\n const handlers = events.map(\n (eventName) => on(eventName, callbackWrapper(eventHandler), doc)\n );\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(\n currentWindow.HTMLInputElement.prototype,\n \"value\"\n );\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, \"value\"],\n [currentWindow.HTMLInputElement.prototype, \"checked\"],\n [currentWindow.HTMLSelectElement.prototype, \"value\"],\n [currentWindow.HTMLTextAreaElement.prototype, \"value\"],\n // Some UI library use selectedIndex to set select value\n [currentWindow.HTMLSelectElement.prototype, \"selectedIndex\"],\n [currentWindow.HTMLOptionElement.prototype, \"selected\"]\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(\n ...hookProperties.map(\n (p) => hookSetter(\n p[0],\n p[1],\n {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false\n // userTriggered to false as this could well be programmatic\n });\n }\n },\n false,\n currentWindow\n )\n )\n );\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if (hasNestedCSSRule(\"CSSGroupingRule\") && childRule.parentRule instanceof CSSGroupingRule || hasNestedCSSRule(\"CSSMediaRule\") && childRule.parentRule instanceof CSSMediaRule || hasNestedCSSRule(\"CSSSupportsRule\") && childRule.parentRule instanceof CSSSupportsRule || hasNestedCSSRule(\"CSSConditionRule\") && childRule.parentRule instanceof CSSConditionRule) {\n const rules2 = Array.from(\n childRule.parentRule.cssRules\n );\n const index = rules2.indexOf(childRule);\n pos.unshift(index);\n } else if (childRule.parentStyleSheet) {\n const rules2 = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules2.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror2, styleMirror) {\n let id, styleId;\n if (!sheet) return {};\n if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);\n else styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror: mirror2, stylesheetManager }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => {\n };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [{ rule, index }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [{ index }]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n let replace;\n if (win.CSSStyleSheet.prototype.replace) {\n replace = win.CSSStyleSheet.prototype.replace;\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replace: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n let replaceSync;\n if (win.CSSStyleSheet.prototype.replaceSync) {\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n replaceSync: text\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n }\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule(\"CSSGroupingRule\")) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n } else {\n if (canMonkeyPatchNestedCSSRule(\"CSSMediaRule\")) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSConditionRule\")) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule(\"CSSSupportsRule\")) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n insertRule: type.prototype.insertRule,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n deleteRule: type.prototype.deleteRule\n };\n type.prototype.insertRule = new Proxy(\n unmodifiedFunctions[typeKey].insertRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index || 0\n // defaults to 0\n ]\n }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n type.prototype.deleteRule = new Proxy(\n unmodifiedFunctions[typeKey].deleteRule,\n {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index] }\n ]\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n }\n );\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n replace && (win.CSSStyleSheet.prototype.replace = replace);\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initAdoptedStyleSheetObserver({\n mirror: mirror2,\n stylesheetManager\n}, host) {\n let hostId = null;\n if (host.nodeName === \"#document\") hostId = mirror2.getId(host);\n else hostId = mirror2.getId(host.host);\n const patchTarget = host.nodeName === \"#document\" ? host.defaultView?.Document : host.ownerDocument?.defaultView?.ShadowRoot;\n const originalPropertyDescriptor = patchTarget?.prototype ? Object.getOwnPropertyDescriptor(\n patchTarget?.prototype,\n \"adoptedStyleSheets\"\n ) : void 0;\n if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n return originalPropertyDescriptor.get?.call(this);\n },\n set(sheets) {\n const result = originalPropertyDescriptor.set?.call(this, sheets);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n } catch (e2) {\n }\n }\n return result;\n }\n });\n return callbackWrapper(() => {\n Object.defineProperty(host, \"adoptedStyleSheets\", {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n get: originalPropertyDescriptor.get,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n set: originalPropertyDescriptor.set\n });\n });\n}\nfunction initStyleDeclarationObserver({\n styleDeclarationCb,\n mirror: mirror2,\n ignoreCSSAttributes,\n stylesheetManager\n}, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [property, value, priority] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return setProperty.apply(thisArg, [property, value, priority]);\n }\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentRule?.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper(\n (target, thisArg, argumentsList) => {\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(\n thisArg.parentRule?.parentStyleSheet,\n mirror2,\n stylesheetManager.styleMirror\n );\n if (id && id !== -1 || styleId && styleId !== -1) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property\n },\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n index: getNestedCSSRulePositions(thisArg.parentRule)\n });\n }\n return target.apply(thisArg, argumentsList);\n }\n )\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({\n mediaInteractionCb,\n blockClass,\n blockSelector,\n unblockSelector,\n mirror: mirror2,\n sampling,\n doc\n}) {\n const handler = callbackWrapper(\n (type) => throttle$1(\n callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target || isBlocked(\n target,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n )) {\n return;\n }\n const { currentTime, volume, muted, playbackRate } = target;\n mediaInteractionCb({\n type,\n id: mirror2.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate\n });\n }),\n sampling.media || 500\n )\n );\n const handlers = [\n on(\"play\", handler(MediaInteractions.Play), doc),\n on(\"pause\", handler(MediaInteractions.Pause), doc),\n on(\"seeked\", handler(MediaInteractions.Seeked), doc),\n on(\"volumechange\", handler(MediaInteractions.VolumeChange), doc),\n on(\"ratechange\", handler(MediaInteractions.RateChange), doc)\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => {\n };\n }\n const handlers = [];\n const fontMap = /* @__PURE__ */ new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace2(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== \"string\",\n descriptors,\n fontSource: typeof source === \"string\" ? source : JSON.stringify(Array.from(new Uint8Array(source)))\n });\n return fontFace;\n };\n const restoreHandler = patch(\n doc.fonts,\n \"add\",\n function(original) {\n return function(fontFace) {\n setTimeout$1(\n callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }),\n 0\n );\n return original.apply(this, [fontFace]);\n };\n }\n );\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initSelectionObserver(param) {\n const {\n doc,\n mirror: mirror2,\n blockClass,\n blockSelector,\n unblockSelector,\n selectionCb\n } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || collapsed && selection?.isCollapsed) return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i2 = 0; i2 < count; i2++) {\n const range = selection.getRangeAt(i2);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(\n startContainer,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n ) || isBlocked(\n endContainer,\n blockClass,\n blockSelector,\n unblockSelector,\n true\n );\n if (blocked) continue;\n ranges.push({\n start: mirror2.getId(startContainer),\n startOffset,\n end: mirror2.getId(endContainer),\n endOffset\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on(\"selectionchange\", updateSelection);\n}\nfunction initCustomElementObserver({\n doc,\n customElementCb\n}) {\n const win = doc.defaultView;\n if (!win || !win.customElements) return () => {\n };\n const restoreHandler = patch(\n win.customElements,\n \"define\",\n function(original) {\n return function(name, constructor, options) {\n try {\n customElementCb({\n define: {\n name\n }\n });\n } catch (e2) {\n }\n return original.apply(this, [name, constructor, options]);\n };\n }\n );\n return restoreHandler;\n}\nfunction initObservers(o2, _hooks = {}) {\n const currentWindow = o2.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n let mutationObserver;\n if (o2.recordDOM) {\n mutationObserver = initMutationObserver(o2, o2.doc);\n }\n const mousemoveHandler = initMoveObserver(o2);\n const mouseInteractionHandler = initMouseInteractionObserver(o2);\n const scrollHandler = initScrollObserver(o2);\n const viewportResizeHandler = initViewportResizeObserver(o2, {\n win: currentWindow\n });\n const inputHandler = initInputObserver(o2);\n const mediaInteractionHandler = initMediaInteractionObserver(o2);\n let styleSheetObserver = () => {\n };\n let adoptedStyleSheetObserver = () => {\n };\n let styleDeclarationObserver = () => {\n };\n let fontObserver = () => {\n };\n if (o2.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o2, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o2, {\n win: currentWindow\n });\n if (o2.collectFonts) {\n fontObserver = initFontObserver(o2);\n }\n }\n const selectionObserver = initSelectionObserver(o2);\n const customElementObserver = initCustomElementObserver(o2);\n const pluginHandlers = [];\n for (const plugin of o2.plugins) {\n pluginHandlers.push(\n plugin.observer(plugin.callback, currentWindow, plugin.options)\n );\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver?.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n adoptedStyleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n selectionObserver();\n customElementObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== \"undefined\";\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(\n typeof window[prop] !== \"undefined\" && // Note: Generally, this check _shouldn't_ be necessary\n // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here\n window[prop].prototype && \"insertRule\" in window[prop].prototype && \"deleteRule\" in window[prop].prototype\n );\n}\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n this.generateIdFn = generateIdFn;\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n }\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n let id = idToRemoteIdMap.get(remoteId);\n if (!id) {\n id = this.generateIdFn();\n idToRemoteIdMap.set(remoteId, id);\n remoteIdToIdMap.set(id, remoteId);\n }\n return id;\n }\n getIds(iframe, remoteId) {\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return remoteId.map(\n (id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap)\n );\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== \"number\") return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId) return -1;\n return remoteId;\n }\n getRemoteIds(iframe, ids) {\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n }\n reset(iframe) {\n if (!iframe) {\n this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();\n this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();\n return;\n }\n this.iframeIdToRemoteIdMap.delete(iframe);\n this.iframeRemoteIdToIdMap.delete(iframe);\n }\n getIdToRemoteIdMap(iframe) {\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n if (!idToRemoteIdMap) {\n idToRemoteIdMap = /* @__PURE__ */ new Map();\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n }\n return idToRemoteIdMap;\n }\n getRemoteIdToIdMap(iframe) {\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n if (!remoteIdToIdMap) {\n remoteIdToIdMap = /* @__PURE__ */ new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\nclass IframeManagerNoop {\n constructor() {\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n }\n addIframe() {\n }\n addLoadListener() {\n }\n attachIframe() {\n }\n}\nclass IframeManager {\n constructor(options) {\n this.iframes = /* @__PURE__ */ new WeakMap();\n this.crossOriginIframeMap = /* @__PURE__ */ new WeakMap();\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = /* @__PURE__ */ new WeakMap();\n this.mutationCb = options.mutationCb;\n this.wrappedEmit = options.wrappedEmit;\n this.stylesheetManager = options.stylesheetManager;\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(\n this.stylesheetManager.styleMirror.generateId.bind(\n this.stylesheetManager.styleMirror\n )\n );\n this.mirror = options.mirror;\n if (this.recordCrossOriginIframes) {\n window.addEventListener(\"message\", this.handleMessage.bind(this));\n }\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n if (iframeEl.contentWindow)\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n this.mutationCb({\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: childSn\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n });\n if (this.recordCrossOriginIframes)\n iframeEl.contentWindow?.addEventListener(\n \"message\",\n this.handleMessage.bind(this)\n );\n this.loadListener?.(iframeEl);\n const iframeDoc = getIFrameContentDocument(iframeEl);\n if (iframeDoc && iframeDoc.adoptedStyleSheets && iframeDoc.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(\n iframeDoc.adoptedStyleSheets,\n this.mirror.getId(iframeDoc)\n );\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== \"rrweb\" || // To filter out the rrweb messages which are forwarded by some sites.\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow) return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl) return;\n const transformedEvent = this.transformCrossOriginEvent(\n iframeEl,\n crossOriginMessageEvent.data.event\n );\n if (transformedEvent)\n this.wrappedEmit(\n transformedEvent,\n crossOriginMessageEvent.data.isCheckout\n );\n }\n transformCrossOriginEvent(iframeEl, e2) {\n switch (e2.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e2.data.node, iframeEl);\n const rootId = e2.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e2.data.node, rootId);\n return {\n timestamp: e2.timestamp,\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: e2.data.node\n }\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true\n }\n };\n }\n case EventType.Meta:\n case EventType.Load:\n case EventType.DomContentLoaded: {\n return false;\n }\n case EventType.Plugin: {\n return e2;\n }\n case EventType.Custom: {\n this.replaceIds(\n e2.data.payload,\n iframeEl,\n [\"id\", \"parentId\", \"previousId\", \"nextId\"]\n );\n return e2;\n }\n case EventType.IncrementalSnapshot: {\n switch (e2.data.source) {\n case IncrementalSource.Mutation: {\n e2.data.adds.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\n \"parentId\",\n \"nextId\",\n \"previousId\"\n ]);\n this.replaceIdOnNode(n2.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n2.node, rootId);\n });\n e2.data.removes.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\"parentId\", \"id\"]);\n });\n e2.data.attributes.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\"id\"]);\n });\n e2.data.texts.forEach((n2) => {\n this.replaceIds(n2, iframeEl, [\"id\"]);\n });\n return e2;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e2.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, [\"id\"]);\n });\n return e2;\n }\n case IncrementalSource.ViewportResize: {\n return false;\n }\n case IncrementalSource.MediaInteraction:\n case IncrementalSource.MouseInteraction:\n case IncrementalSource.Scroll:\n case IncrementalSource.CanvasMutation:\n case IncrementalSource.Input: {\n this.replaceIds(e2.data, iframeEl, [\"id\"]);\n return e2;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e2.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e2.data, iframeEl, [\"styleId\"]);\n return e2;\n }\n case IncrementalSource.Font: {\n return e2;\n }\n case IncrementalSource.Selection: {\n e2.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, [\"start\", \"end\"]);\n });\n return e2;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e2.data, iframeEl, [\"id\"]);\n this.replaceStyleIds(e2.data, iframeEl, [\"styleIds\"]);\n e2.data.styles?.forEach((style) => {\n this.replaceStyleIds(style, iframeEl, [\"styleId\"]);\n });\n return e2;\n }\n }\n }\n }\n return false;\n }\n replace(iframeMirror, obj, iframeEl, keys) {\n for (const key of keys) {\n if (!Array.isArray(obj[key]) && typeof obj[key] !== \"number\") continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(\n iframeEl,\n obj[key]\n );\n } else {\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n }\n }\n return obj;\n }\n replaceIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n }\n replaceStyleIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n }\n replaceIdOnNode(node, iframeEl) {\n this.replaceIds(node, iframeEl, [\"id\", \"rootId\"]);\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.replaceIdOnNode(child, iframeEl);\n });\n }\n }\n patchRootIdOnNode(node, rootId) {\n if (node.type !== NodeType$2.Document && !node.rootId) node.rootId = rootId;\n if (\"childNodes\" in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\n }\n }\n}\nclass ShadowDomManagerNoop {\n init() {\n }\n addShadowRoot() {\n }\n observeAttachShadow() {\n }\n reset() {\n }\n}\nclass ShadowDomManager {\n constructor(options) {\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n this.restoreHandlers = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n this.init();\n }\n init() {\n this.reset();\n this.patchAttachShadow(Element, document);\n }\n addShadowRoot(shadowRoot, doc) {\n if (!isNativeShadowDom(shadowRoot)) return;\n if (this.shadowDoms.has(shadowRoot)) return;\n this.shadowDoms.add(shadowRoot);\n this.bypassOptions.canvasManager.addShadowRoot(shadowRoot);\n const observer = initMutationObserver(\n {\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this\n },\n shadowRoot\n );\n this.restoreHandlers.push(() => observer.disconnect());\n this.restoreHandlers.push(\n initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813\n // scroll is not allowed to pass the boundary, so we need to listen the shadow document\n doc: shadowRoot,\n mirror: this.mirror\n })\n );\n setTimeout$1(() => {\n if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(\n shadowRoot.adoptedStyleSheets,\n this.mirror.getId(shadowRoot.host)\n );\n this.restoreHandlers.push(\n initAdoptedStyleSheetObserver(\n {\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager\n },\n shadowRoot\n )\n );\n }, 0);\n }\n /**\n * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.\n */\n observeAttachShadow(iframeElement) {\n const iframeDoc = getIFrameContentDocument(iframeElement);\n const iframeWindow = getIFrameContentWindow(iframeElement);\n if (!iframeDoc || !iframeWindow) return;\n this.patchAttachShadow(\n iframeWindow.Element,\n iframeDoc\n );\n }\n /**\n * Patch 'attachShadow' to observe newly added shadow doms.\n */\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(\n patch(\n element.prototype,\n \"attachShadow\",\n function(original) {\n return function(option) {\n const shadowRoot = original.call(this, option);\n if (this.shadowRoot && inDom(this))\n manager.addShadowRoot(this.shadowRoot, doc);\n return shadowRoot;\n };\n }\n )\n );\n }\n reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n } catch (e2) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = /* @__PURE__ */ new WeakSet();\n this.bypassOptions.canvasManager.resetShadowRoots();\n }\n}\nvar chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nvar lookup = typeof Uint8Array === \"undefined\" ? [] : new Uint8Array(256);\nfor (var i$1 = 0; i$1 < chars.length; i$1++) {\n lookup[chars.charCodeAt(i$1)] = i$1;\n}\nclass CanvasManagerNoop {\n reset() {\n }\n freeze() {\n }\n unfreeze() {\n }\n lock() {\n }\n unlock() {\n }\n snapshot() {\n }\n addWindow() {\n }\n addShadowRoot() {\n }\n resetShadowRoots() {\n }\n}\nclass StylesheetManager {\n constructor(options) {\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n this.styleMirror = new StyleSheetMirror();\n this.mutationCb = options.mutationCb;\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n }\n attachLinkElement(linkEl, childSn) {\n if (\"_cssText\" in childSn.attributes)\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: childSn.id,\n attributes: childSn.attributes\n }\n ]\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl)) return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0) return;\n const adoptedStyleSheetData = {\n id: hostId,\n styleIds: []\n };\n const styles = [];\n for (const sheet of sheets) {\n let styleId;\n if (!this.styleMirror.has(sheet)) {\n styleId = this.styleMirror.add(sheet);\n styles.push({\n styleId,\n rules: Array.from(sheet.rules || CSSRule, (r2, index) => ({\n rule: stringifyRule(r2),\n index\n }))\n });\n } else styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0) adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = /* @__PURE__ */ new WeakSet();\n }\n // TODO: take snapshot on stylesheet reload by applying event listener\n trackStylesheetInLinkElement(_linkEl) {\n }\n}\nclass ProcessedNodeManager {\n constructor() {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n }\n inOtherBuffer(node, thisBuffer) {\n const buffers = this.nodeMap.get(node);\n return buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer);\n }\n add(node, buffer) {\n if (!this.active) {\n this.active = true;\n onRequestAnimationFrame(() => {\n this.nodeMap = /* @__PURE__ */ new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || /* @__PURE__ */ new Set()).add(buffer));\n }\n destroy() {\n }\n}\nlet wrappedEmit;\nlet _takeFullSnapshot;\ntry {\n if (Array.from([1], (x) => x * 2)[0] !== 2) {\n const cleanFrame = document.createElement(\"iframe\");\n document.body.appendChild(cleanFrame);\n Array.from = cleanFrame.contentWindow?.Array.from || Array.from;\n document.body.removeChild(cleanFrame);\n }\n} catch (err) {\n console.debug(\"Unable to override Array.from\", err);\n}\nconst mirror = createMirror$2();\nfunction record(options = {}) {\n const {\n emit,\n checkoutEveryNms,\n checkoutEveryNth,\n blockClass = \"rr-block\",\n blockSelector = null,\n unblockSelector = null,\n ignoreClass = \"rr-ignore\",\n ignoreSelector = null,\n maskAllText = false,\n maskTextClass = \"rr-mask\",\n unmaskTextClass = null,\n maskTextSelector = null,\n unmaskTextSelector = null,\n inlineStylesheet = true,\n maskAllInputs,\n maskInputOptions: _maskInputOptions,\n slimDOMOptions: _slimDOMOptions,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n maxCanvasSize = null,\n packFn,\n sampling = {},\n dataURLOptions = {},\n mousemoveWait,\n recordDOM = true,\n recordCanvas = false,\n recordCrossOriginIframes = false,\n recordAfter = options.recordAfter === \"DOMContentLoaded\" ? options.recordAfter : \"load\",\n userTriggeredOnInput = false,\n collectFonts = false,\n inlineImages = false,\n plugins,\n keepIframeSrcFn = () => false,\n ignoreCSSAttributes = /* @__PURE__ */ new Set([]),\n errorHandler: errorHandler2,\n onMutation,\n getCanvasManager\n } = options;\n registerErrorHandler(errorHandler2);\n const inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n } catch (e2) {\n passEmitsToParent = true;\n }\n }\n if (inEmittingFrame && !emit) {\n throw new Error(\"emit function is required\");\n }\n if (!inEmittingFrame && !passEmitsToParent) {\n return () => {\n };\n }\n if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true ? {\n color: true,\n date: true,\n \"datetime-local\": true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n radio: true,\n checkbox: true\n } : _maskInputOptions !== void 0 ? _maskInputOptions : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === \"all\" ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n // the following are off for slimDOMOptions === true,\n // as they destroy some (hidden) info:\n headMetaAuthorship: _slimDOMOptions === \"all\",\n headMetaDescKeywords: _slimDOMOptions === \"all\"\n } : _slimDOMOptions ? _slimDOMOptions : {};\n polyfill$1();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e2) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e2 = plugin.eventProcessor(e2);\n }\n }\n if (packFn && // Disable packing events which will be emitted to parent frames.\n !passEmitsToParent) {\n e2 = packFn(e2);\n }\n return e2;\n };\n wrappedEmit = (r2, isCheckout) => {\n const e2 = r2;\n e2.timestamp = nowTimestamp();\n if (mutationBuffers[0]?.isFrozen() && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n emit?.(eventProcessor(e2), isCheckout);\n } else if (passEmitsToParent) {\n const message = {\n type: \"rrweb\",\n event: eventProcessor(e2),\n origin: window.location.origin,\n isCheckout\n };\n window.parent.postMessage(message, \"*\");\n }\n if (e2.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e2;\n incrementalSnapshotCount = 0;\n } else if (e2.type === EventType.IncrementalSnapshot) {\n if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms && lastFullSnapshotEvent && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot2(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n ...m\n }\n });\n };\n const wrappedScrollEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Scroll,\n ...p\n }\n });\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n });\n const wrappedAdoptedStyleSheetEmit = (a2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a2\n }\n });\n const stylesheetManager = new StylesheetManager({\n mutationCb: wrappedMutationEmit,\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit\n });\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === \"boolean\" && __RRWEB_EXCLUDE_IFRAME__ ? new IframeManagerNoop() : new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager,\n recordCrossOriginIframes,\n wrappedEmit\n });\n for (const plugin of plugins || []) {\n if (plugin.getMirror)\n plugin.getMirror({\n nodeMirror: mirror,\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror\n });\n }\n const processedNodeManager = new ProcessedNodeManager();\n const canvasManager = _getCanvasManager(\n getCanvasManager,\n {\n mirror,\n win: window,\n mutationCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p\n }\n }),\n recordCanvas,\n blockClass,\n blockSelector,\n unblockSelector,\n maxCanvasSize,\n sampling: sampling[\"canvas\"],\n dataURLOptions,\n errorHandler: errorHandler2\n }\n );\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === \"boolean\" && __RRWEB_EXCLUDE_SHADOW_DOM__ ? new ShadowDomManagerNoop() : new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n onMutation,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n dataURLOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n stylesheetManager,\n canvasManager,\n keepIframeSrcFn,\n processedNodeManager,\n ignoreCSSAttributes\n },\n mirror\n });\n const takeFullSnapshot2 = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit(\n {\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight()\n }\n },\n isCheckout\n );\n stylesheetManager.reset();\n shadowDomManager.init();\n mutationBuffers.forEach((buf) => buf.lock());\n const node = snapshot(document, {\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n slimDOM: slimDOMOptions,\n dataURLOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n2) => {\n if (isSerializedIframe(n2, mirror)) {\n iframeManager.addIframe(n2);\n }\n if (isSerializedStylesheet(n2, mirror)) {\n stylesheetManager.trackLinkElement(n2);\n }\n if (hasShadowRoot(n2)) {\n shadowDomManager.addShadowRoot(n2.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n if (iframe.contentWindow) {\n canvasManager.addWindow(iframe.contentWindow);\n }\n shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (linkEl, childSn) => {\n stylesheetManager.attachLinkElement(linkEl, childSn);\n },\n onBlockedImageLoad: (_imageEl, serializedNode, { width, height }) => {\n wrappedMutationEmit({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: serializedNode.id,\n attributes: {\n style: {\n width: `${width}px`,\n height: `${height}px`\n }\n }\n }\n ]\n });\n },\n keepIframeSrcFn,\n ignoreCSSAttributes\n });\n if (!node) {\n return console.warn(\"Failed to snapshot the document\");\n }\n wrappedEmit({\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: getWindowScroll(window)\n }\n });\n mutationBuffers.forEach((buf) => buf.unlock());\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n stylesheetManager.adoptStyleSheets(\n document.adoptedStyleSheets,\n mirror.getId(document)\n );\n };\n _takeFullSnapshot = takeFullSnapshot2;\n try {\n const handlers = [];\n const observe = (doc) => {\n return callbackWrapper(initObservers)(\n {\n onMutation,\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions\n }\n }),\n mouseInteractionCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MouseInteraction,\n ...d\n }\n }),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.ViewportResize,\n ...d\n }\n }),\n inputCb: (v2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v2\n }\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p\n }\n }),\n styleSheetRuleCb: (r2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r2\n }\n }),\n styleDeclarationCb: (r2) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r2\n }\n }),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Font,\n ...p\n }\n }),\n selectionCb: (p) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Selection,\n ...p\n }\n });\n },\n customElementCb: (c2) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c2\n }\n });\n },\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordDOM,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n keepIframeSrcFn,\n blockSelector,\n unblockSelector,\n slimDOMOptions,\n dataURLOptions,\n mirror,\n iframeManager,\n stylesheetManager,\n shadowDomManager,\n processedNodeManager,\n canvasManager,\n ignoreCSSAttributes,\n plugins: plugins?.filter((p) => p.observer)?.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload\n }\n })\n })) || []\n },\n {}\n );\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n } catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot2();\n handlers.push(observe(document));\n };\n if (document.readyState === \"interactive\" || document.readyState === \"complete\") {\n init();\n } else {\n handlers.push(\n on(\"DOMContentLoaded\", () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {}\n });\n if (recordAfter === \"DOMContentLoaded\") init();\n })\n );\n handlers.push(\n on(\n \"load\",\n () => {\n wrappedEmit({\n type: EventType.Load,\n data: {}\n });\n if (recordAfter === \"load\") init();\n },\n window\n )\n );\n }\n return () => {\n handlers.forEach((h) => h());\n processedNodeManager.destroy();\n _takeFullSnapshot = void 0;\n unregisterErrorHandler();\n };\n } catch (error) {\n console.warn(error);\n }\n}\nfunction takeFullSnapshot(isCheckout) {\n if (!_takeFullSnapshot) {\n throw new Error(\"please take full snapshot after start recording\");\n }\n _takeFullSnapshot(isCheckout);\n}\nrecord.mirror = mirror;\nrecord.takeFullSnapshot = takeFullSnapshot;\nfunction _getCanvasManager(getCanvasManagerFn, options) {\n try {\n return getCanvasManagerFn ? getCanvasManagerFn(options) : new CanvasManagerNoop();\n } catch {\n console.warn(\"Unable to initialize CanvasManager\");\n return new CanvasManagerNoop();\n }\n}\nvar n;\n!function(t2) {\n t2[t2.NotStarted = 0] = \"NotStarted\", t2[t2.Running = 1] = \"Running\", t2[t2.Stopped = 2] = \"Stopped\";\n}(n || (n = {}));\n\nconst ReplayEventTypeIncrementalSnapshot = 3;\nconst ReplayEventTypeCustom = 5;\n\n/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nfunction timestampToMs(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n\n/**\n * Converts a timestamp to s, if it was in ms, or keeps it as s.\n */\nfunction timestampToS(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Add a breadcrumb event to replay.\n */\nfunction addBreadcrumbEvent(replay, breadcrumb) {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category )) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nfunction getClosestInteractive(element) {\n const closestInteractive = element.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || element;\n}\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nfunction getClickTargetNode(event) {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n return getClosestInteractive(target);\n}\n\n/** Get the event target node. */\nfunction getTargetNode(event) {\n if (isEventWithTarget(event)) {\n return event.target ;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event) {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n\nlet handlers;\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nfunction onWindowOpen(cb) {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers ).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen() {\n fill(WINDOW, 'open', function (originalWindowOpen) {\n return function (...args) {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n\n/** Any IncrementalSource for rrweb that we interpret as a kind of mutation. */\nconst IncrementalMutationSources = new Set([\n IncrementalSource.Mutation,\n IncrementalSource.StyleSheetRule,\n IncrementalSource.StyleDeclaration,\n IncrementalSource.AdoptedStyleSheet,\n IncrementalSource.CanvasMutation,\n IncrementalSource.Selection,\n IncrementalSource.MediaInteraction,\n]);\n\n/** Handle a click. */\nfunction handleClick(clickDetector, clickBreadcrumb, node) {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nclass ClickDetector {\n // protected for testing\n\n constructor(\n replay,\n slowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n this._lastMutation = 0;\n this._lastScroll = 0;\n this._clicks = [];\n\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scrollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n addListeners() {\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n this._teardown = () => {\n cleanupWindowOpen();\n\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n removeListeners() {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n handleClick(breadcrumb, node) {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick = {\n timestamp: timestampToS(breadcrumb.timestamp),\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n\n // If there was a click in the last 1s on the same element, ignore it - only keep a single reference per second\n if (\n this._clicks.some(click => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)\n ) {\n return;\n }\n\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** @inheritDoc */\n registerMutation(timestamp = Date.now()) {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n registerScroll(timestamp = Date.now()) {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n registerClick(element) {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node );\n }\n\n /** Count multiple clicks on elements. */\n _handleMultiClick(node) {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n _getClicks(node) {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n _checkClicks() {\n const timedOutClicks = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // All of these are in seconds!\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n const pos = this._clicks.indexOf(click);\n\n if (pos > -1) {\n this._generateBreadcrumbs(click);\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n _generateBreadcrumbs(click) {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scrollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n _scheduleCheckClicks() {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout$3(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nfunction ignoreElement(node, ignoreSelector) {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb) {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds() {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nfunction updateClickDetectorForRecordingEvent(clickDetector, event) {\n try {\n // note: We only consider incremental snapshots here\n // This means that any full snapshot is ignored for mutation detection - the reason is that we simply cannot know if a mutation happened here.\n // E.g. think that we are buffering, an error happens and we take a full snapshot because we switched to session mode -\n // in this scenario, we would not know if a dead click happened because of the error, which is a key dead click scenario.\n // Instead, by ignoring full snapshots, we have the risk that we generate a false positive\n // (if a mutation _did_ happen but was \"swallowed\" by the full snapshot)\n // But this should be more unlikely as we'd generally capture the incremental snapshot right away\n\n if (!isIncrementalEvent(event)) {\n return;\n }\n\n const { source } = event.data;\n if (IncrementalMutationSources.has(source)) {\n clickDetector.registerMutation(event.timestamp);\n }\n\n if (source === IncrementalSource.Scroll) {\n clickDetector.registerScroll(event.timestamp);\n }\n\n if (isIncrementalMouseInteraction(event)) {\n const { type, id } = event.data;\n const node = record.mirror.getNode(id);\n\n if (node instanceof HTMLElement && type === MouseInteractions.Click) {\n clickDetector.registerClick(node);\n }\n }\n } catch {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event) {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event,\n) {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n\n/**\n * Create a breadcrumb for a replay.\n */\nfunction createBreadcrumb(\n breadcrumb,\n) {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n\nvar NodeType = /* @__PURE__ */ ((NodeType2) => {\n NodeType2[NodeType2[\"Document\"] = 0] = \"Document\";\n NodeType2[NodeType2[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType2[NodeType2[\"Element\"] = 2] = \"Element\";\n NodeType2[NodeType2[\"Text\"] = 3] = \"Text\";\n NodeType2[NodeType2[\"CDATA\"] = 4] = \"CDATA\";\n NodeType2[NodeType2[\"Comment\"] = 5] = \"Comment\";\n return NodeType2;\n})(NodeType || {});\n\n// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nfunction getAttributesToRecord(attributes) {\n const obj = {};\n if (!attributes['data-sentry-component'] && attributes['data-sentry-element']) {\n attributes['data-sentry-component'] = attributes['data-sentry-element'];\n }\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n\nconst handleDomListener = (\n replay,\n) => {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick ? (handlerData.event ) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event?.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result ,\n getClickTargetNode(handlerData.event ) ,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nfunction getBaseDomBreadcrumb(target, message) {\n const nodeId = record.mirror.getId(target);\n const node = nodeId && record.mirror.getNode(nodeId);\n const meta = node && record.mirror.getMeta(node);\n const element = meta && isElement(meta) ? meta : null;\n\n return {\n message,\n data: element\n ? {\n nodeId,\n node: {\n id: nodeId,\n tagName: element.tagName,\n textContent: Array.from(element.childNodes)\n .map((node) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text ).trim())\n .join(''),\n attributes: getAttributesToRecord(element.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nfunction handleDom(handlerData) {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData) {\n const isClick = handlerData.name === 'click';\n\n let message;\n let target = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event ) : getTargetNode(handlerData.event );\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node) {\n return node.type === NodeType.Element;\n}\n\n/** Handle keyboard events & create breadcrumbs. */\nfunction handleKeyboardEvent(replay, event) {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nfunction getKeyboardBreadcrumb(event) {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target ) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target , message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target) {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES\n\n = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Handler creater for web vitals\n */\nfunction webVitalHandler(\n getter,\n replay,\n) {\n return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric));\n}\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nfunction createPerformanceEntries(\n entries,\n) {\n return entries.map(createPerformanceEntry).filter(Boolean) ;\n}\n\nfunction createPerformanceEntry(entry) {\n const entryType = ENTRY_TYPES[entry.entryType];\n if (!entryType) {\n return null;\n }\n\n return entryType(entry);\n}\n\nfunction getAbsoluteTime(time) {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry) {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry) {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry,\n) {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\n/**\n * Add a LCP event to the replay based on a LCP metric.\n */\nfunction getLargestContentfulPaint(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry?.element ? [lastEntry.element] : undefined;\n return getWebVital(metric, 'largest-contentful-paint', node);\n}\n\nfunction isLayoutShift(entry) {\n return (entry ).sources !== undefined;\n}\n\n/**\n * Add a CLS event to the replay based on a CLS metric.\n */\nfunction getCumulativeLayoutShift(metric) {\n const layoutShifts = [];\n const nodes = [];\n for (const entry of metric.entries) {\n if (isLayoutShift(entry)) {\n const nodeIds = [];\n for (const source of entry.sources) {\n if (source.node) {\n nodes.push(source.node);\n const nodeId = record.mirror.getId(source.node);\n if (nodeId) {\n nodeIds.push(nodeId);\n }\n }\n }\n layoutShifts.push({ value: entry.value, nodeIds: nodeIds.length ? nodeIds : undefined });\n }\n }\n\n return getWebVital(metric, 'cumulative-layout-shift', nodes, layoutShifts);\n}\n\n/**\n * Add an INP event to the replay based on an INP metric.\n */\nfunction getInteractionToNextPaint(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry?.target ? [lastEntry.target] : undefined;\n return getWebVital(metric, 'interaction-to-next-paint', node);\n}\n\n/**\n * Add an web vital event to the replay based on the web vital metric.\n */\nfunction getWebVital(\n metric,\n name,\n nodes,\n attributions,\n) {\n const value = metric.value;\n const rating = metric.rating;\n\n const end = getAbsoluteTime(value);\n\n return {\n type: 'web-vital',\n name,\n start: end,\n end,\n data: {\n value,\n size: value,\n rating,\n nodeIds: nodes ? nodes.map(node => record.mirror.getId(node)) : undefined,\n attributions,\n },\n };\n}\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nfunction setupPerformanceObserver(replay) {\n function addPerformanceEntry(entry) {\n // It is possible for entries to come up multiple times\n if (!replay.performanceEntries.includes(entry)) {\n replay.performanceEntries.push(entry);\n }\n }\n\n function onEntries({ entries }) {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks = [];\n\n (['navigation', 'paint', 'resource'] ).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(webVitalHandler(getLargestContentfulPaint, replay)),\n addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)),\n addInpInstrumentationHandler(webVitalHandler(getInteractionToNextPaint, replay)),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\n}\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nconst r = `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,e){for(var i=new n(31),s=0;s<31;++s)i[s]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,s=0,a=new n(r);s>f]=l}else for(o=new n(i),s=0;s>15-t[s]);return o},p=new t(288);for(c=0;c<144;++c)p[c]=8;for(c=144;c<256;++c)p[c]=9;for(c=256;c<280;++c)p[c]=7;for(c=280;c<288;++c)p[c]=8;var g=new t(32);for(c=0;c<32;++c)g[c]=5;var w=d(p,9,0),y=d(g,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=[\"unexpected EOF\",\"invalid block type\",\"invalid length/literal\",\"invalid distance\",\"stream finished\",\"no stream handler\",,\"no callback\",\"invalid UTF-8 data\",\"extra field too long\",\"date not in range 1980-2099\",\"filename too long\",\"stream finishing\",\"invalid zip data\"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],s=0;sd&&(d=o[s].s);var p=new n(d+1),g=A(i[c-1],p,0);if(g>e){s=0;var w=0,y=g-e,m=1<e))break;w+=m-(1<>=y;w>0;){var M=o[s].s;p[M]=0&&w;--s){var E=o[s].s;p[E]==e&&(--p[E],++w)}g=e}return{t:new t(p),l:g}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,s=t[0],a=1,o=function(t){e[i++]=t},h=1;h<=r;++h)if(t[h]==s&&h!=r)++a;else{if(!s&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(s),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(s);a=1,s=t[h]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var s=0;s4&&!H[s[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(h,p)+T(f,g)+l,X=T(h,M)+T(f,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=w,P=p,Q=y,R=g;for(B=0;B255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,s=0|r.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},L=function(s,a,o,h,u){if(!u&&(u={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),v=new t(c.length+s.length);v.set(c),v.set(s,c.length),s=v,u.w=c.length}return function(s,a,o,h,u,c){var v=c.z||s.length,d=new t(h+v+5*(1+Math.ceil(v/7e3))+u),p=d.subarray(h,d.length-u),g=c.l,w=7&(c.r||0);if(a){w&&(p[0]=c.r>>3);for(var y=C[a-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!g)){w=U(s,p,0,F,I,S,O,q,G,j-G,w),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(s[j+Q]==s[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|f[Q]<<18|l[R];var it=31&f[Q],st=31&l[R];O+=e[it]+i[st],++I[257+it],++S[st],B=j+Q,++L}else F[q++]=s[j],++I[s[j]]}}for(j=Math.max(j,B);j=v&&(p[w/8|0]=g,at=v),w=k(p,w+1,s.subarray(j,at))}c.i=v}return b(d,0,h+m(w)+u)}(s,null==a.level?6:a.level,null==a.mem?u.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):20:12+a.mem,o,h,u)},O=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},j=function(){function n(n,r){if(\"function\"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(L(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var s=this.b.length-this.s.z;this.b.set(n.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(s),32768),this.s.z=n.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||E(5),this.s.l&&E(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}();function q(t,n){n||(n={});var r=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}}(),e=t.length;r.p(t);var i,s=L(t,n,10+((i=n).filename?i.filename.length+1:0),8),a=s.length;return function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&O(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}}(s,n),O(s,a-8,r.d()),O(s,a-4,e),s}var B=function(){function t(t,n){this.c=S(),this.v=1,j.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),j.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=L(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=S();i.p(n.dictionary),O(t,2,i.d())}}(r,this.o),this.v=0),n&&O(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(){j.prototype.flush.call(this)},t}(),G=\"undefined\"!=typeof TextEncoder&&new TextEncoder,H=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{H.decode(F,{stream:!0})}catch(t){}var J=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(K(t),this.d=n||!1)},t}();function K(n,r){if(G)return G.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),s=0,a=function(t){i[s++]=t},o=0;oi.length){var h=new t(s+8+(e-o<<1));h.set(i),i=h}var f=n.charCodeAt(o);f<128||r?a(f):f<2048?(a(192|f>>6),a(128|63&f)):f>55295&&f<57344?(a(240|(f=65536+(1047552&f)|1023&n.charCodeAt(++o))>>18),a(128|f>>12&63),a(128|f>>6&63),a(128|63&f)):(a(224|f>>12),a(128|f>>6&63),a(128|63&f))}return b(i,0,s)}const N=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const n=this._hasEvents?\",\":\"\";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push(\"]\",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n{this._deflatedData.push(t)},this.stream=new J((t,n)=>{this.deflate.push(t,n)}),this.stream.push(\"[\")}},P={clear:()=>{N.clear()},addEvent:t=>N.addEvent(t),finish:()=>N.finish(),compress:t=>function(t){return q(K(t))}(t)};addEventListener(\"message\",function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in P&&\"function\"==typeof P[n])try{const t=P[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}}),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n\nfunction e(){const e=new Blob([r]);return URL.createObjectURL(e)}\n\nconst CONSOLE_LEVELS = ['log', 'warn', 'error'] ;\nconst PREFIX = '[Replay] ';\n\nfunction _addBreadcrumb(message, level = 'info') {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level,\n message: `${PREFIX}${message}`,\n },\n { level },\n );\n}\n\nfunction makeReplayDebugLogger() {\n let _capture = false;\n let _trace = false;\n\n const _debug = {\n exception: () => undefined,\n infoTick: () => undefined,\n setConfig: (opts) => {\n _capture = !!opts.captureExceptions;\n _trace = !!opts.traceInternals;\n },\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n _debug[name] = (...args) => {\n debug$1[name](PREFIX, ...args);\n if (_trace) {\n _addBreadcrumb(args.join(''), severityLevelFromString(name));\n }\n };\n });\n\n _debug.exception = (error, ...message) => {\n if (message.length && _debug.error) {\n _debug.error(...message);\n }\n\n debug$1.error(PREFIX, error);\n\n if (_capture) {\n captureException(error, {\n mechanism: {\n handled: true,\n type: 'auto.function.replay.debug',\n },\n });\n } else if (_trace) {\n // No need for a breadcrumb if `_capture` is enabled since it should be\n // captured as an exception\n _addBreadcrumb(error, 'error');\n }\n };\n\n _debug.infoTick = (...args) => {\n debug$1.log(PREFIX, ...args);\n if (_trace) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => _addBreadcrumb(args[0]), 0);\n }\n };\n } else {\n CONSOLE_LEVELS.forEach(name => {\n _debug[name] = () => undefined;\n });\n }\n\n return _debug ;\n}\n\nconst debug = makeReplayDebugLogger();\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nclass EventBufferSizeExceededError extends Error {\n constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nclass EventBufferArray {\n /** All the events that are buffered to be sent. */\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n\n constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n this.waitForCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n get type() {\n return 'sync';\n }\n\n /** @inheritdoc */\n destroy() {\n this.events = [];\n }\n\n /** @inheritdoc */\n async addEvent(event) {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n finish() {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n clear() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass WorkerHandler {\n\n constructor(worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occurred.\n */\n ensureReady() {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }) => {\n if ((data ).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n destroy() {\n DEBUG_BUILD && debug.log('Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n postMessage(method, arg) {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }) => {\n const response = data ;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && debug.error('Error in compression worker: ', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response );\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n _getAndIncrementId() {\n return this._id++;\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass EventBufferCompressionWorker {\n /** @inheritdoc */\n\n /** @inheritdoc */\n\n constructor(worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n this.waitForCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n get type() {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occurred.\n */\n ensureReady() {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n destroy() {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully received and processed by worker.\n */\n addEvent(event) {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n finish() {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n clear() {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && debug.exception(e, 'Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n _sendEventToWorker(data) {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n async _finishRequest() {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nclass EventBufferProxy {\n\n constructor(worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n get waitForCheckout() {\n return this._used.waitForCheckout;\n }\n\n /** @inheritdoc */\n get type() {\n return this._used.type;\n }\n\n /** @inheritDoc */\n get hasEvents() {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n get hasCheckout() {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n set hasCheckout(value) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritdoc */\n // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures\n set waitForCheckout(value) {\n this._used.waitForCheckout = value;\n }\n\n /** @inheritDoc */\n destroy() {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n clear() {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n addEvent(event) {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n async finish() {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n ensureWorkerIsLoaded() {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n async _ensureWorkerIsLoaded() {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n DEBUG_BUILD && debug.exception(error, 'Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n async _switchToCompressionWorker() {\n const { events, hasCheckout, waitForCheckout } = this._fallback;\n\n const addEventPromises = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n this._compression.waitForCheckout = waitForCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n\n // Can now clear fallback buffer as it's no longer necessary\n this._fallback.clear();\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to add events when switching buffers.');\n }\n }\n}\n\n/**\n * Create an event buffer for replays.\n */\nfunction createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}) {\n if (\n useCompression &&\n // eslint-disable-next-line no-restricted-globals\n window.Worker\n ) {\n const worker = _loadWorker(customWorkerUrl);\n\n if (worker) {\n return worker;\n }\n }\n\n DEBUG_BUILD && debug.log('Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl) {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n DEBUG_BUILD && debug.log(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl() {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return e();\n }\n\n return '';\n}\n\n/** If sessionStorage is available. */\nfunction hasSessionStorage() {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch {\n return false;\n }\n}\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nfunction clearSession(replay) {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession() {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nfunction isSampled(sampleRate) {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n\n/**\n * Save a session to session storage.\n */\nfunction saveSession(session) {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Get a session with defaults & applied sampling.\n */\nfunction makeSession(session) {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n const dirty = session.dirty || false;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n dirty,\n };\n}\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nfunction getSessionSampleType(sessionSampleRate, allowBuffering) {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nfunction createSession(\n { sessionSampleRate, allowBuffering, stickySession = false },\n { previousSessionId } = {},\n) {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n\n/**\n * Fetches a session from storage\n */\nfunction fetchSession() {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) ;\n\n DEBUG_BUILD && debug.infoTick('Loading existing session');\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n\n/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nfunction isExpired(\n initialTime,\n expiry,\n targetTime = +new Date(),\n) {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n\n/**\n * Checks to see if session is expired\n */\nfunction isSessionExpired(\n session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n },\n) {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, maxReplayDuration, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, sessionIdleExpire, targetTime)\n );\n}\n\n/** If the session should be refreshed or not. */\nfunction shouldRefreshSession(\n session,\n { sessionIdleExpire, maxReplayDuration },\n) {\n // If not expired, all good, just keep the session\n if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {\n return false;\n }\n\n // If we are buffering & haven't ever flushed yet, always continue\n if (session.sampled === 'buffer' && session.segmentId === 0) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nfunction loadOrCreateSession(\n {\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }\n\n,\n sessionOptions,\n) {\n const existingSession = sessionOptions.stickySession && fetchSession();\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n DEBUG_BUILD && debug.infoTick('Creating new session');\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n DEBUG_BUILD && debug.infoTick('Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n\nfunction isCustomEvent(event) {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * In contrast to `addEvent`, this does not return a promise & does not wait for the adding of the event to succeed/fail.\n * Instead this returns `true` if we tried to add the event, else false.\n * It returns `false` e.g. if we are paused, disabled, or out of the max replay duration.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nfunction addEventSync(replay, event, isCheckout) {\n if (!shouldAddEvent(replay, event)) {\n return false;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n _addEvent(replay, event, isCheckout);\n\n return true;\n}\n\n/**\n * Add an event to the event buffer.\n * Resolves to `null` if no event was added, else to `void`.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nfunction addEvent(\n replay,\n event,\n isCheckout,\n) {\n if (!shouldAddEvent(replay, event)) {\n return Promise.resolve(null);\n }\n\n return _addEvent(replay, event, isCheckout);\n}\n\nasync function _addEvent(\n replay,\n event,\n isCheckout,\n) {\n const { eventBuffer } = replay;\n\n if (!eventBuffer || (eventBuffer.waitForCheckout && !isCheckout)) {\n return null;\n }\n\n const isBufferMode = replay.recordingMode === 'buffer';\n\n try {\n if (isCheckout && isBufferMode) {\n eventBuffer.clear();\n }\n\n if (isCheckout) {\n eventBuffer.hasCheckout = true;\n eventBuffer.waitForCheckout = false;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const isExceeded = error && error instanceof EventBufferSizeExceededError;\n const reason = isExceeded ? 'addEventSizeExceeded' : 'addEvent';\n const client = getClient();\n\n if (client) {\n // We are limited in the drop reasons:\n // https://github.com/getsentry/snuba/blob/6c73be60716c2fb1c30ca627883207887c733cbd/rust_snuba/src/processors/outcomes.rs#L39\n const dropReason = isExceeded ? 'buffer_overflow' : 'internal_sdk_error';\n client.recordDroppedEvent(dropReason, 'replay');\n }\n\n if (isExceeded && isBufferMode) {\n // Clear buffer and wait for next checkout\n eventBuffer.clear();\n eventBuffer.waitForCheckout = true;\n\n return null;\n }\n\n replay.handleException(error);\n\n await replay.stop({ reason });\n }\n}\n\n/** Exported only for tests. */\nfunction shouldAddEvent(replay, event) {\n if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {\n return false;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return false;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {\n DEBUG_BUILD &&\n debug.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`);\n return false;\n }\n\n return true;\n}\n\nfunction maybeApplyCallback(\n event,\n callback,\n) {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n debug.exception(error, 'An error occurred in the `beforeAddRecordingEvent` callback, skipping the event...');\n return null;\n }\n\n return event;\n}\n\n/** If the event is an error event */\nfunction isErrorEvent(event) {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nfunction isReplayEvent(event) {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nfunction isFeedbackEvent(event) {\n return event.type === 'feedback';\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleAfterSendEvent(replay) {\n return (event, sendResponse) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // We skip if we encountered an non-OK status code\n if (!statusCode || statusCode < 200 || statusCode >= 300) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay, event) {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts?.trace?.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id);\n }\n}\n\nfunction handleErrorEvent(replay, event) {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode !== 'buffer' || !event.tags || !event.tags.replayId) {\n return;\n }\n\n const { beforeErrorSampling } = replay.getOptions();\n if (typeof beforeErrorSampling === 'function' && !beforeErrorSampling(event)) {\n return;\n }\n\n setTimeout$3(async () => {\n try {\n // Capture current event buffer as new replay\n await replay.sendBufferedReplayOrFlush();\n } catch (err) {\n replay.handleException(err);\n }\n });\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleBeforeSendEvent(replay) {\n return (event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay, event) {\n const exceptionValue = event.exception?.values?.[0]?.value;\n if (typeof exceptionValue !== 'string') {\n return;\n }\n\n if (\n // Only matches errors in production builds of react-dom\n // Example https://reactjs.org/docs/error-decoder.html?invariant=423\n // With newer React versions, the messages changed to a different website https://react.dev/errors/418\n exceptionValue.match(\n /(reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=|react\\.dev\\/errors\\/)(418|419|422|423|425)/,\n ) ||\n // Development builds of react-dom\n // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.\n // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.\n exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)\n ) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.hydrate-error',\n data: {\n url: getLocationHref(),\n },\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n\n/**\n * Handle breadcrumbs that Sentry captures, and make sure to capture relevant breadcrumbs to Replay as well.\n */\nfunction handleBreadcrumbs(replay) {\n const client = getClient();\n\n if (!client) {\n return;\n }\n\n client.on('beforeAddBreadcrumb', breadcrumb => beforeAddBreadcrumb(replay, breadcrumb));\n}\n\nfunction beforeAddBreadcrumb(replay, breadcrumb) {\n if (!replay.isEnabled() || !isBreadcrumbWithCategory(breadcrumb)) {\n return;\n }\n\n const result = normalizeBreadcrumb(breadcrumb);\n if (result) {\n addBreadcrumbEvent(replay, result);\n }\n}\n\n/** Exported only for tests. */\nfunction normalizeBreadcrumb(breadcrumb) {\n if (\n !isBreadcrumbWithCategory(breadcrumb) ||\n [\n // fetch & xhr are handled separately,in handleNetworkBreadcrumbs\n 'fetch',\n 'xhr',\n // These two are breadcrumbs for emitted sentry events, we don't care about them\n 'sentry.event',\n 'sentry.transaction',\n ].includes(breadcrumb.category) ||\n // We capture UI breadcrumbs separately\n breadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (breadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(breadcrumb);\n }\n\n return createBreadcrumb(breadcrumb);\n}\n\n/** exported for tests only */\nfunction normalizeConsoleBreadcrumb(\n breadcrumb,\n) {\n const args = breadcrumb.data?.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n\nfunction isBreadcrumbWithCategory(breadcrumb) {\n return !!breadcrumb.category;\n}\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nfunction isRrwebError(event, hint) {\n if (event.type || !event.exception?.values?.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException?.__rrweb__) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Reset the `replay_id` field on the DSC.\n */\nfunction resetReplayIdOnDynamicSamplingContext() {\n // Reset DSC on the current scope, if there is one\n const dsc = getCurrentScope().getPropagationContext().dsc;\n if (dsc) {\n delete dsc.replay_id;\n }\n\n // Clear it from frozen DSC on the active span\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const dsc = getDynamicSamplingContextFromSpan(activeSpan);\n delete (dsc ).replay_id;\n }\n}\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nfunction addFeedbackBreadcrumb(replay, event) {\n replay.triggerUserActivity();\n replay.addUpdate(() => {\n if (!event.timestamp) {\n // Ignore events that don't have timestamps (this shouldn't happen, more of a typing issue)\n // Return true here so that we don't flush\n return true;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: event.timestamp * 1000,\n data: {\n tag: 'breadcrumb',\n payload: {\n timestamp: event.timestamp,\n type: 'default',\n category: 'sentry.feedback',\n data: {\n feedbackId: event.event_id,\n },\n },\n },\n } );\n\n return false;\n });\n}\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `handleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nfunction shouldSampleForBufferEvent(replay, event) {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nfunction handleGlobalEventListener(replay) {\n return Object.assign(\n (event, hint) => {\n // Do nothing if replay has been disabled or paused\n if (!replay.isEnabled() || replay.isPaused()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors, transactions, and feedbacks, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {\n return event;\n }\n\n // Ensure we do not add replay_id if the session is expired\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (!isSessionActive) {\n // prevent exceeding replay durations by removing the expired replayId from the DSC\n resetReplayIdOnDynamicSamplingContext();\n return event;\n }\n\n if (isFeedbackEvent(event)) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.flush();\n event.contexts.feedback.replay_id = replay.getSessionId();\n // Add a replay breadcrumb for this piece of feedback\n addFeedbackBreadcrumb(replay, event);\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n DEBUG_BUILD && debug.log('Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n // If we sampled this error in buffer mode, immediately mark the session as \"sampled\"\n // by changing the sampled state from 'buffer' to 'session'. Otherwise, if the application is interrupte\n // before `afterSendEvent` occurs, then the session would remain as \"buffer\" but we have an error event\n // that is tagged with a replay id. This could end up creating replays w/ excessive durations because\n // of the linked error.\n if (isErrorEventSampled && replay.recordingMode === 'buffer' && replay.session?.sampled === 'buffer') {\n const session = replay.session;\n session.dirty = true;\n // Save the session if sticky sessions are enabled to persist the state change\n if (replay.getOptions().stickySession) {\n saveSession(session);\n }\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n\n/**\n * Create a \"span\" for each performance entry.\n */\nfunction createPerformanceSpans(\n replay,\n entries,\n) {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n\nfunction handleHistory(handlerData) {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addHistoryInstrumentationHandler(listener)`.\n */\nfunction handleHistorySpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nfunction shouldFilterRequest(replay, url) {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (DEBUG_BUILD && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return isSentryRequestUrl(url, getClient());\n}\n\n/** Add a performance entry breadcrumb */\nfunction addNetworkBreadcrumb(\n replay,\n result,\n) {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n\n/** Get the size of a body. */\nfunction getBodySize(body) {\n if (!body) {\n return undefined;\n }\n\n const textEncoder = new TextEncoder();\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nfunction parseContentLengthHeader(header) {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Merge a warning into an existing network request/response. */\nfunction mergeWarning(\n info,\n warning,\n) {\n if (!info) {\n return {\n headers: {},\n size: undefined,\n _meta: {\n warnings: [warning],\n },\n };\n }\n\n const newMeta = { ...info._meta };\n const existingWarnings = newMeta.warnings || [];\n newMeta.warnings = [...existingWarnings, warning];\n\n info._meta = newMeta;\n return info;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nfunction makeNetworkReplayBreadcrumb(\n type,\n data,\n) {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: {\n method,\n statusCode,\n request,\n response,\n },\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nfunction buildSkippedNetworkRequestOrResponse(bodySize) {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nfunction buildNetworkRequestOrResponse(\n headers,\n bodySize,\n body,\n) {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings?.length) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nfunction getAllowedHeaders(headers, allowedHeaders) {\n return Object.entries(headers).reduce((filteredHeaders, [key, value]) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = value;\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction normalizeNetworkBody(body)\n\n {\n if (!body || typeof body !== 'string') {\n return {\n body,\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n const isProbablyJson = _strIsProbablyJson(body);\n\n if (exceedsSizeLimit) {\n const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);\n\n if (isProbablyJson) {\n return {\n body: truncatedBody,\n warnings: ['MAYBE_JSON_TRUNCATED'],\n };\n }\n\n return {\n body: `${truncatedBody}…`,\n warnings: ['TEXT_TRUNCATED'],\n };\n }\n\n if (isProbablyJson) {\n try {\n const jsonBody = JSON.parse(body);\n return {\n body: jsonBody,\n };\n } catch {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str) {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nfunction urlMatches(url, urls) {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nfunction getFullUrl(url, baseURI = WINDOW.document.baseURI) {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where appropriate).\n */\nasync function captureFetchBreadcrumbToReplay(\n breadcrumb,\n hint,\n options\n\n,\n) {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to capture fetch breadcrumb');\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichFetchBreadcrumb(\n breadcrumb,\n hint,\n) {\n const { input, response } = hint;\n\n const body = input ? getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb,\n hint,\n options,\n) {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders },\n input,\n requestBodySize,\n) {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody, debug);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nasync function _getResponseInfo(\n captureDetails,\n {\n networkCaptureBodies,\n networkResponseHeaders,\n },\n response,\n responseBodySize,\n) {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};\n\n if (!response || (!networkCaptureBodies && responseBodySize !== undefined)) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n const [bodyText, warning] = await _parseFetchResponseBody(response);\n const result = getResponseData(bodyText, {\n networkCaptureBodies,\n\n responseBodySize,\n captureDetails,\n headers,\n });\n\n if (warning) {\n return mergeWarning(result, warning);\n }\n\n return result;\n}\n\nfunction getResponseData(\n bodyText,\n {\n networkCaptureBodies,\n responseBodySize,\n captureDetails,\n headers,\n }\n\n,\n) {\n try {\n const size = bodyText?.length && responseBodySize === undefined ? getBodySize(bodyText) : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to serialize response body');\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response) {\n const res = _tryCloneResponse(response);\n\n if (!res) {\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n try {\n const text = await _tryGetResponseText(res);\n return [text];\n } catch (error) {\n if (error instanceof Error && error.message.indexOf('Timeout') > -1) {\n DEBUG_BUILD && debug.warn('Parsing text body from response timed out');\n return [undefined, 'BODY_PARSE_TIMEOUT'];\n }\n\n DEBUG_BUILD && debug.exception(error, 'Failed to get text body from response');\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction getAllHeaders(headers, allowedHeaders) {\n const allHeaders = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) ;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs, allowedHeaders) {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input,\n allowedHeaders,\n) {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\nfunction _tryCloneResponse(response) {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && debug.exception(error, 'Failed to clone response body');\n }\n}\n\n/**\n * Get the response body of a fetch request, or timeout after 500ms.\n * Fetch can return a streaming body, that may not resolve (or not for a long time).\n * If that happens, we rather abort after a short time than keep waiting for this.\n */\nfunction _tryGetResponseText(response) {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout$3(() => reject(new Error('Timeout while trying to read response body')), 500);\n\n _getResponseText(response)\n .then(\n txt => resolve(txt),\n reason => reject(reason),\n )\n .finally(() => clearTimeout(timeout));\n });\n}\n\nasync function _getResponseText(response) {\n // Force this to be a promise, just to be safe\n // eslint-disable-next-line no-return-await\n return await response.text();\n}\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where appropriate).\n */\nasync function captureXhrBreadcrumbToReplay(\n breadcrumb,\n hint,\n options,\n) {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to capture xhr breadcrumb');\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichXhrBreadcrumb(\n breadcrumb,\n hint,\n) {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb,\n hint,\n options,\n) {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n // ---- This additional network data below is only captured for URLs defined in `networkDetailAllowUrls` ----\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(parseXhrResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input, debug) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction _getXhrResponseBody(xhr) {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && debug.warn('Failed to get xhr response body', ...errors);\n\n return [undefined];\n}\n\n/**\n * Get the string representation of the XHR response.\n * Based on MDN, these are the possible types of the response:\n * string\n * ArrayBuffer\n * Blob\n * Document\n * POJO\n *\n * Exported only for tests.\n */\nfunction _parseXhrResponse(\n body,\n responseType,\n) {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof Document) {\n return [body.body.outerHTML];\n }\n\n if (responseType === 'json' && body && typeof body === 'object') {\n return [JSON.stringify(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch (error) {\n DEBUG_BUILD && debug.exception(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && debug.log('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body,\n responseType,\n) {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr);\n } catch {\n return undefined;\n }\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nfunction handleNetworkBreadcrumbs(replay) {\n const client = getClient();\n\n try {\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options = {\n replay,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nfunction beforeAddNetworkBreadcrumb(\n options,\n breadcrumb,\n hint,\n) {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n DEBUG_BUILD && debug.exception(e, 'Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint) {\n return hint?.xhr;\n}\n\nfunction _isFetchHint(hint) {\n return hint?.response;\n}\n\n/**\n * Add global listeners that cannot be removed.\n */\nfunction addGlobalListeners(replay) {\n // Listeners from core SDK //\n const client = getClient();\n\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleBreadcrumbs(replay);\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n const eventProcessor = handleGlobalEventListener(replay);\n addEventProcessor(eventProcessor);\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (client) {\n client.on('beforeSendEvent', handleBeforeSendEvent(replay));\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n // Ensure to check that the session is still active - it could have expired in the meanwhile\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (isSessionActive) {\n dsc.replay_id = replayId;\n }\n }\n });\n\n client.on('spanStart', span => {\n replay.lastActiveSpan = span;\n });\n\n // We may be missing the initial spanStart due to timing issues,\n // so we capture it on finish again.\n client.on('spanEnd', span => {\n replay.lastActiveSpan = span;\n });\n\n // We want to attach the replay id to the feedback event\n client.on('beforeSendFeedback', async (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options?.includeReplay && replay.isEnabled() && replayId && feedbackEvent.contexts?.feedback) {\n // In case the feedback is sent via API and not through our widget, we want to flush replay\n if (feedbackEvent.contexts.feedback.source === 'api') {\n await replay.sendBufferedReplayOrFlush();\n }\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n });\n\n client.on('openFeedbackWidget', async () => {\n await replay.sendBufferedReplayOrFlush();\n });\n }\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nasync function addMemoryEntry(replay) {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry) {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nfunction debounce(func, wait, options) {\n return debounce$1(func, wait, {\n ...options,\n // @ts-expect-error - Not quite sure why these types do not match, but this is fine\n setTimeoutImpl: setTimeout$3,\n });\n}\n\nconst NAVIGATOR = GLOBAL_OBJ.navigator;\n\n/**\n * Disable sampling mousemove events on iOS browsers as this can cause blocking the main thread\n * https://github.com/getsentry/sentry-javascript/issues/14534\n */\nfunction getRecordingSamplingOptions() {\n if (\n /iPhone|iPad|iPod/i.test(NAVIGATOR?.userAgent ?? '') ||\n (/Macintosh/i.test(NAVIGATOR?.userAgent ?? '') && NAVIGATOR?.maxTouchPoints && NAVIGATOR?.maxTouchPoints > 1)\n ) {\n return {\n sampling: {\n mousemove: false,\n },\n };\n }\n\n return {};\n}\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nfunction getHandleRecordingEmit(replay) {\n let hadFirstEvent = false;\n\n return (event, _isCheckout) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && debug.warn('Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n if (replay.clickDetector) {\n updateClickDetectorForRecordingEvent(replay.clickDetector, event);\n }\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // If the event is not added (e.g. due to being paused, disabled, or out of the max replay duration),\n // Skip all further steps\n if (!addEventSync(replay, event, isCheckout)) {\n // Return true to skip scheduling a debounced flush\n return true;\n }\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n const session = replay.session;\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time. We have an experimental mode\n // to perform multiple checkouts a session (the idea is to improve\n // seeking during playback), so also only include if segmentId is 0\n // (handled in `addSettingsEvent`).\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n addSettingsEvent(replay, isCheckout);\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && session && replay.eventBuffer && !session.dirty) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n DEBUG_BUILD &&\n debug.log(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`);\n\n session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(session);\n }\n }\n }\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (session?.previousSessionId) {\n return true;\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nfunction createOptionsEvent(replay) {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n shouldRecordCanvas: replay.isRecordingCanvas(),\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay, isCheckout) {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return;\n }\n\n addEventSync(replay, createOptionsEvent(replay), false);\n}\n\n/**\n * Vendored in from @sentry-internal/rrweb.\n *\n * This is a copy of the function from rrweb, it is not nicely exported there.\n */\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n\n // Catch access to node properties to avoid Firefox \"permission denied\" errors\n try {\n const el = node.nodeType === node.ELEMENT_NODE ? (node ) : node.parentElement;\n return el;\n } catch {\n return null;\n }\n}\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nfunction createReplayEnvelope(\n replayEvent,\n recordingData,\n dsn,\n tunnel,\n) {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n\n/**\n * Prepare the recording data ready to be sent.\n */\nfunction prepareRecordingData({\n recordingData,\n headers,\n}\n\n) {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nasync function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}\n\n) {\n const integrations =\n typeof client['_integrations'] === 'object' &&\n client['_integrations'] !== null &&\n !Array.isArray(client['_integrations'])\n ? Object.keys(client['_integrations'])\n : undefined;\n\n const eventHint = { event_id, integrations };\n\n client.emit('preprocessEvent', event, eventHint);\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) ;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n client.emit('postprocessEvent', preparedEvent, eventHint);\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata();\n const { name, version, settings } = metadata?.sdk || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n settings,\n };\n\n return preparedEvent;\n}\n\n/**\n * Send replay attachment using `fetch()`\n */\nasync function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}) {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client?.getTransport();\n const dsn = client?.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return Promise.resolve({});\n }\n\n const baseEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay');\n DEBUG_BUILD && debug.log('An event processor returned `null`, will not send event.');\n return Promise.resolve({});\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // Check for rate limiting first (handles 429 and rate limit headers)\n const rateLimits = updateRateLimits({}, response);\n if (isRateLimited(rateLimits, 'replay')) {\n throw new RateLimitError(rateLimits);\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nclass TransportStatusCodeError extends Error {\n constructor(statusCode) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nclass RateLimitError extends Error {\n\n constructor(rateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n\n/**\n * This error indicates that the replay duration limit was exceeded and the session is too long.\n *\n */\nclass ReplayDurationLimitError extends Error {\n constructor() {\n super('Session is too long, not sending replay');\n }\n}\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nasync function sendReplay(\n replayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n) {\n const { recordingData, onError } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (onError) {\n onError(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout$3(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n\nconst THROTTLED = '__THROTTLED';\nconst SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction throttle(\n fn,\n maxCount,\n durationSeconds,\n) {\n const counter = new Map();\n\n const _cleanup = (now) => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = () => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest) => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nclass ReplayContainer {\n\n /**\n * Recording can happen in one of two modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n\n /**\n * The current or last active span.\n * This is only available when performance is enabled.\n */\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n\n /** The replay has to be manually started, because no sample rate (neither session or error) was provided. */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n\n /**\n * Is the integration currently active?\n */\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n\n /**\n * Function to stop recording\n */\n\n /**\n * Internal use for canvas recording options\n */\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n\n /**\n * Handle when page is blurred\n */\n\n /**\n * Handle when page is focused\n */\n\n /** Ensure page remains active when a key is pressed. */\n\n constructor({\n options,\n recordingOptions,\n }\n\n) {\n this.eventBuffer = null;\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n } ;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._requiresManualStart = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event, isCheckout) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n\n // Configure replay debug logger w/ experimental options\n if (DEBUG_BUILD) {\n const experiments = options._experiments;\n debug.setConfig({\n captureExceptions: !!experiments.captureExceptions,\n traceInternals: !!experiments.traceInternals,\n });\n }\n\n // We set these handler properties as class properties, to make binding/unbinding them easier\n this._handleVisibilityChange = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n this._handleWindowBlur = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n this._handleWindowFocus = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n this._handleKeyboardEvent = (event) => {\n handleKeyboardEvent(this, event);\n };\n }\n\n /** Get the event context. */\n getContext() {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n isEnabled() {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n isPaused() {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n isRecordingCanvas() {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n getOptions() {\n return this._options;\n }\n\n /** A wrapper to conditionally capture exceptions. */\n handleException(error) {\n DEBUG_BUILD && debug.exception(error);\n if (this._options.onError) {\n this._options.onError(error);\n }\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n initializeSampling(previousSessionId) {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0;\n\n this._requiresManualStart = requiresManualStart;\n\n if (requiresManualStart) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n this._initializeSessionForSampling(previousSessionId);\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n DEBUG_BUILD && debug.exception(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled === false) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n // If segmentId > 0, it means we've previously already captured this session\n // In this case, we still want to continue in `session` recording mode\n this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';\n\n DEBUG_BUILD && debug.infoTick(`Starting replay in ${this.recordingMode} mode`);\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will log a message if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (this._isEnabled && this.recordingMode === 'session') {\n DEBUG_BUILD && debug.log('Recording is already in progress');\n return;\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n DEBUG_BUILD && debug.log('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && debug.infoTick('Starting replay in session mode');\n\n // Required as user activity is initially set in\n // constructor, so if `start()` is called after\n // session idle expiration, a replay will not be\n // created due to an idle timeout.\n this._updateUserActivity();\n\n const session = loadOrCreateSession(\n {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n },\n {\n stickySession: this._options.stickySession,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n },\n );\n\n this.session = session;\n this.recordingMode = 'session';\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n startBuffering() {\n if (this._isEnabled) {\n DEBUG_BUILD && debug.log('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && debug.infoTick('Starting replay in buffer mode');\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: 0,\n allowBuffering: true,\n },\n );\n\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n startRecording() {\n try {\n const canvasOptions = this._canvas;\n\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer'\n ? { checkoutEveryNms: BUFFER_CHECKOUT_TIME }\n : // Otherwise, use experimental option w/ min checkout time of 6 minutes\n // This is to improve playback seeking as there could potentially be\n // less mutations to process in the worse cases.\n //\n // checkout by \"N\" events is probably ideal, but means we have less\n // control about the number of checkouts we make (which generally\n // increases replay size)\n this._options._experiments.continuousCheckout && {\n // Minimum checkout time is 6 minutes\n checkoutEveryNms: Math.max(360000, this._options._experiments.continuousCheckout),\n }),\n emit: getHandleRecordingEmit(this),\n ...getRecordingSamplingOptions(),\n onMutation: this._onMutationHandler.bind(this),\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n stopRecording() {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this.handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n async stop({ forceFlush = false, reason } = {}) {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n // Make sure to reset `recordingMode` to `buffer` to avoid any additional\n // breadcrumbs to trigger a flush (e.g. in `addUpdate()`)\n this.recordingMode = 'buffer';\n\n try {\n DEBUG_BUILD && debug.log(`Stopping Replay${reason ? ` triggered by ${reason}` : ''}`);\n\n resetReplayIdOnDynamicSamplingContext();\n\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer?.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n pause() {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n DEBUG_BUILD && debug.log('Pausing replay');\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n resume() {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n DEBUG_BUILD && debug.log('Resuming replay');\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n DEBUG_BUILD && debug.log('Converting buffer to session');\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode ) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this.session.dirty = false;\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n addUpdate(cb) {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer' || !this._isEnabled) {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n triggerUserActivity() {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._checkSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n updateUserActivity() {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n conditionalFlush() {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n flush() {\n return this._debouncedFlush() ;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of multiple flushes happening closely together.\n */\n flushImmediate() {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() ;\n }\n\n /**\n * Cancels queued up flushes.\n */\n cancelFlush() {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current session (=replay) ID\n *\n * @param onlyIfSampled - If true, will only return the session ID if the session is sampled.\n */\n getSessionId(onlyIfSampled) {\n if (onlyIfSampled && this.session?.sampled === false) {\n return undefined;\n }\n\n return this.session?.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n checkAndHandleExpiredSession() {\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._checkSession()) {\n // Check session handles the refreshing itself\n return false;\n }\n\n return true;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n setInitialState() {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n throttledAddEvent(\n event,\n isCheckout,\n ) {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n // Return `false` if the event _was_ added, as that means we schedule a flush\n return !addEventSync(this, {\n type: ReplayEventTypeCustom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n getCurrentRoute() {\n const lastActiveSpan = this.lastActiveSpan || getActiveSpan();\n const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan);\n\n const attributes = (lastRootSpan && spanToJSON(lastRootSpan).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastRootSpan || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastRootSpan).description;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n _initializeRecording() {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n workerUrl: this._options.workerUrl,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n this._isPaused = false;\n\n this.startRecording();\n }\n\n /**\n * Loads (or refreshes) the current session.\n */\n _initializeSessionForSampling(previousSessionId) {\n // Whenever there is _any_ error sample rate, we always allow buffering\n // Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors\n const allowBuffering = this._options.errorSampleRate > 0;\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n previousSessionId,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering,\n },\n );\n\n this.session = session;\n }\n\n /**\n * Checks and potentially refreshes the current session.\n * Returns false if session is not recorded.\n */\n _checkSession() {\n // If there is no session yet, we do not want to refresh anything\n // This should generally not happen, but to be safe....\n if (!this.session) {\n return false;\n }\n\n const currentSession = this.session;\n\n if (\n shouldRefreshSession(currentSession, {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n })\n ) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._refreshSession(currentSession);\n return false;\n }\n\n return true;\n }\n\n /**\n * Refresh a session with a new one.\n * This stops the current session (without forcing a flush, as that would never work since we are expired),\n * and then does a new sampling based on the refreshed session.\n */\n async _refreshSession(session) {\n if (!this._isEnabled) {\n return;\n }\n await this.stop({ reason: 'refresh session' });\n this.initializeSampling(session.id);\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n _addListeners() {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this);\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this.handleException(err);\n }\n\n this._performanceCleanupCallback = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n _removeListeners() {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n _doChangeToBackgroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n });\n\n if (expired) {\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n _doChangeToForegroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n DEBUG_BUILD && debug.log('Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n _updateUserActivity(_lastActivity = Date.now()) {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n _updateSessionActivity(_lastActivity = Date.now()) {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n _createCustomBreadcrumb(breadcrumb) {\n this.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEntries`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n _addPerformanceEntries() {\n let performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // If we are manually starting, we want to ensure we only include performance entries\n // that are after the initial timestamp\n // The reason for this is that we may have performance entries from the page load, but may decide to start\n // the replay later on, in which case we do not want to include these entries.\n // without this, manually started replays can have events long before the actual replay recording starts,\n // which messes with the timeline etc.\n if (this._requiresManualStart) {\n const initialTimestampInSeconds = this._context.initialTimestamp / 1000;\n performanceEntries = performanceEntries.filter(entry => entry.start >= initialTimestampInSeconds);\n }\n\n return Promise.all(createPerformanceSpans(this, performanceEntries));\n }\n\n /**\n * Clear _context\n */\n _clearContext() {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n _updateInitialTimestampFromEventBuffer() {\n const { session, eventBuffer } = this;\n // If replay was started manually (=no sample rate was given),\n // We do not want to back-port the initial timestamp\n if (!session || !eventBuffer || this._requiresManualStart) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n _popEventContext() {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n async _runFlush() {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && debug.error('No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer?.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n // if this changed in the meanwhile, e.g. because the session was refreshed or similar, we abort here\n if (replayId !== this.getSessionId()) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accommodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 30000) {\n throw new ReplayDurationLimitError();\n }\n\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n timestamp,\n onError: err => this.handleException(err),\n });\n } catch (err) {\n this.handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'sendReplay' });\n\n const client = getClient();\n\n if (client) {\n let dropReason;\n if (err instanceof RateLimitError) {\n dropReason = 'ratelimit_backoff';\n } else if (err instanceof ReplayDurationLimitError) {\n dropReason = 'invalid';\n } else {\n dropReason = 'send_error';\n }\n client.recordDroppedEvent(dropReason, 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n async _flush({\n force = false,\n }\n\n = {}) {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && debug.error('Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n // should never happen, as we would have bailed out before\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxReplayDuration), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this._options.maxReplayDuration + 5000;\n if (tooShort || tooLong) {\n DEBUG_BUILD &&\n debug.log(\n `Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n DEBUG_BUILD && debug.log('Flushing initial segment without checkout.');\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n const _flushInProgress = !!this._flushLock;\n\n // this._flushLock acts as a lock so that future calls to `_flush()` will\n // be blocked until current flush is finished (i.e. this promise resolves)\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n }\n\n try {\n await this._flushLock;\n } catch (err) {\n this.handleException(err);\n } finally {\n this._flushLock = undefined;\n\n if (_flushInProgress) {\n // Wait for previous flush to finish, then call the debounced\n // `_flush()`. It's possible there are other flush requests queued and\n // waiting for it to resolve. We want to reduce all outstanding\n // requests (as well as any new flush requests that occur within a\n // second of the locked flush completing) into a single flush.\n this._debouncedFlush();\n }\n }\n }\n\n /** Save the session, if it is sticky */\n _maybeSaveSession() {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n _onMutationHandler(mutations) {\n const { ignoreMutations } = this._options._experiments;\n if (ignoreMutations?.length) {\n if (\n mutations.some(mutation => {\n const el = closestElementOfNode(mutation.target);\n const selector = ignoreMutations.join(',');\n return el?.matches(selector);\n })\n ) {\n return false;\n }\n }\n\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n }\n}\n\nfunction getOption(selectors, defaultSelectors) {\n return [\n ...selectors,\n // sentry defaults\n ...defaultSelectors,\n ].join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nfunction getPrivacyOptions({ mask, unmask, block, unblock, ignore }) {\n const defaultBlockedElements = ['base', 'iframe[srcdoc]:not([src])'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]']);\n const unmaskSelector = getOption(unmask, []);\n\n const options = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n\n blockSelector: getOption(block, ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements]),\n unblockSelector: getOption(unblock, []),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]']),\n };\n\n return options;\n}\n\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nfunction maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}) {\n // We only mask attributes if `maskAllText` is true\n if (!maskAllText) {\n return value;\n }\n\n // unmaskTextSelector takes precedence\n if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {\n return value;\n }\n\n if (\n maskAttributes.includes(key) ||\n // Need to mask `value` attribute for `` if it's a button-like\n // type\n (key === 'value' && el.tagName === 'INPUT' && ['submit', 'button'].includes(el.getAttribute('type') || ''))\n ) {\n return value.replace(/[\\S]/g, '*');\n }\n\n return value;\n}\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\n// Symbol to store the original body on Request objects\nconst ORIGINAL_BODY = Symbol.for('sentry__originalRequestBody');\n\nlet _initialized = false;\nlet _isRequestInstrumented = false;\n\n/**\n * Instruments the global Request constructor to store the original body.\n * This allows us to retrieve the original body value later, since Request\n * converts string bodies to ReadableStreams.\n */\nfunction _INTERNAL_instrumentRequestInterface() {\n if (typeof Request === 'undefined' || _isRequestInstrumented) {\n return;\n }\n\n const OriginalRequest = Request;\n\n try {\n const SentryRequest = function (input, init) {\n const request = new OriginalRequest(input, init);\n if (init?.body != null) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-member-access\n (request )[ORIGINAL_BODY] = init.body;\n }\n return request;\n };\n\n SentryRequest.prototype = OriginalRequest.prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-member-access\n (GLOBAL_OBJ ).Request = SentryRequest;\n\n _isRequestInstrumented = true;\n } catch {\n // Fail silently if Request is frozen\n }\n}\n\n/**\n * Sentry integration for [Session Replay](https://sentry.io/for/session-replay/).\n *\n * See the [Replay documentation](https://docs.sentry.io/platforms/javascript/guides/session-replay/) for more information.\n *\n * @example\n *\n * ```\n * Sentry.init({\n * dsn: '__DSN__',\n * integrations: [Sentry.replayIntegration()],\n * });\n * ```\n */\nconst replayIntegration = ((options) => {\n return new Replay(options);\n}) ;\n\n/**\n * Replay integration\n */\nclass Replay {\n /**\n * @inheritDoc\n */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n\n constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n maxReplayDuration = MAX_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n workerUrl,\n _experiments = {},\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10000,\n\n slowClickTimeout = 7000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder', 'aria-label'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n onError,\n attachRawBodyFromRequest = false,\n } = {}) {\n this.name = 'Replay';\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n maskAttributeFn: (key, value, el) =>\n maskAttribute({\n maskAttributes,\n maskAllText,\n privacyOptions,\n key,\n value,\n el,\n }),\n\n ...privacyOptions,\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n errorHandler: (err) => {\n try {\n err.__rrweb__ = true;\n } catch {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n // experimental support for recording iframes from different origins\n recordCrossOriginIframes: Boolean(_experiments.recordCrossOriginIframes),\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n useCompression,\n workerUrl,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n beforeErrorSampling,\n onError,\n attachRawBodyFromRequest,\n\n _experiments,\n };\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n this._recordingOptions.ignoreCSSAttributes = new Set(['background-image']);\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n get _isInitialized() {\n return _initialized;\n }\n\n /** Update _isInitialized */\n set _isInitialized(value) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n afterAllSetup(client) {\n if (!isBrowser() || this._replay) {\n return;\n }\n\n if (this._initialOptions.attachRawBodyFromRequest) {\n _INTERNAL_instrumentRequestInterface();\n }\n\n this._setup(client);\n this._initialize(client);\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will log a message if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (!this._replay) {\n return;\n }\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n startBuffering() {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n stop() {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * If replay is not enabled, a new session replay is started.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n flush(options) {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n // assuming a session should be recorded in this case\n if (!this._replay.isEnabled()) {\n this._replay.start();\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n *\n * @param onlyIfSampled - If true, will only return the session ID if the session is sampled.\n *\n */\n getReplayId(onlyIfSampled) {\n if (!this._replay?.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId(onlyIfSampled);\n }\n\n /**\n * Get the current recording mode. This can be either `session` or `buffer`.\n *\n * `session`: Recording the whole session, sending it continuously\n * `buffer`: Always keeping the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n getRecordingMode() {\n if (!this._replay?.isEnabled()) {\n return;\n }\n\n return this._replay.recordingMode;\n }\n\n /**\n * Initializes replay.\n */\n _initialize(client) {\n if (!this._replay) {\n return;\n }\n\n this._maybeLoadFromReplayCanvasIntegration(client);\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n _setup(client) {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions, client);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n\n /** Get canvas options from ReplayCanvas integration, if it is also added. */\n _maybeLoadFromReplayCanvasIntegration(client) {\n // To save bundle size, we skip checking for stuff here\n // and instead just try-catch everything - as generally this should all be defined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n try {\n const canvasIntegration = client.getIntegrationByName('ReplayCanvas')\n\n;\n if (!canvasIntegration) {\n return;\n }\n\n this._replay['_canvas'] = canvasIntegration.getOptions();\n } catch {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions, client) {\n const opt = client.getOptions() ;\n\n const finalOptions = {\n sessionSampleRate: 0,\n errorSampleRate: 0,\n ...initialOptions,\n };\n\n const replaysSessionSampleRate = parseSampleRate(opt.replaysSessionSampleRate);\n const replaysOnErrorSampleRate = parseSampleRate(opt.replaysOnErrorSampleRate);\n\n if (replaysSessionSampleRate == null && replaysOnErrorSampleRate == null) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n });\n }\n\n if (replaysSessionSampleRate != null) {\n finalOptions.sessionSampleRate = replaysSessionSampleRate;\n }\n\n if (replaysOnErrorSampleRate != null) {\n finalOptions.errorSampleRate = replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers) {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n\n/**\n * This is a small utility to get a type-safe instance of the Replay integration.\n */\nfunction getReplay() {\n const client = getClient();\n return client?.getIntegrationByName('Replay');\n}\n\nexport { getReplay, replayIntegration };\n//# sourceMappingURL=index.js.map\n","/*!\nTurbo 8.0.21\nCopyright © 2026 37signals LLC\n */\nconst FrameLoadingStyle = {\n eager: \"eager\",\n lazy: \"lazy\"\n};\n\n/**\n * Contains a fragment of HTML which is updated based on navigation within\n * it (e.g. via links or form submissions).\n *\n * @customElement turbo-frame\n * @example\n * \n * \n * Show all expanded messages in this frame.\n * \n *\n *
\n * Show response from this form within this frame.\n *
\n * \n */\nclass FrameElement extends HTMLElement {\n static delegateConstructor = undefined\n\n loaded = Promise.resolve()\n\n static get observedAttributes() {\n return [\"disabled\", \"loading\", \"src\"]\n }\n\n constructor() {\n super();\n this.delegate = new FrameElement.delegateConstructor(this);\n }\n\n connectedCallback() {\n this.delegate.connect();\n }\n\n disconnectedCallback() {\n this.delegate.disconnect();\n }\n\n reload() {\n return this.delegate.sourceURLReloaded()\n }\n\n attributeChangedCallback(name) {\n if (name == \"loading\") {\n this.delegate.loadingStyleChanged();\n } else if (name == \"src\") {\n this.delegate.sourceURLChanged();\n } else if (name == \"disabled\") {\n this.delegate.disabledChanged();\n }\n }\n\n /**\n * Gets the URL to lazily load source HTML from\n */\n get src() {\n return this.getAttribute(\"src\")\n }\n\n /**\n * Sets the URL to lazily load source HTML from\n */\n set src(value) {\n if (value) {\n this.setAttribute(\"src\", value);\n } else {\n this.removeAttribute(\"src\");\n }\n }\n\n /**\n * Gets the refresh mode for the frame.\n */\n get refresh() {\n return this.getAttribute(\"refresh\")\n }\n\n /**\n * Sets the refresh mode for the frame.\n */\n set refresh(value) {\n if (value) {\n this.setAttribute(\"refresh\", value);\n } else {\n this.removeAttribute(\"refresh\");\n }\n }\n\n get shouldReloadWithMorph() {\n return this.src && this.refresh === \"morph\"\n }\n\n /**\n * Determines if the element is loading\n */\n get loading() {\n return frameLoadingStyleFromString(this.getAttribute(\"loading\") || \"\")\n }\n\n /**\n * Sets the value of if the element is loading\n */\n set loading(value) {\n if (value) {\n this.setAttribute(\"loading\", value);\n } else {\n this.removeAttribute(\"loading\");\n }\n }\n\n /**\n * Gets the disabled state of the frame.\n *\n * If disabled, no requests will be intercepted by the frame.\n */\n get disabled() {\n return this.hasAttribute(\"disabled\")\n }\n\n /**\n * Sets the disabled state of the frame.\n *\n * If disabled, no requests will be intercepted by the frame.\n */\n set disabled(value) {\n if (value) {\n this.setAttribute(\"disabled\", \"\");\n } else {\n this.removeAttribute(\"disabled\");\n }\n }\n\n /**\n * Gets the autoscroll state of the frame.\n *\n * If true, the frame will be scrolled into view automatically on update.\n */\n get autoscroll() {\n return this.hasAttribute(\"autoscroll\")\n }\n\n /**\n * Sets the autoscroll state of the frame.\n *\n * If true, the frame will be scrolled into view automatically on update.\n */\n set autoscroll(value) {\n if (value) {\n this.setAttribute(\"autoscroll\", \"\");\n } else {\n this.removeAttribute(\"autoscroll\");\n }\n }\n\n /**\n * Determines if the element has finished loading\n */\n get complete() {\n return !this.delegate.isLoading\n }\n\n /**\n * Gets the active state of the frame.\n *\n * If inactive, source changes will not be observed.\n */\n get isActive() {\n return this.ownerDocument === document && !this.isPreview\n }\n\n /**\n * Sets the active state of the frame.\n *\n * If inactive, source changes will not be observed.\n */\n get isPreview() {\n return this.ownerDocument?.documentElement?.hasAttribute(\"data-turbo-preview\")\n }\n}\n\nfunction frameLoadingStyleFromString(style) {\n switch (style.toLowerCase()) {\n case \"lazy\":\n return FrameLoadingStyle.lazy\n default:\n return FrameLoadingStyle.eager\n }\n}\n\nconst drive = {\n enabled: true,\n progressBarDelay: 500,\n unvisitableExtensions: new Set(\n [\n \".7z\", \".aac\", \".apk\", \".avi\", \".bmp\", \".bz2\", \".css\", \".csv\", \".deb\", \".dmg\", \".doc\",\n \".docx\", \".exe\", \".gif\", \".gz\", \".heic\", \".heif\", \".ico\", \".iso\", \".jpeg\", \".jpg\",\n \".js\", \".json\", \".m4a\", \".mkv\", \".mov\", \".mp3\", \".mp4\", \".mpeg\", \".mpg\", \".msi\",\n \".ogg\", \".ogv\", \".pdf\", \".pkg\", \".png\", \".ppt\", \".pptx\", \".rar\", \".rtf\",\n \".svg\", \".tar\", \".tif\", \".tiff\", \".txt\", \".wav\", \".webm\", \".webp\", \".wma\", \".wmv\",\n \".xls\", \".xlsx\", \".xml\", \".zip\"\n ]\n )\n};\n\nfunction activateScriptElement(element) {\n if (element.getAttribute(\"data-turbo-eval\") == \"false\") {\n return element\n } else {\n const createdScriptElement = document.createElement(\"script\");\n const cspNonce = getCspNonce();\n if (cspNonce) {\n createdScriptElement.nonce = cspNonce;\n }\n createdScriptElement.textContent = element.textContent;\n createdScriptElement.async = false;\n copyElementAttributes(createdScriptElement, element);\n return createdScriptElement\n }\n}\n\nfunction copyElementAttributes(destinationElement, sourceElement) {\n for (const { name, value } of sourceElement.attributes) {\n destinationElement.setAttribute(name, value);\n }\n}\n\nfunction createDocumentFragment(html) {\n const template = document.createElement(\"template\");\n template.innerHTML = html;\n return template.content\n}\n\nfunction dispatch(eventName, { target, cancelable, detail } = {}) {\n const event = new CustomEvent(eventName, {\n cancelable,\n bubbles: true,\n composed: true,\n detail\n });\n\n if (target && target.isConnected) {\n target.dispatchEvent(event);\n } else {\n document.documentElement.dispatchEvent(event);\n }\n\n return event\n}\n\nfunction cancelEvent(event) {\n event.preventDefault();\n event.stopImmediatePropagation();\n}\n\nfunction nextRepaint() {\n if (document.visibilityState === \"hidden\") {\n return nextEventLoopTick()\n } else {\n return nextAnimationFrame()\n }\n}\n\nfunction nextAnimationFrame() {\n return new Promise((resolve) => requestAnimationFrame(() => resolve()))\n}\n\nfunction nextEventLoopTick() {\n return new Promise((resolve) => setTimeout(() => resolve(), 0))\n}\n\nfunction parseHTMLDocument(html = \"\") {\n return new DOMParser().parseFromString(html, \"text/html\")\n}\n\nfunction unindent(strings, ...values) {\n const lines = interpolate(strings, values).replace(/^\\n/, \"\").split(\"\\n\");\n const match = lines[0].match(/^\\s+/);\n const indent = match ? match[0].length : 0;\n return lines.map((line) => line.slice(indent)).join(\"\\n\")\n}\n\nfunction interpolate(strings, values) {\n return strings.reduce((result, string, i) => {\n const value = values[i] == undefined ? \"\" : values[i];\n return result + string + value\n }, \"\")\n}\n\nfunction uuid() {\n return Array.from({ length: 36 })\n .map((_, i) => {\n if (i == 8 || i == 13 || i == 18 || i == 23) {\n return \"-\"\n } else if (i == 14) {\n return \"4\"\n } else if (i == 19) {\n return (Math.floor(Math.random() * 4) + 8).toString(16)\n } else {\n return Math.floor(Math.random() * 16).toString(16)\n }\n })\n .join(\"\")\n}\n\nfunction getAttribute(attributeName, ...elements) {\n for (const value of elements.map((element) => element?.getAttribute(attributeName))) {\n if (typeof value == \"string\") return value\n }\n\n return null\n}\n\nfunction hasAttribute(attributeName, ...elements) {\n return elements.some((element) => element && element.hasAttribute(attributeName))\n}\n\nfunction markAsBusy(...elements) {\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.setAttribute(\"busy\", \"\");\n }\n element.setAttribute(\"aria-busy\", \"true\");\n }\n}\n\nfunction clearBusyState(...elements) {\n for (const element of elements) {\n if (element.localName == \"turbo-frame\") {\n element.removeAttribute(\"busy\");\n }\n\n element.removeAttribute(\"aria-busy\");\n }\n}\n\nfunction waitForLoad(element, timeoutInMilliseconds = 2000) {\n return new Promise((resolve) => {\n const onComplete = () => {\n element.removeEventListener(\"error\", onComplete);\n element.removeEventListener(\"load\", onComplete);\n resolve();\n };\n\n element.addEventListener(\"load\", onComplete, { once: true });\n element.addEventListener(\"error\", onComplete, { once: true });\n setTimeout(resolve, timeoutInMilliseconds);\n })\n}\n\nfunction getHistoryMethodForAction(action) {\n switch (action) {\n case \"replace\":\n return history.replaceState\n case \"advance\":\n case \"restore\":\n return history.pushState\n }\n}\n\nfunction isAction(action) {\n return action == \"advance\" || action == \"replace\" || action == \"restore\"\n}\n\nfunction getVisitAction(...elements) {\n const action = getAttribute(\"data-turbo-action\", ...elements);\n\n return isAction(action) ? action : null\n}\n\nfunction getMetaElement(name) {\n return document.querySelector(`meta[name=\"${name}\"]`)\n}\n\nfunction getMetaContent(name) {\n const element = getMetaElement(name);\n return element && element.content\n}\n\nfunction getCspNonce() {\n const element = getMetaElement(\"csp-nonce\");\n\n if (element) {\n const { nonce, content } = element;\n return nonce == \"\" ? content : nonce\n }\n}\n\nfunction setMetaContent(name, content) {\n let element = getMetaElement(name);\n\n if (!element) {\n element = document.createElement(\"meta\");\n element.setAttribute(\"name\", name);\n\n document.head.appendChild(element);\n }\n\n element.setAttribute(\"content\", content);\n\n return element\n}\n\nfunction findClosestRecursively(element, selector) {\n if (element instanceof Element) {\n return (\n element.closest(selector) || findClosestRecursively(element.assignedSlot || element.getRootNode()?.host, selector)\n )\n }\n}\n\nfunction elementIsFocusable(element) {\n const inertDisabledOrHidden = \"[inert], :disabled, [hidden], details:not([open]), dialog:not([open])\";\n\n return !!element && element.closest(inertDisabledOrHidden) == null && typeof element.focus == \"function\"\n}\n\nfunction queryAutofocusableElement(elementOrDocumentFragment) {\n return Array.from(elementOrDocumentFragment.querySelectorAll(\"[autofocus]\")).find(elementIsFocusable)\n}\n\nasync function around(callback, reader) {\n const before = reader();\n\n callback();\n\n await nextAnimationFrame();\n\n const after = reader();\n\n return [before, after]\n}\n\nfunction doesNotTargetIFrame(name) {\n if (name === \"_blank\") {\n return false\n } else if (name) {\n for (const element of document.getElementsByName(name)) {\n if (element instanceof HTMLIFrameElement) return false\n }\n\n return true\n } else {\n return true\n }\n}\n\nfunction findLinkFromClickTarget(target) {\n const link = findClosestRecursively(target, \"a[href], a[xlink\\\\:href]\");\n\n if (!link) return null\n if (link.href.startsWith(\"#\")) return null\n if (link.hasAttribute(\"download\")) return null\n\n const linkTarget = link.getAttribute(\"target\");\n if (linkTarget && linkTarget !== \"_self\") return null\n\n return link\n}\n\nfunction debounce(fn, delay) {\n let timeoutId = null;\n\n return (...args) => {\n const callback = () => fn.apply(this, args);\n clearTimeout(timeoutId);\n timeoutId = setTimeout(callback, delay);\n }\n}\n\nconst submitter = {\n \"aria-disabled\": {\n beforeSubmit: submitter => {\n submitter.setAttribute(\"aria-disabled\", \"true\");\n submitter.addEventListener(\"click\", cancelEvent);\n },\n\n afterSubmit: submitter => {\n submitter.removeAttribute(\"aria-disabled\");\n submitter.removeEventListener(\"click\", cancelEvent);\n }\n },\n\n \"disabled\": {\n beforeSubmit: submitter => submitter.disabled = true,\n afterSubmit: submitter => submitter.disabled = false\n }\n};\n\nclass Config {\n #submitter = null\n\n constructor(config) {\n Object.assign(this, config);\n }\n\n get submitter() {\n return this.#submitter\n }\n\n set submitter(value) {\n this.#submitter = submitter[value] || value;\n }\n}\n\nconst forms = new Config({\n mode: \"on\",\n submitter: \"disabled\"\n});\n\nconst config = {\n drive,\n forms\n};\n\nfunction expandURL(locatable) {\n return new URL(locatable.toString(), document.baseURI)\n}\n\nfunction getAnchor(url) {\n let anchorMatch;\n if (url.hash) {\n return url.hash.slice(1)\n // eslint-disable-next-line no-cond-assign\n } else if ((anchorMatch = url.href.match(/#(.*)$/))) {\n return anchorMatch[1]\n }\n}\n\nfunction getAction$1(form, submitter) {\n const action = submitter?.getAttribute(\"formaction\") || form.getAttribute(\"action\") || form.action;\n\n return expandURL(action)\n}\n\nfunction getExtension(url) {\n return (getLastPathComponent(url).match(/\\.[^.]*$/) || [])[0] || \"\"\n}\n\nfunction isPrefixedBy(baseURL, url) {\n const prefix = addTrailingSlash(url.origin + url.pathname);\n return addTrailingSlash(baseURL.href) === prefix || baseURL.href.startsWith(prefix)\n}\n\nfunction locationIsVisitable(location, rootLocation) {\n return isPrefixedBy(location, rootLocation) && !config.drive.unvisitableExtensions.has(getExtension(location))\n}\n\nfunction getLocationForLink(link) {\n return expandURL(link.getAttribute(\"href\") || \"\")\n}\n\nfunction getRequestURL(url) {\n const anchor = getAnchor(url);\n return anchor != null ? url.href.slice(0, -(anchor.length + 1)) : url.href\n}\n\nfunction toCacheKey(url) {\n return getRequestURL(url)\n}\n\nfunction urlsAreEqual(left, right) {\n return expandURL(left).href == expandURL(right).href\n}\n\nfunction getPathComponents(url) {\n return url.pathname.split(\"/\").slice(1)\n}\n\nfunction getLastPathComponent(url) {\n return getPathComponents(url).slice(-1)[0]\n}\n\nfunction addTrailingSlash(value) {\n return value.endsWith(\"/\") ? value : value + \"/\"\n}\n\nclass FetchResponse {\n constructor(response) {\n this.response = response;\n }\n\n get succeeded() {\n return this.response.ok\n }\n\n get failed() {\n return !this.succeeded\n }\n\n get clientError() {\n return this.statusCode >= 400 && this.statusCode <= 499\n }\n\n get serverError() {\n return this.statusCode >= 500 && this.statusCode <= 599\n }\n\n get redirected() {\n return this.response.redirected\n }\n\n get location() {\n return expandURL(this.response.url)\n }\n\n get isHTML() {\n return this.contentType && this.contentType.match(/^(?:text\\/([^\\s;,]+\\b)?html|application\\/xhtml\\+xml)\\b/)\n }\n\n get statusCode() {\n return this.response.status\n }\n\n get contentType() {\n return this.header(\"Content-Type\")\n }\n\n get responseText() {\n return this.response.clone().text()\n }\n\n get responseHTML() {\n if (this.isHTML) {\n return this.response.clone().text()\n } else {\n return Promise.resolve(undefined)\n }\n }\n\n header(name) {\n return this.response.headers.get(name)\n }\n}\n\nclass LimitedSet extends Set {\n constructor(maxSize) {\n super();\n this.maxSize = maxSize;\n }\n\n add(value) {\n if (this.size >= this.maxSize) {\n const iterator = this.values();\n const oldestValue = iterator.next().value;\n this.delete(oldestValue);\n }\n super.add(value);\n }\n}\n\nconst recentRequests = new LimitedSet(20);\n\nfunction fetchWithTurboHeaders(url, options = {}) {\n const modifiedHeaders = new Headers(options.headers || {});\n const requestUID = uuid();\n recentRequests.add(requestUID);\n modifiedHeaders.append(\"X-Turbo-Request-Id\", requestUID);\n\n return window.fetch(url, {\n ...options,\n headers: modifiedHeaders\n })\n}\n\nfunction fetchMethodFromString(method) {\n switch (method.toLowerCase()) {\n case \"get\":\n return FetchMethod.get\n case \"post\":\n return FetchMethod.post\n case \"put\":\n return FetchMethod.put\n case \"patch\":\n return FetchMethod.patch\n case \"delete\":\n return FetchMethod.delete\n }\n}\n\nconst FetchMethod = {\n get: \"get\",\n post: \"post\",\n put: \"put\",\n patch: \"patch\",\n delete: \"delete\"\n};\n\nfunction fetchEnctypeFromString(encoding) {\n switch (encoding.toLowerCase()) {\n case FetchEnctype.multipart:\n return FetchEnctype.multipart\n case FetchEnctype.plain:\n return FetchEnctype.plain\n default:\n return FetchEnctype.urlEncoded\n }\n}\n\nconst FetchEnctype = {\n urlEncoded: \"application/x-www-form-urlencoded\",\n multipart: \"multipart/form-data\",\n plain: \"text/plain\"\n};\n\nclass FetchRequest {\n abortController = new AbortController()\n #resolveRequestPromise = (_value) => {}\n\n constructor(delegate, method, location, requestBody = new URLSearchParams(), target = null, enctype = FetchEnctype.urlEncoded) {\n const [url, body] = buildResourceAndBody(expandURL(location), method, requestBody, enctype);\n\n this.delegate = delegate;\n this.url = url;\n this.target = target;\n this.fetchOptions = {\n credentials: \"same-origin\",\n redirect: \"follow\",\n method: method.toUpperCase(),\n headers: { ...this.defaultHeaders },\n body: body,\n signal: this.abortSignal,\n referrer: this.delegate.referrer?.href\n };\n this.enctype = enctype;\n }\n\n get method() {\n return this.fetchOptions.method\n }\n\n set method(value) {\n const fetchBody = this.isSafe ? this.url.searchParams : this.fetchOptions.body || new FormData();\n const fetchMethod = fetchMethodFromString(value) || FetchMethod.get;\n\n this.url.search = \"\";\n\n const [url, body] = buildResourceAndBody(this.url, fetchMethod, fetchBody, this.enctype);\n\n this.url = url;\n this.fetchOptions.body = body;\n this.fetchOptions.method = fetchMethod.toUpperCase();\n }\n\n get headers() {\n return this.fetchOptions.headers\n }\n\n set headers(value) {\n this.fetchOptions.headers = value;\n }\n\n get body() {\n if (this.isSafe) {\n return this.url.searchParams\n } else {\n return this.fetchOptions.body\n }\n }\n\n set body(value) {\n this.fetchOptions.body = value;\n }\n\n get location() {\n return this.url\n }\n\n get params() {\n return this.url.searchParams\n }\n\n get entries() {\n return this.body ? Array.from(this.body.entries()) : []\n }\n\n cancel() {\n this.abortController.abort();\n }\n\n async perform() {\n const { fetchOptions } = this;\n this.delegate.prepareRequest(this);\n const event = await this.#allowRequestToBeIntercepted(fetchOptions);\n try {\n this.delegate.requestStarted(this);\n\n if (event.detail.fetchRequest) {\n this.response = event.detail.fetchRequest.response;\n } else {\n this.response = fetchWithTurboHeaders(this.url.href, fetchOptions);\n }\n\n const response = await this.response;\n return await this.receive(response)\n } catch (error) {\n if (error.name !== \"AbortError\") {\n if (this.#willDelegateErrorHandling(error)) {\n this.delegate.requestErrored(this, error);\n }\n throw error\n }\n } finally {\n this.delegate.requestFinished(this);\n }\n }\n\n async receive(response) {\n const fetchResponse = new FetchResponse(response);\n const event = dispatch(\"turbo:before-fetch-response\", {\n cancelable: true,\n detail: { fetchResponse },\n target: this.target\n });\n if (event.defaultPrevented) {\n this.delegate.requestPreventedHandlingResponse(this, fetchResponse);\n } else if (fetchResponse.succeeded) {\n this.delegate.requestSucceededWithResponse(this, fetchResponse);\n } else {\n this.delegate.requestFailedWithResponse(this, fetchResponse);\n }\n return fetchResponse\n }\n\n get defaultHeaders() {\n return {\n Accept: \"text/html, application/xhtml+xml\"\n }\n }\n\n get isSafe() {\n return isSafe(this.method)\n }\n\n get abortSignal() {\n return this.abortController.signal\n }\n\n acceptResponseType(mimeType) {\n this.headers[\"Accept\"] = [mimeType, this.headers[\"Accept\"]].join(\", \");\n }\n\n async #allowRequestToBeIntercepted(fetchOptions) {\n const requestInterception = new Promise((resolve) => (this.#resolveRequestPromise = resolve));\n const event = dispatch(\"turbo:before-fetch-request\", {\n cancelable: true,\n detail: {\n fetchOptions,\n url: this.url,\n resume: this.#resolveRequestPromise\n },\n target: this.target\n });\n this.url = event.detail.url;\n if (event.defaultPrevented) await requestInterception;\n\n return event\n }\n\n #willDelegateErrorHandling(error) {\n const event = dispatch(\"turbo:fetch-request-error\", {\n target: this.target,\n cancelable: true,\n detail: { request: this, error: error }\n });\n\n return !event.defaultPrevented\n }\n}\n\nfunction isSafe(fetchMethod) {\n return fetchMethodFromString(fetchMethod) == FetchMethod.get\n}\n\nfunction buildResourceAndBody(resource, method, requestBody, enctype) {\n const searchParams =\n Array.from(requestBody).length > 0 ? new URLSearchParams(entriesExcludingFiles(requestBody)) : resource.searchParams;\n\n if (isSafe(method)) {\n return [mergeIntoURLSearchParams(resource, searchParams), null]\n } else if (enctype == FetchEnctype.urlEncoded) {\n return [resource, searchParams]\n } else {\n return [resource, requestBody]\n }\n}\n\nfunction entriesExcludingFiles(requestBody) {\n const entries = [];\n\n for (const [name, value] of requestBody) {\n if (value instanceof File) continue\n else entries.push([name, value]);\n }\n\n return entries\n}\n\nfunction mergeIntoURLSearchParams(url, requestBody) {\n const searchParams = new URLSearchParams(entriesExcludingFiles(requestBody));\n\n url.search = searchParams.toString();\n\n return url\n}\n\nclass AppearanceObserver {\n started = false\n\n constructor(delegate, element) {\n this.delegate = delegate;\n this.element = element;\n this.intersectionObserver = new IntersectionObserver(this.intersect);\n }\n\n start() {\n if (!this.started) {\n this.started = true;\n this.intersectionObserver.observe(this.element);\n }\n }\n\n stop() {\n if (this.started) {\n this.started = false;\n this.intersectionObserver.unobserve(this.element);\n }\n }\n\n intersect = (entries) => {\n const lastEntry = entries.slice(-1)[0];\n if (lastEntry?.isIntersecting) {\n this.delegate.elementAppearedInViewport(this.element);\n }\n }\n}\n\nclass StreamMessage {\n static contentType = \"text/vnd.turbo-stream.html\"\n\n static wrap(message) {\n if (typeof message == \"string\") {\n return new this(createDocumentFragment(message))\n } else {\n return message\n }\n }\n\n constructor(fragment) {\n this.fragment = importStreamElements(fragment);\n }\n}\n\nfunction importStreamElements(fragment) {\n for (const element of fragment.querySelectorAll(\"turbo-stream\")) {\n const streamElement = document.importNode(element, true);\n\n for (const inertScriptElement of streamElement.templateElement.content.querySelectorAll(\"script\")) {\n inertScriptElement.replaceWith(activateScriptElement(inertScriptElement));\n }\n\n element.replaceWith(streamElement);\n }\n\n return fragment\n}\n\nconst identity = key => key;\n\nclass LRUCache {\n keys = []\n entries = {}\n #toCacheKey\n\n constructor(size, toCacheKey = identity) {\n this.size = size;\n this.#toCacheKey = toCacheKey;\n }\n\n has(key) {\n return this.#toCacheKey(key) in this.entries\n }\n\n get(key) {\n if (this.has(key)) {\n const entry = this.read(key);\n this.touch(key);\n return entry\n }\n }\n\n put(key, entry) {\n this.write(key, entry);\n this.touch(key);\n return entry\n }\n\n clear() {\n for (const key of Object.keys(this.entries)) {\n this.evict(key);\n }\n }\n\n // Private\n\n read(key) {\n return this.entries[this.#toCacheKey(key)]\n }\n\n write(key, entry) {\n this.entries[this.#toCacheKey(key)] = entry;\n }\n\n touch(key) {\n key = this.#toCacheKey(key);\n const index = this.keys.indexOf(key);\n if (index > -1) this.keys.splice(index, 1);\n this.keys.unshift(key);\n this.trim();\n }\n\n trim() {\n for (const key of this.keys.splice(this.size)) {\n this.evict(key);\n }\n }\n\n evict(key) {\n delete this.entries[key];\n }\n}\n\nconst PREFETCH_DELAY = 100;\n\nclass PrefetchCache extends LRUCache {\n #prefetchTimeout = null\n #maxAges = {}\n\n constructor(size = 1, prefetchDelay = PREFETCH_DELAY) {\n super(size, toCacheKey);\n this.prefetchDelay = prefetchDelay;\n }\n\n putLater(url, request, ttl) {\n this.#prefetchTimeout = setTimeout(() => {\n request.perform();\n this.put(url, request, ttl);\n this.#prefetchTimeout = null;\n }, this.prefetchDelay);\n }\n\n put(url, request, ttl = cacheTtl) {\n super.put(url, request);\n this.#maxAges[toCacheKey(url)] = new Date(new Date().getTime() + ttl);\n }\n\n clear() {\n super.clear();\n if (this.#prefetchTimeout) clearTimeout(this.#prefetchTimeout);\n }\n\n evict(key) {\n super.evict(key);\n delete this.#maxAges[key];\n }\n\n has(key) {\n if (super.has(key)) {\n const maxAge = this.#maxAges[toCacheKey(key)];\n\n return maxAge && maxAge > Date.now()\n } else {\n return false\n }\n }\n}\n\nconst cacheTtl = 10 * 1000;\nconst prefetchCache = new PrefetchCache();\n\nconst FormSubmissionState = {\n initialized: \"initialized\",\n requesting: \"requesting\",\n waiting: \"waiting\",\n receiving: \"receiving\",\n stopping: \"stopping\",\n stopped: \"stopped\"\n};\n\nclass FormSubmission {\n state = FormSubmissionState.initialized\n\n static confirmMethod(message) {\n return Promise.resolve(confirm(message))\n }\n\n constructor(delegate, formElement, submitter, mustRedirect = false) {\n const method = getMethod(formElement, submitter);\n const action = getAction(getFormAction(formElement, submitter), method);\n const body = buildFormData(formElement, submitter);\n const enctype = getEnctype(formElement, submitter);\n\n this.delegate = delegate;\n this.formElement = formElement;\n this.submitter = submitter;\n this.fetchRequest = new FetchRequest(this, method, action, body, formElement, enctype);\n this.mustRedirect = mustRedirect;\n }\n\n get method() {\n return this.fetchRequest.method\n }\n\n set method(value) {\n this.fetchRequest.method = value;\n }\n\n get action() {\n return this.fetchRequest.url.toString()\n }\n\n set action(value) {\n this.fetchRequest.url = expandURL(value);\n }\n\n get body() {\n return this.fetchRequest.body\n }\n\n get enctype() {\n return this.fetchRequest.enctype\n }\n\n get isSafe() {\n return this.fetchRequest.isSafe\n }\n\n get location() {\n return this.fetchRequest.url\n }\n\n // The submission process\n\n async start() {\n const { initialized, requesting } = FormSubmissionState;\n const confirmationMessage = getAttribute(\"data-turbo-confirm\", this.submitter, this.formElement);\n\n if (typeof confirmationMessage === \"string\") {\n const confirmMethod = typeof config.forms.confirm === \"function\" ?\n config.forms.confirm :\n FormSubmission.confirmMethod;\n\n const answer = await confirmMethod(confirmationMessage, this.formElement, this.submitter);\n if (!answer) {\n return\n }\n }\n\n if (this.state == initialized) {\n this.state = requesting;\n return this.fetchRequest.perform()\n }\n }\n\n stop() {\n const { stopping, stopped } = FormSubmissionState;\n if (this.state != stopping && this.state != stopped) {\n this.state = stopping;\n this.fetchRequest.cancel();\n return true\n }\n }\n\n // Fetch request delegate\n\n prepareRequest(request) {\n if (!request.isSafe) {\n const token = getCookieValue(getMetaContent(\"csrf-param\")) || getMetaContent(\"csrf-token\");\n if (token) {\n request.headers[\"X-CSRF-Token\"] = token;\n }\n }\n\n if (this.requestAcceptsTurboStreamResponse(request)) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n\n requestStarted(_request) {\n this.state = FormSubmissionState.waiting;\n if (this.submitter) config.forms.submitter.beforeSubmit(this.submitter);\n this.setSubmitsWith();\n markAsBusy(this.formElement);\n dispatch(\"turbo:submit-start\", {\n target: this.formElement,\n detail: { formSubmission: this }\n });\n this.delegate.formSubmissionStarted(this);\n }\n\n requestPreventedHandlingResponse(request, response) {\n prefetchCache.clear();\n\n this.result = { success: response.succeeded, fetchResponse: response };\n }\n\n requestSucceededWithResponse(request, response) {\n if (response.clientError || response.serverError) {\n this.delegate.formSubmissionFailedWithResponse(this, response);\n return\n }\n\n prefetchCache.clear();\n\n if (this.requestMustRedirect(request) && responseSucceededWithoutRedirect(response)) {\n const error = new Error(\"Form responses must redirect to another location\");\n this.delegate.formSubmissionErrored(this, error);\n } else {\n this.state = FormSubmissionState.receiving;\n this.result = { success: true, fetchResponse: response };\n this.delegate.formSubmissionSucceededWithResponse(this, response);\n }\n }\n\n requestFailedWithResponse(request, response) {\n this.result = { success: false, fetchResponse: response };\n this.delegate.formSubmissionFailedWithResponse(this, response);\n }\n\n requestErrored(request, error) {\n this.result = { success: false, error };\n this.delegate.formSubmissionErrored(this, error);\n }\n\n requestFinished(_request) {\n this.state = FormSubmissionState.stopped;\n if (this.submitter) config.forms.submitter.afterSubmit(this.submitter);\n this.resetSubmitterText();\n clearBusyState(this.formElement);\n dispatch(\"turbo:submit-end\", {\n target: this.formElement,\n detail: { formSubmission: this, ...this.result }\n });\n this.delegate.formSubmissionFinished(this);\n }\n\n // Private\n\n setSubmitsWith() {\n if (!this.submitter || !this.submitsWith) return\n\n if (this.submitter.matches(\"button\")) {\n this.originalSubmitText = this.submitter.innerHTML;\n this.submitter.innerHTML = this.submitsWith;\n } else if (this.submitter.matches(\"input\")) {\n const input = this.submitter;\n this.originalSubmitText = input.value;\n input.value = this.submitsWith;\n }\n }\n\n resetSubmitterText() {\n if (!this.submitter || !this.originalSubmitText) return\n\n if (this.submitter.matches(\"button\")) {\n this.submitter.innerHTML = this.originalSubmitText;\n } else if (this.submitter.matches(\"input\")) {\n const input = this.submitter;\n input.value = this.originalSubmitText;\n }\n }\n\n requestMustRedirect(request) {\n return !request.isSafe && this.mustRedirect\n }\n\n requestAcceptsTurboStreamResponse(request) {\n return !request.isSafe || hasAttribute(\"data-turbo-stream\", this.submitter, this.formElement)\n }\n\n get submitsWith() {\n return this.submitter?.getAttribute(\"data-turbo-submits-with\")\n }\n}\n\nfunction buildFormData(formElement, submitter) {\n const formData = new FormData(formElement);\n const name = submitter?.getAttribute(\"name\");\n const value = submitter?.getAttribute(\"value\");\n\n if (name) {\n formData.append(name, value || \"\");\n }\n\n return formData\n}\n\nfunction getCookieValue(cookieName) {\n if (cookieName != null) {\n const cookies = document.cookie ? document.cookie.split(\"; \") : [];\n const cookie = cookies.find((cookie) => cookie.startsWith(cookieName));\n if (cookie) {\n const value = cookie.split(\"=\").slice(1).join(\"=\");\n return value ? decodeURIComponent(value) : undefined\n }\n }\n}\n\nfunction responseSucceededWithoutRedirect(response) {\n return response.statusCode == 200 && !response.redirected\n}\n\nfunction getFormAction(formElement, submitter) {\n const formElementAction = typeof formElement.action === \"string\" ? formElement.action : null;\n\n if (submitter?.hasAttribute(\"formaction\")) {\n return submitter.getAttribute(\"formaction\") || \"\"\n } else {\n return formElement.getAttribute(\"action\") || formElementAction || \"\"\n }\n}\n\nfunction getAction(formAction, fetchMethod) {\n const action = expandURL(formAction);\n\n if (isSafe(fetchMethod)) {\n action.search = \"\";\n }\n\n return action\n}\n\nfunction getMethod(formElement, submitter) {\n const method = submitter?.getAttribute(\"formmethod\") || formElement.getAttribute(\"method\") || \"\";\n return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get\n}\n\nfunction getEnctype(formElement, submitter) {\n return fetchEnctypeFromString(submitter?.getAttribute(\"formenctype\") || formElement.enctype)\n}\n\nclass Snapshot {\n constructor(element) {\n this.element = element;\n }\n\n get activeElement() {\n return this.element.ownerDocument.activeElement\n }\n\n get children() {\n return [...this.element.children]\n }\n\n hasAnchor(anchor) {\n return this.getElementForAnchor(anchor) != null\n }\n\n getElementForAnchor(anchor) {\n return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null\n }\n\n get isConnected() {\n return this.element.isConnected\n }\n\n get firstAutofocusableElement() {\n return queryAutofocusableElement(this.element)\n }\n\n get permanentElements() {\n return queryPermanentElementsAll(this.element)\n }\n\n getPermanentElementById(id) {\n return getPermanentElementById(this.element, id)\n }\n\n getPermanentElementMapForSnapshot(snapshot) {\n const permanentElementMap = {};\n\n for (const currentPermanentElement of this.permanentElements) {\n const { id } = currentPermanentElement;\n const newPermanentElement = snapshot.getPermanentElementById(id);\n if (newPermanentElement) {\n permanentElementMap[id] = [currentPermanentElement, newPermanentElement];\n }\n }\n\n return permanentElementMap\n }\n}\n\nfunction getPermanentElementById(node, id) {\n return node.querySelector(`#${id}[data-turbo-permanent]`)\n}\n\nfunction queryPermanentElementsAll(node) {\n return node.querySelectorAll(\"[id][data-turbo-permanent]\")\n}\n\nclass FormSubmitObserver {\n started = false\n\n constructor(delegate, eventTarget) {\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n\n start() {\n if (!this.started) {\n this.eventTarget.addEventListener(\"submit\", this.submitCaptured, true);\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n this.eventTarget.removeEventListener(\"submit\", this.submitCaptured, true);\n this.started = false;\n }\n }\n\n submitCaptured = () => {\n this.eventTarget.removeEventListener(\"submit\", this.submitBubbled, false);\n this.eventTarget.addEventListener(\"submit\", this.submitBubbled, false);\n }\n\n submitBubbled = (event) => {\n if (!event.defaultPrevented) {\n const form = event.target instanceof HTMLFormElement ? event.target : undefined;\n const submitter = event.submitter || undefined;\n\n if (\n form &&\n submissionDoesNotDismissDialog(form, submitter) &&\n submissionDoesNotTargetIFrame(form, submitter) &&\n this.delegate.willSubmitForm(form, submitter)\n ) {\n event.preventDefault();\n event.stopImmediatePropagation();\n this.delegate.formSubmitted(form, submitter);\n }\n }\n }\n}\n\nfunction submissionDoesNotDismissDialog(form, submitter) {\n const method = submitter?.getAttribute(\"formmethod\") || form.getAttribute(\"method\");\n\n return method != \"dialog\"\n}\n\nfunction submissionDoesNotTargetIFrame(form, submitter) {\n const target = submitter?.getAttribute(\"formtarget\") || form.getAttribute(\"target\");\n\n return doesNotTargetIFrame(target)\n}\n\nclass View {\n #resolveRenderPromise = (_value) => {}\n #resolveInterceptionPromise = (_value) => {}\n\n constructor(delegate, element) {\n this.delegate = delegate;\n this.element = element;\n }\n\n // Scrolling\n\n scrollToAnchor(anchor) {\n const element = this.snapshot.getElementForAnchor(anchor);\n if (element) {\n this.focusElement(element);\n this.scrollToElement(element);\n } else {\n this.scrollToPosition({ x: 0, y: 0 });\n }\n }\n\n scrollToAnchorFromLocation(location) {\n this.scrollToAnchor(getAnchor(location));\n }\n\n scrollToElement(element) {\n element.scrollIntoView();\n }\n\n focusElement(element) {\n if (element instanceof HTMLElement) {\n if (element.hasAttribute(\"tabindex\")) {\n element.focus();\n } else {\n element.setAttribute(\"tabindex\", \"-1\");\n element.focus();\n element.removeAttribute(\"tabindex\");\n }\n }\n }\n\n scrollToPosition({ x, y }) {\n this.scrollRoot.scrollTo(x, y);\n }\n\n scrollToTop() {\n this.scrollToPosition({ x: 0, y: 0 });\n }\n\n get scrollRoot() {\n return window\n }\n\n // Rendering\n\n async render(renderer) {\n const { isPreview, shouldRender, willRender, newSnapshot: snapshot } = renderer;\n\n // A workaround to ignore tracked element mismatch reloads when performing\n // a promoted Visit from a frame navigation\n const shouldInvalidate = willRender;\n\n if (shouldRender) {\n try {\n this.renderPromise = new Promise((resolve) => (this.#resolveRenderPromise = resolve));\n this.renderer = renderer;\n await this.prepareToRenderSnapshot(renderer);\n\n const renderInterception = new Promise((resolve) => (this.#resolveInterceptionPromise = resolve));\n const options = { resume: this.#resolveInterceptionPromise, render: this.renderer.renderElement, renderMethod: this.renderer.renderMethod };\n const immediateRender = this.delegate.allowsImmediateRender(snapshot, options);\n if (!immediateRender) await renderInterception;\n\n await this.renderSnapshot(renderer);\n this.delegate.viewRenderedSnapshot(snapshot, isPreview, this.renderer.renderMethod);\n this.delegate.preloadOnLoadLinksForView(this.element);\n this.finishRenderingSnapshot(renderer);\n } finally {\n delete this.renderer;\n this.#resolveRenderPromise(undefined);\n delete this.renderPromise;\n }\n } else if (shouldInvalidate) {\n this.invalidate(renderer.reloadReason);\n }\n }\n\n invalidate(reason) {\n this.delegate.viewInvalidated(reason);\n }\n\n async prepareToRenderSnapshot(renderer) {\n this.markAsPreview(renderer.isPreview);\n await renderer.prepareToRender();\n }\n\n markAsPreview(isPreview) {\n if (isPreview) {\n this.element.setAttribute(\"data-turbo-preview\", \"\");\n } else {\n this.element.removeAttribute(\"data-turbo-preview\");\n }\n }\n\n markVisitDirection(direction) {\n this.element.setAttribute(\"data-turbo-visit-direction\", direction);\n }\n\n unmarkVisitDirection() {\n this.element.removeAttribute(\"data-turbo-visit-direction\");\n }\n\n async renderSnapshot(renderer) {\n await renderer.render();\n }\n\n finishRenderingSnapshot(renderer) {\n renderer.finishRendering();\n }\n}\n\nclass FrameView extends View {\n missing() {\n this.element.innerHTML = `Content missing`;\n }\n\n get snapshot() {\n return new Snapshot(this.element)\n }\n}\n\nclass LinkInterceptor {\n constructor(delegate, element) {\n this.delegate = delegate;\n this.element = element;\n }\n\n start() {\n this.element.addEventListener(\"click\", this.clickBubbled);\n document.addEventListener(\"turbo:click\", this.linkClicked);\n document.addEventListener(\"turbo:before-visit\", this.willVisit);\n }\n\n stop() {\n this.element.removeEventListener(\"click\", this.clickBubbled);\n document.removeEventListener(\"turbo:click\", this.linkClicked);\n document.removeEventListener(\"turbo:before-visit\", this.willVisit);\n }\n\n clickBubbled = (event) => {\n if (this.clickEventIsSignificant(event)) {\n this.clickEvent = event;\n } else {\n delete this.clickEvent;\n }\n }\n\n linkClicked = (event) => {\n if (this.clickEvent && this.clickEventIsSignificant(event)) {\n if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {\n this.clickEvent.preventDefault();\n event.preventDefault();\n this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);\n }\n }\n delete this.clickEvent;\n }\n\n willVisit = (_event) => {\n delete this.clickEvent;\n }\n\n clickEventIsSignificant(event) {\n const target = event.composed ? event.target?.parentElement : event.target;\n const element = findLinkFromClickTarget(target) || target;\n\n return element instanceof Element && element.closest(\"turbo-frame, html\") == this.element\n }\n}\n\nclass LinkClickObserver {\n started = false\n\n constructor(delegate, eventTarget) {\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n\n start() {\n if (!this.started) {\n this.eventTarget.addEventListener(\"click\", this.clickCaptured, true);\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n this.eventTarget.removeEventListener(\"click\", this.clickCaptured, true);\n this.started = false;\n }\n }\n\n clickCaptured = () => {\n this.eventTarget.removeEventListener(\"click\", this.clickBubbled, false);\n this.eventTarget.addEventListener(\"click\", this.clickBubbled, false);\n }\n\n clickBubbled = (event) => {\n if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {\n const target = (event.composedPath && event.composedPath()[0]) || event.target;\n const link = findLinkFromClickTarget(target);\n if (link && doesNotTargetIFrame(link.target)) {\n const location = getLocationForLink(link);\n if (this.delegate.willFollowLinkToLocation(link, location, event)) {\n event.preventDefault();\n this.delegate.followedLinkToLocation(link, location);\n }\n }\n }\n }\n\n clickEventIsSignificant(event) {\n return !(\n (event.target && event.target.isContentEditable) ||\n event.defaultPrevented ||\n event.which > 1 ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n )\n }\n}\n\nclass FormLinkClickObserver {\n constructor(delegate, element) {\n this.delegate = delegate;\n this.linkInterceptor = new LinkClickObserver(this, element);\n }\n\n start() {\n this.linkInterceptor.start();\n }\n\n stop() {\n this.linkInterceptor.stop();\n }\n\n // Link hover observer delegate\n\n canPrefetchRequestToLocation(link, location) {\n return false\n }\n\n prefetchAndCacheRequestToLocation(link, location) {\n return\n }\n\n // Link click observer delegate\n\n willFollowLinkToLocation(link, location, originalEvent) {\n return (\n this.delegate.willSubmitFormLinkToLocation(link, location, originalEvent) &&\n (link.hasAttribute(\"data-turbo-method\") || link.hasAttribute(\"data-turbo-stream\"))\n )\n }\n\n followedLinkToLocation(link, location) {\n const form = document.createElement(\"form\");\n\n const type = \"hidden\";\n for (const [name, value] of location.searchParams) {\n form.append(Object.assign(document.createElement(\"input\"), { type, name, value }));\n }\n\n const action = Object.assign(location, { search: \"\" });\n form.setAttribute(\"data-turbo\", \"true\");\n form.setAttribute(\"action\", action.href);\n form.setAttribute(\"hidden\", \"\");\n\n const method = link.getAttribute(\"data-turbo-method\");\n if (method) form.setAttribute(\"method\", method);\n\n const turboFrame = link.getAttribute(\"data-turbo-frame\");\n if (turboFrame) form.setAttribute(\"data-turbo-frame\", turboFrame);\n\n const turboAction = getVisitAction(link);\n if (turboAction) form.setAttribute(\"data-turbo-action\", turboAction);\n\n const turboConfirm = link.getAttribute(\"data-turbo-confirm\");\n if (turboConfirm) form.setAttribute(\"data-turbo-confirm\", turboConfirm);\n\n const turboStream = link.hasAttribute(\"data-turbo-stream\");\n if (turboStream) form.setAttribute(\"data-turbo-stream\", \"\");\n\n this.delegate.submittedFormLinkToLocation(link, location, form);\n\n document.body.appendChild(form);\n form.addEventListener(\"turbo:submit-end\", () => form.remove(), { once: true });\n requestAnimationFrame(() => form.requestSubmit());\n }\n}\n\nclass Bardo {\n static async preservingPermanentElements(delegate, permanentElementMap, callback) {\n const bardo = new this(delegate, permanentElementMap);\n bardo.enter();\n await callback();\n bardo.leave();\n }\n\n constructor(delegate, permanentElementMap) {\n this.delegate = delegate;\n this.permanentElementMap = permanentElementMap;\n }\n\n enter() {\n for (const id in this.permanentElementMap) {\n const [currentPermanentElement, newPermanentElement] = this.permanentElementMap[id];\n this.delegate.enteringBardo(currentPermanentElement, newPermanentElement);\n this.replaceNewPermanentElementWithPlaceholder(newPermanentElement);\n }\n }\n\n leave() {\n for (const id in this.permanentElementMap) {\n const [currentPermanentElement] = this.permanentElementMap[id];\n this.replaceCurrentPermanentElementWithClone(currentPermanentElement);\n this.replacePlaceholderWithPermanentElement(currentPermanentElement);\n this.delegate.leavingBardo(currentPermanentElement);\n }\n }\n\n replaceNewPermanentElementWithPlaceholder(permanentElement) {\n const placeholder = createPlaceholderForPermanentElement(permanentElement);\n permanentElement.replaceWith(placeholder);\n }\n\n replaceCurrentPermanentElementWithClone(permanentElement) {\n const clone = permanentElement.cloneNode(true);\n permanentElement.replaceWith(clone);\n }\n\n replacePlaceholderWithPermanentElement(permanentElement) {\n const placeholder = this.getPlaceholderById(permanentElement.id);\n placeholder?.replaceWith(permanentElement);\n }\n\n getPlaceholderById(id) {\n return this.placeholders.find((element) => element.content == id)\n }\n\n get placeholders() {\n return [...document.querySelectorAll(\"meta[name=turbo-permanent-placeholder][content]\")]\n }\n}\n\nfunction createPlaceholderForPermanentElement(permanentElement) {\n const element = document.createElement(\"meta\");\n element.setAttribute(\"name\", \"turbo-permanent-placeholder\");\n element.setAttribute(\"content\", permanentElement.id);\n return element\n}\n\nclass Renderer {\n #activeElement = null\n\n static renderElement(currentElement, newElement) {\n // Abstract method\n }\n\n constructor(currentSnapshot, newSnapshot, isPreview, willRender = true) {\n this.currentSnapshot = currentSnapshot;\n this.newSnapshot = newSnapshot;\n this.isPreview = isPreview;\n this.willRender = willRender;\n this.renderElement = this.constructor.renderElement;\n this.promise = new Promise((resolve, reject) => (this.resolvingFunctions = { resolve, reject }));\n }\n\n get shouldRender() {\n return true\n }\n\n get shouldAutofocus() {\n return true\n }\n\n get reloadReason() {\n return\n }\n\n prepareToRender() {\n return\n }\n\n render() {\n // Abstract method\n }\n\n finishRendering() {\n if (this.resolvingFunctions) {\n this.resolvingFunctions.resolve();\n delete this.resolvingFunctions;\n }\n }\n\n async preservingPermanentElements(callback) {\n await Bardo.preservingPermanentElements(this, this.permanentElementMap, callback);\n }\n\n focusFirstAutofocusableElement() {\n if (this.shouldAutofocus) {\n const element = this.connectedSnapshot.firstAutofocusableElement;\n if (element) {\n element.focus();\n }\n }\n }\n\n // Bardo delegate\n\n enteringBardo(currentPermanentElement) {\n if (this.#activeElement) return\n\n if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) {\n this.#activeElement = this.currentSnapshot.activeElement;\n }\n }\n\n leavingBardo(currentPermanentElement) {\n if (currentPermanentElement.contains(this.#activeElement) && this.#activeElement instanceof HTMLElement) {\n this.#activeElement.focus();\n\n this.#activeElement = null;\n }\n }\n\n get connectedSnapshot() {\n return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot\n }\n\n get currentElement() {\n return this.currentSnapshot.element\n }\n\n get newElement() {\n return this.newSnapshot.element\n }\n\n get permanentElementMap() {\n return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot)\n }\n\n get renderMethod() {\n return \"replace\"\n }\n}\n\nclass FrameRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n const destinationRange = document.createRange();\n destinationRange.selectNodeContents(currentElement);\n destinationRange.deleteContents();\n\n const frameElement = newElement;\n const sourceRange = frameElement.ownerDocument?.createRange();\n if (sourceRange) {\n sourceRange.selectNodeContents(frameElement);\n currentElement.appendChild(sourceRange.extractContents());\n }\n }\n\n constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {\n super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender);\n this.delegate = delegate;\n }\n\n get shouldRender() {\n return true\n }\n\n async render() {\n await nextRepaint();\n this.preservingPermanentElements(() => {\n this.loadFrameElement();\n });\n this.scrollFrameIntoView();\n await nextRepaint();\n this.focusFirstAutofocusableElement();\n await nextRepaint();\n this.activateScriptElements();\n }\n\n loadFrameElement() {\n this.delegate.willRenderFrame(this.currentElement, this.newElement);\n this.renderElement(this.currentElement, this.newElement);\n }\n\n scrollFrameIntoView() {\n if (this.currentElement.autoscroll || this.newElement.autoscroll) {\n const element = this.currentElement.firstElementChild;\n const block = readScrollLogicalPosition(this.currentElement.getAttribute(\"data-autoscroll-block\"), \"end\");\n const behavior = readScrollBehavior(this.currentElement.getAttribute(\"data-autoscroll-behavior\"), \"auto\");\n\n if (element) {\n element.scrollIntoView({ block, behavior });\n return true\n }\n }\n return false\n }\n\n activateScriptElements() {\n for (const inertScriptElement of this.newScriptElements) {\n const activatedScriptElement = activateScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n\n get newScriptElements() {\n return this.currentElement.querySelectorAll(\"script\")\n }\n}\n\nfunction readScrollLogicalPosition(value, defaultValue) {\n if (value == \"end\" || value == \"start\" || value == \"center\" || value == \"nearest\") {\n return value\n } else {\n return defaultValue\n }\n}\n\nfunction readScrollBehavior(value, defaultValue) {\n if (value == \"auto\" || value == \"smooth\") {\n return value\n } else {\n return defaultValue\n }\n}\n\n/**\n * @typedef {object} ConfigHead\n *\n * @property {'merge' | 'append' | 'morph' | 'none'} [style]\n * @property {boolean} [block]\n * @property {boolean} [ignore]\n * @property {function(Element): boolean} [shouldPreserve]\n * @property {function(Element): boolean} [shouldReAppend]\n * @property {function(Element): boolean} [shouldRemove]\n * @property {function(Element, {added: Node[], kept: Element[], removed: Element[]}): void} [afterHeadMorphed]\n */\n\n/**\n * @typedef {object} ConfigCallbacks\n *\n * @property {function(Node): boolean} [beforeNodeAdded]\n * @property {function(Node): void} [afterNodeAdded]\n * @property {function(Element, Node): boolean} [beforeNodeMorphed]\n * @property {function(Element, Node): void} [afterNodeMorphed]\n * @property {function(Element): boolean} [beforeNodeRemoved]\n * @property {function(Element): void} [afterNodeRemoved]\n * @property {function(string, Element, \"update\" | \"remove\"): boolean} [beforeAttributeUpdated]\n */\n\n/**\n * @typedef {object} Config\n *\n * @property {'outerHTML' | 'innerHTML'} [morphStyle]\n * @property {boolean} [ignoreActive]\n * @property {boolean} [ignoreActiveValue]\n * @property {boolean} [restoreFocus]\n * @property {ConfigCallbacks} [callbacks]\n * @property {ConfigHead} [head]\n */\n\n/**\n * @typedef {function} NoOp\n *\n * @returns {void}\n */\n\n/**\n * @typedef {object} ConfigHeadInternal\n *\n * @property {'merge' | 'append' | 'morph' | 'none'} style\n * @property {boolean} [block]\n * @property {boolean} [ignore]\n * @property {(function(Element): boolean) | NoOp} shouldPreserve\n * @property {(function(Element): boolean) | NoOp} shouldReAppend\n * @property {(function(Element): boolean) | NoOp} shouldRemove\n * @property {(function(Element, {added: Node[], kept: Element[], removed: Element[]}): void) | NoOp} afterHeadMorphed\n */\n\n/**\n * @typedef {object} ConfigCallbacksInternal\n *\n * @property {(function(Node): boolean) | NoOp} beforeNodeAdded\n * @property {(function(Node): void) | NoOp} afterNodeAdded\n * @property {(function(Node, Node): boolean) | NoOp} beforeNodeMorphed\n * @property {(function(Node, Node): void) | NoOp} afterNodeMorphed\n * @property {(function(Node): boolean) | NoOp} beforeNodeRemoved\n * @property {(function(Node): void) | NoOp} afterNodeRemoved\n * @property {(function(string, Element, \"update\" | \"remove\"): boolean) | NoOp} beforeAttributeUpdated\n */\n\n/**\n * @typedef {object} ConfigInternal\n *\n * @property {'outerHTML' | 'innerHTML'} morphStyle\n * @property {boolean} [ignoreActive]\n * @property {boolean} [ignoreActiveValue]\n * @property {boolean} [restoreFocus]\n * @property {ConfigCallbacksInternal} callbacks\n * @property {ConfigHeadInternal} head\n */\n\n/**\n * @typedef {Object} IdSets\n * @property {Set} persistentIds\n * @property {Map>} idMap\n */\n\n/**\n * @typedef {Function} Morph\n *\n * @param {Element | Document} oldNode\n * @param {Element | Node | HTMLCollection | Node[] | string | null} newContent\n * @param {Config} [config]\n * @returns {undefined | Node[]}\n */\n\n// base IIFE to define idiomorph\n/**\n *\n * @type {{defaults: ConfigInternal, morph: Morph}}\n */\nvar Idiomorph = (function () {\n\n /**\n * @typedef {object} MorphContext\n *\n * @property {Element} target\n * @property {Element} newContent\n * @property {ConfigInternal} config\n * @property {ConfigInternal['morphStyle']} morphStyle\n * @property {ConfigInternal['ignoreActive']} ignoreActive\n * @property {ConfigInternal['ignoreActiveValue']} ignoreActiveValue\n * @property {ConfigInternal['restoreFocus']} restoreFocus\n * @property {Map>} idMap\n * @property {Set} persistentIds\n * @property {ConfigInternal['callbacks']} callbacks\n * @property {ConfigInternal['head']} head\n * @property {HTMLDivElement} pantry\n * @property {Element[]} activeElementAndParents\n */\n\n //=============================================================================\n // AND NOW IT BEGINS...\n //=============================================================================\n\n const noOp = () => {};\n /**\n * Default configuration values, updatable by users now\n * @type {ConfigInternal}\n */\n const defaults = {\n morphStyle: \"outerHTML\",\n callbacks: {\n beforeNodeAdded: noOp,\n afterNodeAdded: noOp,\n beforeNodeMorphed: noOp,\n afterNodeMorphed: noOp,\n beforeNodeRemoved: noOp,\n afterNodeRemoved: noOp,\n beforeAttributeUpdated: noOp,\n },\n head: {\n style: \"merge\",\n shouldPreserve: (elt) => elt.getAttribute(\"im-preserve\") === \"true\",\n shouldReAppend: (elt) => elt.getAttribute(\"im-re-append\") === \"true\",\n shouldRemove: noOp,\n afterHeadMorphed: noOp,\n },\n restoreFocus: true,\n };\n\n /**\n * Core idiomorph function for morphing one DOM tree to another\n *\n * @param {Element | Document} oldNode\n * @param {Element | Node | HTMLCollection | Node[] | string | null} newContent\n * @param {Config} [config]\n * @returns {Promise | Node[]}\n */\n function morph(oldNode, newContent, config = {}) {\n oldNode = normalizeElement(oldNode);\n const newNode = normalizeParent(newContent);\n const ctx = createMorphContext(oldNode, newNode, config);\n\n const morphedNodes = saveAndRestoreFocus(ctx, () => {\n return withHeadBlocking(\n ctx,\n oldNode,\n newNode,\n /** @param {MorphContext} ctx */ (ctx) => {\n if (ctx.morphStyle === \"innerHTML\") {\n morphChildren(ctx, oldNode, newNode);\n return Array.from(oldNode.childNodes);\n } else {\n return morphOuterHTML(ctx, oldNode, newNode);\n }\n },\n );\n });\n\n ctx.pantry.remove();\n return morphedNodes;\n }\n\n /**\n * Morph just the outerHTML of the oldNode to the newContent\n * We have to be careful because the oldNode could have siblings which need to be untouched\n * @param {MorphContext} ctx\n * @param {Element} oldNode\n * @param {Element} newNode\n * @returns {Node[]}\n */\n function morphOuterHTML(ctx, oldNode, newNode) {\n const oldParent = normalizeParent(oldNode);\n morphChildren(\n ctx,\n oldParent,\n newNode,\n // these two optional params are the secret sauce\n oldNode, // start point for iteration\n oldNode.nextSibling, // end point for iteration\n );\n // this is safe even with siblings, because normalizeParent returns a SlicedParentNode if needed.\n return Array.from(oldParent.childNodes);\n }\n\n /**\n * @param {MorphContext} ctx\n * @param {Function} fn\n * @returns {Promise | Node[]}\n */\n function saveAndRestoreFocus(ctx, fn) {\n if (!ctx.config.restoreFocus) return fn();\n let activeElement =\n /** @type {HTMLInputElement|HTMLTextAreaElement|null} */ (\n document.activeElement\n );\n\n // don't bother if the active element is not an input or textarea\n if (\n !(\n activeElement instanceof HTMLInputElement ||\n activeElement instanceof HTMLTextAreaElement\n )\n ) {\n return fn();\n }\n\n const { id: activeElementId, selectionStart, selectionEnd } = activeElement;\n\n const results = fn();\n\n if (\n activeElementId &&\n activeElementId !== document.activeElement?.getAttribute(\"id\")\n ) {\n activeElement = ctx.target.querySelector(`[id=\"${activeElementId}\"]`);\n activeElement?.focus();\n }\n if (activeElement && !activeElement.selectionEnd && selectionEnd) {\n activeElement.setSelectionRange(selectionStart, selectionEnd);\n }\n\n return results;\n }\n\n const morphChildren = (function () {\n /**\n * This is the core algorithm for matching up children. The idea is to use id sets to try to match up\n * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but\n * by using id sets, we are able to better match up with content deeper in the DOM.\n *\n * Basic algorithm:\n * - for each node in the new content:\n * - search self and siblings for an id set match, falling back to a soft match\n * - if match found\n * - remove any nodes up to the match:\n * - pantry persistent nodes\n * - delete the rest\n * - morph the match\n * - elsif no match found, and node is persistent\n * - find its match by querying the old root (future) and pantry (past)\n * - move it and its children here\n * - morph it\n * - else\n * - create a new node from scratch as a last result\n *\n * @param {MorphContext} ctx the merge context\n * @param {Element} oldParent the old content that we are merging the new content into\n * @param {Element} newParent the parent element of the new content\n * @param {Node|null} [insertionPoint] the point in the DOM we start morphing at (defaults to first child)\n * @param {Node|null} [endPoint] the point in the DOM we stop morphing at (defaults to after last child)\n */\n function morphChildren(\n ctx,\n oldParent,\n newParent,\n insertionPoint = null,\n endPoint = null,\n ) {\n // normalize\n if (\n oldParent instanceof HTMLTemplateElement &&\n newParent instanceof HTMLTemplateElement\n ) {\n // @ts-ignore we can pretend the DocumentFragment is an Element\n oldParent = oldParent.content;\n // @ts-ignore ditto\n newParent = newParent.content;\n }\n insertionPoint ||= oldParent.firstChild;\n\n // run through all the new content\n for (const newChild of newParent.childNodes) {\n // once we reach the end of the old parent content skip to the end and insert the rest\n if (insertionPoint && insertionPoint != endPoint) {\n const bestMatch = findBestMatch(\n ctx,\n newChild,\n insertionPoint,\n endPoint,\n );\n if (bestMatch) {\n // if the node to morph is not at the insertion point then remove/move up to it\n if (bestMatch !== insertionPoint) {\n removeNodesBetween(ctx, insertionPoint, bestMatch);\n }\n morphNode(bestMatch, newChild, ctx);\n insertionPoint = bestMatch.nextSibling;\n continue;\n }\n }\n\n // if the matching node is elsewhere in the original content\n if (newChild instanceof Element) {\n // we can pretend the id is non-null because the next `.has` line will reject it if not\n const newChildId = /** @type {String} */ (\n newChild.getAttribute(\"id\")\n );\n if (ctx.persistentIds.has(newChildId)) {\n // move it and all its children here and morph\n const movedChild = moveBeforeById(\n oldParent,\n newChildId,\n insertionPoint,\n ctx,\n );\n morphNode(movedChild, newChild, ctx);\n insertionPoint = movedChild.nextSibling;\n continue;\n }\n }\n\n // last resort: insert the new node from scratch\n const insertedNode = createNode(\n oldParent,\n newChild,\n insertionPoint,\n ctx,\n );\n // could be null if beforeNodeAdded prevented insertion\n if (insertedNode) {\n insertionPoint = insertedNode.nextSibling;\n }\n }\n\n // remove any remaining old nodes that didn't match up with new content\n while (insertionPoint && insertionPoint != endPoint) {\n const tempNode = insertionPoint;\n insertionPoint = insertionPoint.nextSibling;\n removeNode(ctx, tempNode);\n }\n }\n\n /**\n * This performs the action of inserting a new node while handling situations where the node contains\n * elements with persistent ids and possible state info we can still preserve by moving in and then morphing\n *\n * @param {Element} oldParent\n * @param {Node} newChild\n * @param {Node|null} insertionPoint\n * @param {MorphContext} ctx\n * @returns {Node|null}\n */\n function createNode(oldParent, newChild, insertionPoint, ctx) {\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return null;\n if (ctx.idMap.has(newChild)) {\n // node has children with ids with possible state so create a dummy elt of same type and apply full morph algorithm\n const newEmptyChild = document.createElement(\n /** @type {Element} */ (newChild).tagName,\n );\n oldParent.insertBefore(newEmptyChild, insertionPoint);\n morphNode(newEmptyChild, newChild, ctx);\n ctx.callbacks.afterNodeAdded(newEmptyChild);\n return newEmptyChild;\n } else {\n // optimisation: no id state to preserve so we can just insert a clone of the newChild and its descendants\n const newClonedChild = document.importNode(newChild, true); // importNode to not mutate newParent\n oldParent.insertBefore(newClonedChild, insertionPoint);\n ctx.callbacks.afterNodeAdded(newClonedChild);\n return newClonedChild;\n }\n }\n\n //=============================================================================\n // Matching Functions\n //=============================================================================\n const findBestMatch = (function () {\n /**\n * Scans forward from the startPoint to the endPoint looking for a match\n * for the node. It looks for an id set match first, then a soft match.\n * We abort softmatching if we find two future soft matches, to reduce churn.\n * @param {Node} node\n * @param {MorphContext} ctx\n * @param {Node | null} startPoint\n * @param {Node | null} endPoint\n * @returns {Node | null}\n */\n function findBestMatch(ctx, node, startPoint, endPoint) {\n let softMatch = null;\n let nextSibling = node.nextSibling;\n let siblingSoftMatchCount = 0;\n\n let cursor = startPoint;\n while (cursor && cursor != endPoint) {\n // soft matching is a prerequisite for id set matching\n if (isSoftMatch(cursor, node)) {\n if (isIdSetMatch(ctx, cursor, node)) {\n return cursor; // found an id set match, we're done!\n }\n\n // we haven't yet saved a soft match fallback\n if (softMatch === null) {\n // the current soft match will hard match something else in the future, leave it\n if (!ctx.idMap.has(cursor)) {\n // save this as the fallback if we get through the loop without finding a hard match\n softMatch = cursor;\n }\n }\n }\n if (\n softMatch === null &&\n nextSibling &&\n isSoftMatch(cursor, nextSibling)\n ) {\n // The next new node has a soft match with this node, so\n // increment the count of future soft matches\n siblingSoftMatchCount++;\n nextSibling = nextSibling.nextSibling;\n\n // If there are two future soft matches, block soft matching for this node to allow\n // future siblings to soft match. This is to reduce churn in the DOM when an element\n // is prepended.\n if (siblingSoftMatchCount >= 2) {\n softMatch = undefined;\n }\n }\n\n // if the current node contains active element, stop looking for better future matches,\n // because if one is found, this node will be moved to the pantry, reparenting it and thus losing focus\n // @ts-ignore pretend cursor is Element rather than Node, we're just testing for array inclusion\n if (ctx.activeElementAndParents.includes(cursor)) break;\n\n cursor = cursor.nextSibling;\n }\n\n return softMatch || null;\n }\n\n /**\n *\n * @param {MorphContext} ctx\n * @param {Node} oldNode\n * @param {Node} newNode\n * @returns {boolean}\n */\n function isIdSetMatch(ctx, oldNode, newNode) {\n let oldSet = ctx.idMap.get(oldNode);\n let newSet = ctx.idMap.get(newNode);\n\n if (!newSet || !oldSet) return false;\n\n for (const id of oldSet) {\n // a potential match is an id in the new and old nodes that\n // has not already been merged into the DOM\n // But the newNode content we call this on has not been\n // merged yet and we don't allow duplicate IDs so it is simple\n if (newSet.has(id)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n *\n * @param {Node} oldNode\n * @param {Node} newNode\n * @returns {boolean}\n */\n function isSoftMatch(oldNode, newNode) {\n // ok to cast: if one is not element, `id` and `tagName` will be undefined and we'll just compare that.\n const oldElt = /** @type {Element} */ (oldNode);\n const newElt = /** @type {Element} */ (newNode);\n\n return (\n oldElt.nodeType === newElt.nodeType &&\n oldElt.tagName === newElt.tagName &&\n // If oldElt has an `id` with possible state and it doesn't match newElt.id then avoid morphing.\n // We'll still match an anonymous node with an IDed newElt, though, because if it got this far,\n // its not persistent, and new nodes can't have any hidden state.\n // We can't use .id because of form input shadowing, and we can't count on .getAttribute's presence because it could be a document-fragment\n (!oldElt.getAttribute?.(\"id\") ||\n oldElt.getAttribute?.(\"id\") === newElt.getAttribute?.(\"id\"))\n );\n }\n\n return findBestMatch;\n })();\n\n //=============================================================================\n // DOM Manipulation Functions\n //=============================================================================\n\n /**\n * Gets rid of an unwanted DOM node; strategy depends on nature of its reuse:\n * - Persistent nodes will be moved to the pantry for later reuse\n * - Other nodes will have their hooks called, and then are removed\n * @param {MorphContext} ctx\n * @param {Node} node\n */\n function removeNode(ctx, node) {\n // are we going to id set match this later?\n if (ctx.idMap.has(node)) {\n // skip callbacks and move to pantry\n moveBefore(ctx.pantry, node, null);\n } else {\n // remove for realsies\n if (ctx.callbacks.beforeNodeRemoved(node) === false) return;\n node.parentNode?.removeChild(node);\n ctx.callbacks.afterNodeRemoved(node);\n }\n }\n\n /**\n * Remove nodes between the start and end nodes\n * @param {MorphContext} ctx\n * @param {Node} startInclusive\n * @param {Node} endExclusive\n * @returns {Node|null}\n */\n function removeNodesBetween(ctx, startInclusive, endExclusive) {\n /** @type {Node | null} */\n let cursor = startInclusive;\n // remove nodes until the endExclusive node\n while (cursor && cursor !== endExclusive) {\n let tempNode = /** @type {Node} */ (cursor);\n cursor = cursor.nextSibling;\n removeNode(ctx, tempNode);\n }\n return cursor;\n }\n\n /**\n * Search for an element by id within the document and pantry, and move it using moveBefore.\n *\n * @param {Element} parentNode - The parent node to which the element will be moved.\n * @param {string} id - The ID of the element to be moved.\n * @param {Node | null} after - The reference node to insert the element before.\n * If `null`, the element is appended as the last child.\n * @param {MorphContext} ctx\n * @returns {Element} The found element\n */\n function moveBeforeById(parentNode, id, after, ctx) {\n const target =\n /** @type {Element} - will always be found */\n (\n // ctx.target.id unsafe because of form input shadowing\n // ctx.target could be a document fragment which doesn't have `getAttribute`\n (ctx.target.getAttribute?.(\"id\") === id && ctx.target) ||\n ctx.target.querySelector(`[id=\"${id}\"]`) ||\n ctx.pantry.querySelector(`[id=\"${id}\"]`)\n );\n removeElementFromAncestorsIdMaps(target, ctx);\n moveBefore(parentNode, target, after);\n return target;\n }\n\n /**\n * Removes an element from its ancestors' id maps. This is needed when an element is moved from the\n * \"future\" via `moveBeforeId`. Otherwise, its erstwhile ancestors could be mistakenly moved to the\n * pantry rather than being deleted, preventing their removal hooks from being called.\n *\n * @param {Element} element - element to remove from its ancestors' id maps\n * @param {MorphContext} ctx\n */\n function removeElementFromAncestorsIdMaps(element, ctx) {\n // we know id is non-null String, because this function is only called on elements with ids\n const id = /** @type {String} */ (element.getAttribute(\"id\"));\n /** @ts-ignore - safe to loop in this way **/\n while ((element = element.parentNode)) {\n let idSet = ctx.idMap.get(element);\n if (idSet) {\n idSet.delete(id);\n if (!idSet.size) {\n ctx.idMap.delete(element);\n }\n }\n }\n }\n\n /**\n * Moves an element before another element within the same parent.\n * Uses the proposed `moveBefore` API if available (and working), otherwise falls back to `insertBefore`.\n * This is essentialy a forward-compat wrapper.\n *\n * @param {Element} parentNode - The parent node containing the after element.\n * @param {Node} element - The element to be moved.\n * @param {Node | null} after - The reference node to insert `element` before.\n * If `null`, `element` is appended as the last child.\n */\n function moveBefore(parentNode, element, after) {\n // @ts-ignore - use proposed moveBefore feature\n if (parentNode.moveBefore) {\n try {\n // @ts-ignore - use proposed moveBefore feature\n parentNode.moveBefore(element, after);\n } catch (e) {\n // fall back to insertBefore as some browsers may fail on moveBefore when trying to move Dom disconnected nodes to pantry\n parentNode.insertBefore(element, after);\n }\n } else {\n parentNode.insertBefore(element, after);\n }\n }\n\n return morphChildren;\n })();\n\n //=============================================================================\n // Single Node Morphing Code\n //=============================================================================\n const morphNode = (function () {\n /**\n * @param {Node} oldNode root node to merge content into\n * @param {Node} newContent new content to merge\n * @param {MorphContext} ctx the merge context\n * @returns {Node | null} the element that ended up in the DOM\n */\n function morphNode(oldNode, newContent, ctx) {\n if (ctx.ignoreActive && oldNode === document.activeElement) {\n // don't morph focused element\n return null;\n }\n\n if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) {\n return oldNode;\n }\n\n if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) ; else if (\n oldNode instanceof HTMLHeadElement &&\n ctx.head.style !== \"morph\"\n ) {\n // ok to cast: if newContent wasn't also a , it would've got caught in the `!isSoftMatch` branch above\n handleHeadElement(\n oldNode,\n /** @type {HTMLHeadElement} */ (newContent),\n ctx,\n );\n } else {\n morphAttributes(oldNode, newContent, ctx);\n if (!ignoreValueOfActiveElement(oldNode, ctx)) {\n // @ts-ignore newContent can be a node here because .firstChild will be null\n morphChildren(ctx, oldNode, newContent);\n }\n }\n ctx.callbacks.afterNodeMorphed(oldNode, newContent);\n return oldNode;\n }\n\n /**\n * syncs the oldNode to the newNode, copying over all attributes and\n * inner element state from the newNode to the oldNode\n *\n * @param {Node} oldNode the node to copy attributes & state to\n * @param {Node} newNode the node to copy attributes & state from\n * @param {MorphContext} ctx the merge context\n */\n function morphAttributes(oldNode, newNode, ctx) {\n let type = newNode.nodeType;\n\n // if is an element type, sync the attributes from the\n // new node into the new node\n if (type === 1 /* element type */) {\n const oldElt = /** @type {Element} */ (oldNode);\n const newElt = /** @type {Element} */ (newNode);\n\n const oldAttributes = oldElt.attributes;\n const newAttributes = newElt.attributes;\n for (const newAttribute of newAttributes) {\n if (ignoreAttribute(newAttribute.name, oldElt, \"update\", ctx)) {\n continue;\n }\n if (oldElt.getAttribute(newAttribute.name) !== newAttribute.value) {\n oldElt.setAttribute(newAttribute.name, newAttribute.value);\n }\n }\n // iterate backwards to avoid skipping over items when a delete occurs\n for (let i = oldAttributes.length - 1; 0 <= i; i--) {\n const oldAttribute = oldAttributes[i];\n\n // toAttributes is a live NamedNodeMap, so iteration+mutation is unsafe\n // e.g. custom element attribute callbacks can remove other attributes\n if (!oldAttribute) continue;\n\n if (!newElt.hasAttribute(oldAttribute.name)) {\n if (ignoreAttribute(oldAttribute.name, oldElt, \"remove\", ctx)) {\n continue;\n }\n oldElt.removeAttribute(oldAttribute.name);\n }\n }\n\n if (!ignoreValueOfActiveElement(oldElt, ctx)) {\n syncInputValue(oldElt, newElt, ctx);\n }\n }\n\n // sync text nodes\n if (type === 8 /* comment */ || type === 3 /* text */) {\n if (oldNode.nodeValue !== newNode.nodeValue) {\n oldNode.nodeValue = newNode.nodeValue;\n }\n }\n }\n\n /**\n * NB: many bothans died to bring us information:\n *\n * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js\n * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113\n *\n * @param {Element} oldElement the element to sync the input value to\n * @param {Element} newElement the element to sync the input value from\n * @param {MorphContext} ctx the merge context\n */\n function syncInputValue(oldElement, newElement, ctx) {\n if (\n oldElement instanceof HTMLInputElement &&\n newElement instanceof HTMLInputElement &&\n newElement.type !== \"file\"\n ) {\n let newValue = newElement.value;\n let oldValue = oldElement.value;\n\n // sync boolean attributes\n syncBooleanAttribute(oldElement, newElement, \"checked\", ctx);\n syncBooleanAttribute(oldElement, newElement, \"disabled\", ctx);\n\n if (!newElement.hasAttribute(\"value\")) {\n if (!ignoreAttribute(\"value\", oldElement, \"remove\", ctx)) {\n oldElement.value = \"\";\n oldElement.removeAttribute(\"value\");\n }\n } else if (oldValue !== newValue) {\n if (!ignoreAttribute(\"value\", oldElement, \"update\", ctx)) {\n oldElement.setAttribute(\"value\", newValue);\n oldElement.value = newValue;\n }\n }\n // TODO: QUESTION(1cg): this used to only check `newElement` unlike the other branches -- why?\n // did I break something?\n } else if (\n oldElement instanceof HTMLOptionElement &&\n newElement instanceof HTMLOptionElement\n ) {\n syncBooleanAttribute(oldElement, newElement, \"selected\", ctx);\n } else if (\n oldElement instanceof HTMLTextAreaElement &&\n newElement instanceof HTMLTextAreaElement\n ) {\n let newValue = newElement.value;\n let oldValue = oldElement.value;\n if (ignoreAttribute(\"value\", oldElement, \"update\", ctx)) {\n return;\n }\n if (newValue !== oldValue) {\n oldElement.value = newValue;\n }\n if (\n oldElement.firstChild &&\n oldElement.firstChild.nodeValue !== newValue\n ) {\n oldElement.firstChild.nodeValue = newValue;\n }\n }\n }\n\n /**\n * @param {Element} oldElement element to write the value to\n * @param {Element} newElement element to read the value from\n * @param {string} attributeName the attribute name\n * @param {MorphContext} ctx the merge context\n */\n function syncBooleanAttribute(oldElement, newElement, attributeName, ctx) {\n // @ts-ignore this function is only used on boolean attrs that are reflected as dom properties\n const newLiveValue = newElement[attributeName],\n // @ts-ignore ditto\n oldLiveValue = oldElement[attributeName];\n if (newLiveValue !== oldLiveValue) {\n const ignoreUpdate = ignoreAttribute(\n attributeName,\n oldElement,\n \"update\",\n ctx,\n );\n if (!ignoreUpdate) {\n // update attribute's associated DOM property\n // @ts-ignore this function is only used on boolean attrs that are reflected as dom properties\n oldElement[attributeName] = newElement[attributeName];\n }\n if (newLiveValue) {\n if (!ignoreUpdate) {\n // https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML\n // this is the correct way to set a boolean attribute to \"true\"\n oldElement.setAttribute(attributeName, \"\");\n }\n } else {\n if (!ignoreAttribute(attributeName, oldElement, \"remove\", ctx)) {\n oldElement.removeAttribute(attributeName);\n }\n }\n }\n }\n\n /**\n * @param {string} attr the attribute to be mutated\n * @param {Element} element the element that is going to be updated\n * @param {\"update\" | \"remove\"} updateType\n * @param {MorphContext} ctx the merge context\n * @returns {boolean} true if the attribute should be ignored, false otherwise\n */\n function ignoreAttribute(attr, element, updateType, ctx) {\n if (\n attr === \"value\" &&\n ctx.ignoreActiveValue &&\n element === document.activeElement\n ) {\n return true;\n }\n return (\n ctx.callbacks.beforeAttributeUpdated(attr, element, updateType) ===\n false\n );\n }\n\n /**\n * @param {Node} possibleActiveElement\n * @param {MorphContext} ctx\n * @returns {boolean}\n */\n function ignoreValueOfActiveElement(possibleActiveElement, ctx) {\n return (\n !!ctx.ignoreActiveValue &&\n possibleActiveElement === document.activeElement &&\n possibleActiveElement !== document.body\n );\n }\n\n return morphNode;\n })();\n\n //=============================================================================\n // Head Management Functions\n //=============================================================================\n /**\n * @param {MorphContext} ctx\n * @param {Element} oldNode\n * @param {Element} newNode\n * @param {function} callback\n * @returns {Node[] | Promise}\n */\n function withHeadBlocking(ctx, oldNode, newNode, callback) {\n if (ctx.head.block) {\n const oldHead = oldNode.querySelector(\"head\");\n const newHead = newNode.querySelector(\"head\");\n if (oldHead && newHead) {\n const promises = handleHeadElement(oldHead, newHead, ctx);\n // when head promises resolve, proceed ignoring the head tag\n return Promise.all(promises).then(() => {\n const newCtx = Object.assign(ctx, {\n head: {\n block: false,\n ignore: true,\n },\n });\n return callback(newCtx);\n });\n }\n }\n // just proceed if we not head blocking\n return callback(ctx);\n }\n\n /**\n * The HEAD tag can be handled specially, either w/ a 'merge' or 'append' style\n *\n * @param {Element} oldHead\n * @param {Element} newHead\n * @param {MorphContext} ctx\n * @returns {Promise[]}\n */\n function handleHeadElement(oldHead, newHead, ctx) {\n let added = [];\n let removed = [];\n let preserved = [];\n let nodesToAppend = [];\n\n // put all new head elements into a Map, by their outerHTML\n let srcToNewHeadNodes = new Map();\n for (const newHeadChild of newHead.children) {\n srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);\n }\n\n // for each elt in the current head\n for (const currentHeadElt of oldHead.children) {\n // If the current head element is in the map\n let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);\n let isReAppended = ctx.head.shouldReAppend(currentHeadElt);\n let isPreserved = ctx.head.shouldPreserve(currentHeadElt);\n if (inNewContent || isPreserved) {\n if (isReAppended) {\n // remove the current version and let the new version replace it and re-execute\n removed.push(currentHeadElt);\n } else {\n // this element already exists and should not be re-appended, so remove it from\n // the new content map, preserving it in the DOM\n srcToNewHeadNodes.delete(currentHeadElt.outerHTML);\n preserved.push(currentHeadElt);\n }\n } else {\n if (ctx.head.style === \"append\") {\n // we are appending and this existing element is not new content\n // so if and only if it is marked for re-append do we do anything\n if (isReAppended) {\n removed.push(currentHeadElt);\n nodesToAppend.push(currentHeadElt);\n }\n } else {\n // if this is a merge, we remove this content since it is not in the new head\n if (ctx.head.shouldRemove(currentHeadElt) !== false) {\n removed.push(currentHeadElt);\n }\n }\n }\n }\n\n // Push the remaining new head elements in the Map into the\n // nodes to append to the head tag\n nodesToAppend.push(...srcToNewHeadNodes.values());\n\n let promises = [];\n for (const newNode of nodesToAppend) {\n // TODO: This could theoretically be null, based on type\n let newElt = /** @type {ChildNode} */ (\n document.createRange().createContextualFragment(newNode.outerHTML)\n .firstChild\n );\n if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {\n if (\n (\"href\" in newElt && newElt.href) ||\n (\"src\" in newElt && newElt.src)\n ) {\n /** @type {(result?: any) => void} */ let resolve;\n let promise = new Promise(function (_resolve) {\n resolve = _resolve;\n });\n newElt.addEventListener(\"load\", function () {\n resolve();\n });\n promises.push(promise);\n }\n oldHead.appendChild(newElt);\n ctx.callbacks.afterNodeAdded(newElt);\n added.push(newElt);\n }\n }\n\n // remove all removed elements, after we have appended the new elements to avoid\n // additional network requests for things like style sheets\n for (const removedElement of removed) {\n if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {\n oldHead.removeChild(removedElement);\n ctx.callbacks.afterNodeRemoved(removedElement);\n }\n }\n\n ctx.head.afterHeadMorphed(oldHead, {\n added: added,\n kept: preserved,\n removed: removed,\n });\n return promises;\n }\n\n //=============================================================================\n // Create Morph Context Functions\n //=============================================================================\n const createMorphContext = (function () {\n /**\n *\n * @param {Element} oldNode\n * @param {Element} newContent\n * @param {Config} config\n * @returns {MorphContext}\n */\n function createMorphContext(oldNode, newContent, config) {\n const { persistentIds, idMap } = createIdMaps(oldNode, newContent);\n\n const mergedConfig = mergeDefaults(config);\n const morphStyle = mergedConfig.morphStyle || \"outerHTML\";\n if (![\"innerHTML\", \"outerHTML\"].includes(morphStyle)) {\n throw `Do not understand how to morph style ${morphStyle}`;\n }\n\n return {\n target: oldNode,\n newContent: newContent,\n config: mergedConfig,\n morphStyle: morphStyle,\n ignoreActive: mergedConfig.ignoreActive,\n ignoreActiveValue: mergedConfig.ignoreActiveValue,\n restoreFocus: mergedConfig.restoreFocus,\n idMap: idMap,\n persistentIds: persistentIds,\n pantry: createPantry(),\n activeElementAndParents: createActiveElementAndParents(oldNode),\n callbacks: mergedConfig.callbacks,\n head: mergedConfig.head,\n };\n }\n\n /**\n * Deep merges the config object and the Idiomorph.defaults object to\n * produce a final configuration object\n * @param {Config} config\n * @returns {ConfigInternal}\n */\n function mergeDefaults(config) {\n let finalConfig = Object.assign({}, defaults);\n\n // copy top level stuff into final config\n Object.assign(finalConfig, config);\n\n // copy callbacks into final config (do this to deep merge the callbacks)\n finalConfig.callbacks = Object.assign(\n {},\n defaults.callbacks,\n config.callbacks,\n );\n\n // copy head config into final config (do this to deep merge the head)\n finalConfig.head = Object.assign({}, defaults.head, config.head);\n\n return finalConfig;\n }\n\n /**\n * @returns {HTMLDivElement}\n */\n function createPantry() {\n const pantry = document.createElement(\"div\");\n pantry.hidden = true;\n document.body.insertAdjacentElement(\"afterend\", pantry);\n return pantry;\n }\n\n /**\n * @param {Element} oldNode\n * @returns {Element[]}\n */\n function createActiveElementAndParents(oldNode) {\n /** @type {Element[]} */\n let activeElementAndParents = [];\n let elt = document.activeElement;\n if (elt?.tagName !== \"BODY\" && oldNode.contains(elt)) {\n while (elt) {\n activeElementAndParents.push(elt);\n if (elt === oldNode) break;\n elt = elt.parentElement;\n }\n }\n return activeElementAndParents;\n }\n\n /**\n * Returns all elements with an ID contained within the root element and its descendants\n *\n * @param {Element} root\n * @returns {Element[]}\n */\n function findIdElements(root) {\n let elements = Array.from(root.querySelectorAll(\"[id]\"));\n // root could be a document fragment which doesn't have `getAttribute`\n if (root.getAttribute?.(\"id\")) {\n elements.push(root);\n }\n return elements;\n }\n\n /**\n * A bottom-up algorithm that populates a map of Element -> IdSet.\n * The idSet for a given element is the set of all IDs contained within its subtree.\n * As an optimzation, we filter these IDs through the given list of persistent IDs,\n * because we don't need to bother considering IDed elements that won't be in the new content.\n *\n * @param {Map>} idMap\n * @param {Set} persistentIds\n * @param {Element} root\n * @param {Element[]} elements\n */\n function populateIdMapWithTree(idMap, persistentIds, root, elements) {\n for (const elt of elements) {\n // we can pretend id is non-null String, because the .has line will reject it immediately if not\n const id = /** @type {String} */ (elt.getAttribute(\"id\"));\n if (persistentIds.has(id)) {\n /** @type {Element|null} */\n let current = elt;\n // walk up the parent hierarchy of that element, adding the id\n // of element to the parent's id set\n while (current) {\n let idSet = idMap.get(current);\n // if the id set doesn't exist, create it and insert it in the map\n if (idSet == null) {\n idSet = new Set();\n idMap.set(current, idSet);\n }\n idSet.add(id);\n\n if (current === root) break;\n current = current.parentElement;\n }\n }\n }\n }\n\n /**\n * This function computes a map of nodes to all ids contained within that node (inclusive of the\n * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows\n * for a looser definition of \"matching\" than tradition id matching, and allows child nodes\n * to contribute to a parent nodes matching.\n *\n * @param {Element} oldContent the old content that will be morphed\n * @param {Element} newContent the new content to morph to\n * @returns {IdSets}\n */\n function createIdMaps(oldContent, newContent) {\n const oldIdElements = findIdElements(oldContent);\n const newIdElements = findIdElements(newContent);\n\n const persistentIds = createPersistentIds(oldIdElements, newIdElements);\n\n /** @type {Map>} */\n let idMap = new Map();\n populateIdMapWithTree(idMap, persistentIds, oldContent, oldIdElements);\n\n /** @ts-ignore - if newContent is a duck-typed parent, pass its single child node as the root to halt upwards iteration */\n const newRoot = newContent.__idiomorphRoot || newContent;\n populateIdMapWithTree(idMap, persistentIds, newRoot, newIdElements);\n\n return { persistentIds, idMap };\n }\n\n /**\n * This function computes the set of ids that persist between the two contents excluding duplicates\n *\n * @param {Element[]} oldIdElements\n * @param {Element[]} newIdElements\n * @returns {Set}\n */\n function createPersistentIds(oldIdElements, newIdElements) {\n let duplicateIds = new Set();\n\n /** @type {Map} */\n let oldIdTagNameMap = new Map();\n for (const { id, tagName } of oldIdElements) {\n if (oldIdTagNameMap.has(id)) {\n duplicateIds.add(id);\n } else {\n oldIdTagNameMap.set(id, tagName);\n }\n }\n\n let persistentIds = new Set();\n for (const { id, tagName } of newIdElements) {\n if (persistentIds.has(id)) {\n duplicateIds.add(id);\n } else if (oldIdTagNameMap.get(id) === tagName) {\n persistentIds.add(id);\n }\n // skip if tag types mismatch because its not possible to morph one tag into another\n }\n\n for (const id of duplicateIds) {\n persistentIds.delete(id);\n }\n return persistentIds;\n }\n\n return createMorphContext;\n })();\n\n //=============================================================================\n // HTML Normalization Functions\n //=============================================================================\n const { normalizeElement, normalizeParent } = (function () {\n /** @type {WeakSet} */\n const generatedByIdiomorph = new WeakSet();\n\n /**\n *\n * @param {Element | Document} content\n * @returns {Element}\n */\n function normalizeElement(content) {\n if (content instanceof Document) {\n return content.documentElement;\n } else {\n return content;\n }\n }\n\n /**\n *\n * @param {null | string | Node | HTMLCollection | Node[] | Document & {generatedByIdiomorph:boolean}} newContent\n * @returns {Element}\n */\n function normalizeParent(newContent) {\n if (newContent == null) {\n return document.createElement(\"div\"); // dummy parent element\n } else if (typeof newContent === \"string\") {\n return normalizeParent(parseContent(newContent));\n } else if (\n generatedByIdiomorph.has(/** @type {Element} */ (newContent))\n ) {\n // the template tag created by idiomorph parsing can serve as a dummy parent\n return /** @type {Element} */ (newContent);\n } else if (newContent instanceof Node) {\n if (newContent.parentNode) {\n // we can't use the parent directly because newContent may have siblings\n // that we don't want in the morph, and reparenting might be expensive (TODO is it?),\n // so instead we create a fake parent node that only sees a slice of its children.\n /** @type {Element} */\n return /** @type {any} */ (new SlicedParentNode(newContent));\n } else {\n // a single node is added as a child to a dummy parent\n const dummyParent = document.createElement(\"div\");\n dummyParent.append(newContent);\n return dummyParent;\n }\n } else {\n // all nodes in the array or HTMLElement collection are consolidated under\n // a single dummy parent element\n const dummyParent = document.createElement(\"div\");\n for (const elt of [...newContent]) {\n dummyParent.append(elt);\n }\n return dummyParent;\n }\n }\n\n /**\n * A fake duck-typed parent element to wrap a single node, without actually reparenting it.\n * This is useful because the node may have siblings that we don't want in the morph, and it may also be moved\n * or replaced with one or more elements during the morph. This class effectively allows us a window into\n * a slice of a node's children.\n * \"If it walks like a duck, and quacks like a duck, then it must be a duck!\" -- James Whitcomb Riley (1849–1916)\n */\n class SlicedParentNode {\n /** @param {Node} node */\n constructor(node) {\n this.originalNode = node;\n this.realParentNode = /** @type {Element} */ (node.parentNode);\n this.previousSibling = node.previousSibling;\n this.nextSibling = node.nextSibling;\n }\n\n /** @returns {Node[]} */\n get childNodes() {\n // return slice of realParent's current childNodes, based on previousSibling and nextSibling\n const nodes = [];\n let cursor = this.previousSibling\n ? this.previousSibling.nextSibling\n : this.realParentNode.firstChild;\n while (cursor && cursor != this.nextSibling) {\n nodes.push(cursor);\n cursor = cursor.nextSibling;\n }\n return nodes;\n }\n\n /**\n * @param {string} selector\n * @returns {Element[]}\n */\n querySelectorAll(selector) {\n return this.childNodes.reduce((results, node) => {\n if (node instanceof Element) {\n if (node.matches(selector)) results.push(node);\n const nodeList = node.querySelectorAll(selector);\n for (let i = 0; i < nodeList.length; i++) {\n results.push(nodeList[i]);\n }\n }\n return results;\n }, /** @type {Element[]} */ ([]));\n }\n\n /**\n * @param {Node} node\n * @param {Node} referenceNode\n * @returns {Node}\n */\n insertBefore(node, referenceNode) {\n return this.realParentNode.insertBefore(node, referenceNode);\n }\n\n /**\n * @param {Node} node\n * @param {Node} referenceNode\n * @returns {Node}\n */\n moveBefore(node, referenceNode) {\n // @ts-ignore - use new moveBefore feature\n return this.realParentNode.moveBefore(node, referenceNode);\n }\n\n /**\n * for later use with populateIdMapWithTree to halt upwards iteration\n * @returns {Node}\n */\n get __idiomorphRoot() {\n return this.originalNode;\n }\n }\n\n /**\n *\n * @param {string} newContent\n * @returns {Node | null | DocumentFragment}\n */\n function parseContent(newContent) {\n let parser = new DOMParser();\n\n // remove svgs to avoid false-positive matches on head, etc.\n let contentWithSvgsRemoved = newContent.replace(\n /]*>|>)([\\s\\S]*?)<\\/svg>/gim,\n \"\",\n );\n\n // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping\n if (\n contentWithSvgsRemoved.match(/<\\/html>/) ||\n contentWithSvgsRemoved.match(/<\\/head>/) ||\n contentWithSvgsRemoved.match(/<\\/body>/)\n ) {\n let content = parser.parseFromString(newContent, \"text/html\");\n // if it is a full HTML document, return the document itself as the parent container\n if (contentWithSvgsRemoved.match(/<\\/html>/)) {\n generatedByIdiomorph.add(content);\n return content;\n } else {\n // otherwise return the html element as the parent container\n let htmlElement = content.firstChild;\n if (htmlElement) {\n generatedByIdiomorph.add(htmlElement);\n }\n return htmlElement;\n }\n } else {\n // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help\n // deal with touchy tags like tr, tbody, etc.\n let responseDoc = parser.parseFromString(\n \"\",\n \"text/html\",\n );\n let content = /** @type {HTMLTemplateElement} */ (\n responseDoc.body.querySelector(\"template\")\n ).content;\n generatedByIdiomorph.add(content);\n return content;\n }\n }\n\n return { normalizeElement, normalizeParent };\n })();\n\n //=============================================================================\n // This is what ends up becoming the Idiomorph global object\n //=============================================================================\n return {\n morph,\n defaults,\n };\n})();\n\n/**\n * Morph the state of the currentElement based on the attributes and contents of\n * the newElement. Morphing may dispatch turbo:before-morph-element,\n * turbo:before-morph-attribute, and turbo:morph-element events.\n *\n * @param currentElement Element destination of morphing changes\n * @param newElement Element source of morphing changes\n */\nfunction morphElements(currentElement, newElement, { callbacks, ...options } = {}) {\n Idiomorph.morph(currentElement, newElement, {\n ...options,\n callbacks: new DefaultIdiomorphCallbacks(callbacks)\n });\n}\n\n/**\n * Morph the child elements of the currentElement based on the child elements of\n * the newElement. Morphing children may dispatch turbo:before-morph-element,\n * turbo:before-morph-attribute, and turbo:morph-element events.\n *\n * @param currentElement Element destination of morphing children changes\n * @param newElement Element source of morphing children changes\n */\nfunction morphChildren(currentElement, newElement, options = {}) {\n morphElements(currentElement, newElement.childNodes, {\n ...options,\n morphStyle: \"innerHTML\"\n });\n}\n\nfunction shouldRefreshFrameWithMorphing(currentFrame, newFrame) {\n return currentFrame instanceof FrameElement &&\n currentFrame.shouldReloadWithMorph && (!newFrame || areFramesCompatibleForRefreshing(currentFrame, newFrame)) &&\n !currentFrame.closest(\"[data-turbo-permanent]\")\n}\n\nfunction areFramesCompatibleForRefreshing(currentFrame, newFrame) {\n // newFrame cannot yet be an instance of FrameElement because custom\n // elements don't get initialized until they're attached to the DOM, so\n // test its Element#nodeName instead\n return newFrame instanceof Element && newFrame.nodeName === \"TURBO-FRAME\" && currentFrame.id === newFrame.id &&\n (!newFrame.getAttribute(\"src\") || urlsAreEqual(currentFrame.src, newFrame.getAttribute(\"src\")))\n}\n\nfunction closestFrameReloadableWithMorphing(node) {\n return node.parentElement.closest(\"turbo-frame[src][refresh=morph]\")\n}\n\nclass DefaultIdiomorphCallbacks {\n #beforeNodeMorphed\n\n constructor({ beforeNodeMorphed } = {}) {\n this.#beforeNodeMorphed = beforeNodeMorphed || (() => true);\n }\n\n beforeNodeAdded = (node) => {\n return !(node.id && node.hasAttribute(\"data-turbo-permanent\") && document.getElementById(node.id))\n }\n\n beforeNodeMorphed = (currentElement, newElement) => {\n if (currentElement instanceof Element) {\n if (!currentElement.hasAttribute(\"data-turbo-permanent\") && this.#beforeNodeMorphed(currentElement, newElement)) {\n const event = dispatch(\"turbo:before-morph-element\", {\n cancelable: true,\n target: currentElement,\n detail: { currentElement, newElement }\n });\n\n return !event.defaultPrevented\n } else {\n return false\n }\n }\n }\n\n beforeAttributeUpdated = (attributeName, target, mutationType) => {\n const event = dispatch(\"turbo:before-morph-attribute\", {\n cancelable: true,\n target,\n detail: { attributeName, mutationType }\n });\n\n return !event.defaultPrevented\n }\n\n beforeNodeRemoved = (node) => {\n return this.beforeNodeMorphed(node)\n }\n\n afterNodeMorphed = (currentElement, newElement) => {\n if (currentElement instanceof Element) {\n dispatch(\"turbo:morph-element\", {\n target: currentElement,\n detail: { currentElement, newElement }\n });\n }\n }\n}\n\nclass MorphingFrameRenderer extends FrameRenderer {\n static renderElement(currentElement, newElement) {\n dispatch(\"turbo:before-frame-morph\", {\n target: currentElement,\n detail: { currentElement, newElement }\n });\n\n morphChildren(currentElement, newElement, {\n callbacks: {\n beforeNodeMorphed: (node, newNode) => {\n if (\n shouldRefreshFrameWithMorphing(node, newNode) &&\n closestFrameReloadableWithMorphing(node) === currentElement\n ) {\n node.reload();\n return false\n }\n return true\n }\n }\n });\n }\n\n async preservingPermanentElements(callback) {\n return await callback()\n }\n}\n\nclass ProgressBar {\n static animationDuration = 300 /*ms*/\n\n static get defaultCSS() {\n return unindent`\n .turbo-progress-bar {\n position: fixed;\n display: block;\n top: 0;\n left: 0;\n height: 3px;\n background: #0076ff;\n z-index: 2147483647;\n transition:\n width ${ProgressBar.animationDuration}ms ease-out,\n opacity ${ProgressBar.animationDuration / 2}ms ${ProgressBar.animationDuration / 2}ms ease-in;\n transform: translate3d(0, 0, 0);\n }\n `\n }\n\n hiding = false\n value = 0\n visible = false\n\n constructor() {\n this.stylesheetElement = this.createStylesheetElement();\n this.progressElement = this.createProgressElement();\n this.installStylesheetElement();\n this.setValue(0);\n }\n\n show() {\n if (!this.visible) {\n this.visible = true;\n this.installProgressElement();\n this.startTrickling();\n }\n }\n\n hide() {\n if (this.visible && !this.hiding) {\n this.hiding = true;\n this.fadeProgressElement(() => {\n this.uninstallProgressElement();\n this.stopTrickling();\n this.visible = false;\n this.hiding = false;\n });\n }\n }\n\n setValue(value) {\n this.value = value;\n this.refresh();\n }\n\n // Private\n\n installStylesheetElement() {\n document.head.insertBefore(this.stylesheetElement, document.head.firstChild);\n }\n\n installProgressElement() {\n this.progressElement.style.width = \"0\";\n this.progressElement.style.opacity = \"1\";\n document.documentElement.insertBefore(this.progressElement, document.body);\n this.refresh();\n }\n\n fadeProgressElement(callback) {\n this.progressElement.style.opacity = \"0\";\n setTimeout(callback, ProgressBar.animationDuration * 1.5);\n }\n\n uninstallProgressElement() {\n if (this.progressElement.parentNode) {\n document.documentElement.removeChild(this.progressElement);\n }\n }\n\n startTrickling() {\n if (!this.trickleInterval) {\n this.trickleInterval = window.setInterval(this.trickle, ProgressBar.animationDuration);\n }\n }\n\n stopTrickling() {\n window.clearInterval(this.trickleInterval);\n delete this.trickleInterval;\n }\n\n trickle = () => {\n this.setValue(this.value + Math.random() / 100);\n }\n\n refresh() {\n requestAnimationFrame(() => {\n this.progressElement.style.width = `${10 + this.value * 90}%`;\n });\n }\n\n createStylesheetElement() {\n const element = document.createElement(\"style\");\n element.type = \"text/css\";\n element.textContent = ProgressBar.defaultCSS;\n const cspNonce = getCspNonce();\n if (cspNonce) {\n element.nonce = cspNonce;\n }\n return element\n }\n\n createProgressElement() {\n const element = document.createElement(\"div\");\n element.className = \"turbo-progress-bar\";\n return element\n }\n}\n\nclass HeadSnapshot extends Snapshot {\n detailsByOuterHTML = this.children\n .filter((element) => !elementIsNoscript(element))\n .map((element) => elementWithoutNonce(element))\n .reduce((result, element) => {\n const { outerHTML } = element;\n const details =\n outerHTML in result\n ? result[outerHTML]\n : {\n type: elementType(element),\n tracked: elementIsTracked(element),\n elements: []\n };\n return {\n ...result,\n [outerHTML]: {\n ...details,\n elements: [...details.elements, element]\n }\n }\n }, {})\n\n get trackedElementSignature() {\n return Object.keys(this.detailsByOuterHTML)\n .filter((outerHTML) => this.detailsByOuterHTML[outerHTML].tracked)\n .join(\"\")\n }\n\n getScriptElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"script\", snapshot)\n }\n\n getStylesheetElementsNotInSnapshot(snapshot) {\n return this.getElementsMatchingTypeNotInSnapshot(\"stylesheet\", snapshot)\n }\n\n getElementsMatchingTypeNotInSnapshot(matchedType, snapshot) {\n return Object.keys(this.detailsByOuterHTML)\n .filter((outerHTML) => !(outerHTML in snapshot.detailsByOuterHTML))\n .map((outerHTML) => this.detailsByOuterHTML[outerHTML])\n .filter(({ type }) => type == matchedType)\n .map(({ elements: [element] }) => element)\n }\n\n get provisionalElements() {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const { type, tracked, elements } = this.detailsByOuterHTML[outerHTML];\n if (type == null && !tracked) {\n return [...result, ...elements]\n } else if (elements.length > 1) {\n return [...result, ...elements.slice(1)]\n } else {\n return result\n }\n }, [])\n }\n\n getMetaValue(name) {\n const element = this.findMetaElementByName(name);\n return element ? element.getAttribute(\"content\") : null\n }\n\n findMetaElementByName(name) {\n return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {\n const {\n elements: [element]\n } = this.detailsByOuterHTML[outerHTML];\n return elementIsMetaElementWithName(element, name) ? element : result\n }, undefined | undefined)\n }\n}\n\nfunction elementType(element) {\n if (elementIsScript(element)) {\n return \"script\"\n } else if (elementIsStylesheet(element)) {\n return \"stylesheet\"\n }\n}\n\nfunction elementIsTracked(element) {\n return element.getAttribute(\"data-turbo-track\") == \"reload\"\n}\n\nfunction elementIsScript(element) {\n const tagName = element.localName;\n return tagName == \"script\"\n}\n\nfunction elementIsNoscript(element) {\n const tagName = element.localName;\n return tagName == \"noscript\"\n}\n\nfunction elementIsStylesheet(element) {\n const tagName = element.localName;\n return tagName == \"style\" || (tagName == \"link\" && element.getAttribute(\"rel\") == \"stylesheet\")\n}\n\nfunction elementIsMetaElementWithName(element, name) {\n const tagName = element.localName;\n return tagName == \"meta\" && element.getAttribute(\"name\") == name\n}\n\nfunction elementWithoutNonce(element) {\n if (element.hasAttribute(\"nonce\")) {\n element.setAttribute(\"nonce\", \"\");\n }\n\n return element\n}\n\nclass PageSnapshot extends Snapshot {\n static fromHTMLString(html = \"\") {\n return this.fromDocument(parseHTMLDocument(html))\n }\n\n static fromElement(element) {\n return this.fromDocument(element.ownerDocument)\n }\n\n static fromDocument({ documentElement, body, head }) {\n return new this(documentElement, body, new HeadSnapshot(head))\n }\n\n constructor(documentElement, body, headSnapshot) {\n super(body);\n this.documentElement = documentElement;\n this.headSnapshot = headSnapshot;\n }\n\n clone() {\n const clonedElement = this.element.cloneNode(true);\n\n const selectElements = this.element.querySelectorAll(\"select\");\n const clonedSelectElements = clonedElement.querySelectorAll(\"select\");\n\n for (const [index, source] of selectElements.entries()) {\n const clone = clonedSelectElements[index];\n for (const option of clone.selectedOptions) option.selected = false;\n for (const option of source.selectedOptions) clone.options[option.index].selected = true;\n }\n\n for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type=\"password\"]')) {\n clonedPasswordInput.value = \"\";\n }\n\n for (const clonedNoscriptElement of clonedElement.querySelectorAll(\"noscript\")) {\n clonedNoscriptElement.remove();\n }\n\n return new PageSnapshot(this.documentElement, clonedElement, this.headSnapshot)\n }\n\n get lang() {\n return this.documentElement.getAttribute(\"lang\")\n }\n\n get dir() {\n return this.documentElement.getAttribute(\"dir\")\n }\n\n get headElement() {\n return this.headSnapshot.element\n }\n\n get rootLocation() {\n const root = this.getSetting(\"root\") ?? \"/\";\n return expandURL(root)\n }\n\n get cacheControlValue() {\n return this.getSetting(\"cache-control\")\n }\n\n get isPreviewable() {\n return this.cacheControlValue != \"no-preview\"\n }\n\n get isCacheable() {\n return this.cacheControlValue != \"no-cache\"\n }\n\n get isVisitable() {\n return this.getSetting(\"visit-control\") != \"reload\"\n }\n\n get prefersViewTransitions() {\n const viewTransitionEnabled = this.getSetting(\"view-transition\") === \"true\" || this.headSnapshot.getMetaValue(\"view-transition\") === \"same-origin\";\n return viewTransitionEnabled && !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n }\n\n get refreshMethod() {\n return this.getSetting(\"refresh-method\")\n }\n\n get refreshScroll() {\n return this.getSetting(\"refresh-scroll\")\n }\n\n // Private\n\n getSetting(name) {\n return this.headSnapshot.getMetaValue(`turbo-${name}`)\n }\n}\n\nclass ViewTransitioner {\n #viewTransitionStarted = false\n #lastOperation = Promise.resolve()\n\n renderChange(useViewTransition, render) {\n if (useViewTransition && this.viewTransitionsAvailable && !this.#viewTransitionStarted) {\n this.#viewTransitionStarted = true;\n this.#lastOperation = this.#lastOperation.then(async () => {\n await document.startViewTransition(render).finished;\n });\n } else {\n this.#lastOperation = this.#lastOperation.then(render);\n }\n\n return this.#lastOperation\n }\n\n get viewTransitionsAvailable() {\n return document.startViewTransition\n }\n}\n\nconst defaultOptions = {\n action: \"advance\",\n historyChanged: false,\n visitCachedSnapshot: () => {},\n willRender: true,\n updateHistory: true,\n shouldCacheSnapshot: true,\n acceptsStreamResponse: false,\n refresh: {}\n};\n\nconst TimingMetric = {\n visitStart: \"visitStart\",\n requestStart: \"requestStart\",\n requestEnd: \"requestEnd\",\n visitEnd: \"visitEnd\"\n};\n\nconst VisitState = {\n initialized: \"initialized\",\n started: \"started\",\n canceled: \"canceled\",\n failed: \"failed\",\n completed: \"completed\"\n};\n\nconst SystemStatusCode = {\n networkFailure: 0,\n timeoutFailure: -1,\n contentTypeMismatch: -2\n};\n\nconst Direction = {\n advance: \"forward\",\n restore: \"back\",\n replace: \"none\"\n};\n\nclass Visit {\n identifier = uuid() // Required by turbo-ios\n timingMetrics = {}\n\n followedRedirect = false\n historyChanged = false\n scrolled = false\n shouldCacheSnapshot = true\n acceptsStreamResponse = false\n snapshotCached = false\n state = VisitState.initialized\n viewTransitioner = new ViewTransitioner()\n\n constructor(delegate, location, restorationIdentifier, options = {}) {\n this.delegate = delegate;\n this.location = location;\n this.restorationIdentifier = restorationIdentifier || uuid();\n\n const {\n action,\n historyChanged,\n referrer,\n snapshot,\n snapshotHTML,\n response,\n visitCachedSnapshot,\n willRender,\n updateHistory,\n shouldCacheSnapshot,\n acceptsStreamResponse,\n direction,\n refresh\n } = {\n ...defaultOptions,\n ...options\n };\n this.action = action;\n this.historyChanged = historyChanged;\n this.referrer = referrer;\n this.snapshot = snapshot;\n this.snapshotHTML = snapshotHTML;\n this.response = response;\n this.isPageRefresh = this.view.isPageRefresh(this);\n this.visitCachedSnapshot = visitCachedSnapshot;\n this.willRender = willRender;\n this.updateHistory = updateHistory;\n this.scrolled = !willRender;\n this.shouldCacheSnapshot = shouldCacheSnapshot;\n this.acceptsStreamResponse = acceptsStreamResponse;\n this.direction = direction || Direction[action];\n this.refresh = refresh;\n }\n\n get adapter() {\n return this.delegate.adapter\n }\n\n get view() {\n return this.delegate.view\n }\n\n get history() {\n return this.delegate.history\n }\n\n get restorationData() {\n return this.history.getRestorationDataForIdentifier(this.restorationIdentifier)\n }\n\n start() {\n if (this.state == VisitState.initialized) {\n this.recordTimingMetric(TimingMetric.visitStart);\n this.state = VisitState.started;\n this.adapter.visitStarted(this);\n this.delegate.visitStarted(this);\n }\n }\n\n cancel() {\n if (this.state == VisitState.started) {\n if (this.request) {\n this.request.cancel();\n }\n this.cancelRender();\n this.state = VisitState.canceled;\n }\n }\n\n complete() {\n if (this.state == VisitState.started) {\n this.recordTimingMetric(TimingMetric.visitEnd);\n this.adapter.visitCompleted(this);\n this.state = VisitState.completed;\n this.followRedirect();\n\n if (!this.followedRedirect) {\n this.delegate.visitCompleted(this);\n }\n }\n }\n\n fail() {\n if (this.state == VisitState.started) {\n this.state = VisitState.failed;\n this.adapter.visitFailed(this);\n this.delegate.visitCompleted(this);\n }\n }\n\n changeHistory() {\n if (!this.historyChanged && this.updateHistory) {\n const actionForHistory = this.location.href === this.referrer?.href ? \"replace\" : this.action;\n const method = getHistoryMethodForAction(actionForHistory);\n this.history.update(method, this.location, this.restorationIdentifier);\n this.historyChanged = true;\n }\n }\n\n issueRequest() {\n if (this.hasPreloadedResponse()) {\n this.simulateRequest();\n } else if (this.shouldIssueRequest() && !this.request) {\n this.request = new FetchRequest(this, FetchMethod.get, this.location);\n this.request.perform();\n }\n }\n\n simulateRequest() {\n if (this.response) {\n this.startRequest();\n this.recordResponse();\n this.finishRequest();\n }\n }\n\n startRequest() {\n this.recordTimingMetric(TimingMetric.requestStart);\n this.adapter.visitRequestStarted(this);\n }\n\n recordResponse(response = this.response) {\n this.response = response;\n if (response) {\n const { statusCode } = response;\n if (isSuccessful(statusCode)) {\n this.adapter.visitRequestCompleted(this);\n } else {\n this.adapter.visitRequestFailedWithStatusCode(this, statusCode);\n }\n }\n }\n\n finishRequest() {\n this.recordTimingMetric(TimingMetric.requestEnd);\n this.adapter.visitRequestFinished(this);\n }\n\n loadResponse() {\n if (this.response) {\n const { statusCode, responseHTML } = this.response;\n this.render(async () => {\n if (this.shouldCacheSnapshot) this.cacheSnapshot();\n if (this.view.renderPromise) await this.view.renderPromise;\n\n if (isSuccessful(statusCode) && responseHTML != null) {\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n await this.renderPageSnapshot(snapshot, false);\n\n this.adapter.visitRendered(this);\n this.complete();\n } else {\n await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML), this);\n this.adapter.visitRendered(this);\n this.fail();\n }\n });\n }\n }\n\n getCachedSnapshot() {\n const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot();\n\n if (snapshot && (!getAnchor(this.location) || snapshot.hasAnchor(getAnchor(this.location)))) {\n if (this.action == \"restore\" || snapshot.isPreviewable) {\n return snapshot\n }\n }\n }\n\n getPreloadedSnapshot() {\n if (this.snapshotHTML) {\n return PageSnapshot.fromHTMLString(this.snapshotHTML)\n }\n }\n\n hasCachedSnapshot() {\n return this.getCachedSnapshot() != null\n }\n\n loadCachedSnapshot() {\n const snapshot = this.getCachedSnapshot();\n if (snapshot) {\n const isPreview = this.shouldIssueRequest();\n this.render(async () => {\n this.cacheSnapshot();\n if (this.isPageRefresh) {\n this.adapter.visitRendered(this);\n } else {\n if (this.view.renderPromise) await this.view.renderPromise;\n\n await this.renderPageSnapshot(snapshot, isPreview);\n\n this.adapter.visitRendered(this);\n if (!isPreview) {\n this.complete();\n }\n }\n });\n }\n }\n\n followRedirect() {\n if (this.redirectedToLocation && !this.followedRedirect && this.response?.redirected) {\n this.adapter.visitProposedToLocation(this.redirectedToLocation, {\n action: \"replace\",\n response: this.response,\n shouldCacheSnapshot: false,\n willRender: false\n });\n this.followedRedirect = true;\n }\n }\n\n // Fetch request delegate\n\n prepareRequest(request) {\n if (this.acceptsStreamResponse) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n\n requestStarted() {\n this.startRequest();\n }\n\n requestPreventedHandlingResponse(_request, _response) {}\n\n async requestSucceededWithResponse(request, response) {\n const responseHTML = await response.responseHTML;\n const { redirected, statusCode } = response;\n if (responseHTML == undefined) {\n this.recordResponse({\n statusCode: SystemStatusCode.contentTypeMismatch,\n redirected\n });\n } else {\n this.redirectedToLocation = response.redirected ? response.location : undefined;\n this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n }\n }\n\n async requestFailedWithResponse(request, response) {\n const responseHTML = await response.responseHTML;\n const { redirected, statusCode } = response;\n if (responseHTML == undefined) {\n this.recordResponse({\n statusCode: SystemStatusCode.contentTypeMismatch,\n redirected\n });\n } else {\n this.recordResponse({ statusCode: statusCode, responseHTML, redirected });\n }\n }\n\n requestErrored(_request, _error) {\n this.recordResponse({\n statusCode: SystemStatusCode.networkFailure,\n redirected: false\n });\n }\n\n requestFinished() {\n this.finishRequest();\n }\n\n // Scrolling\n\n performScroll() {\n if (!this.scrolled && !this.view.forceReloaded && !this.view.shouldPreserveScrollPosition(this)) {\n if (this.action == \"restore\") {\n this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();\n } else {\n this.scrollToAnchor() || this.view.scrollToTop();\n }\n\n this.scrolled = true;\n }\n }\n\n scrollToRestoredPosition() {\n const { scrollPosition } = this.restorationData;\n if (scrollPosition) {\n this.view.scrollToPosition(scrollPosition);\n return true\n }\n }\n\n scrollToAnchor() {\n const anchor = getAnchor(this.location);\n if (anchor != null) {\n this.view.scrollToAnchor(anchor);\n return true\n }\n }\n\n // Instrumentation\n\n recordTimingMetric(metric) {\n this.timingMetrics[metric] = new Date().getTime();\n }\n\n getTimingMetrics() {\n return { ...this.timingMetrics }\n }\n\n // Private\n\n hasPreloadedResponse() {\n return typeof this.response == \"object\"\n }\n\n shouldIssueRequest() {\n if (this.action == \"restore\") {\n return !this.hasCachedSnapshot()\n } else {\n return this.willRender\n }\n }\n\n cacheSnapshot() {\n if (!this.snapshotCached) {\n this.view.cacheSnapshot(this.snapshot).then((snapshot) => snapshot && this.visitCachedSnapshot(snapshot));\n this.snapshotCached = true;\n }\n }\n\n async render(callback) {\n this.cancelRender();\n await new Promise((resolve) => {\n this.frame =\n document.visibilityState === \"hidden\" ? setTimeout(() => resolve(), 0) : requestAnimationFrame(() => resolve());\n });\n await callback();\n delete this.frame;\n }\n\n async renderPageSnapshot(snapshot, isPreview) {\n await this.viewTransitioner.renderChange(this.view.shouldTransitionTo(snapshot), async () => {\n await this.view.renderPage(snapshot, isPreview, this.willRender, this);\n this.performScroll();\n });\n }\n\n cancelRender() {\n if (this.frame) {\n cancelAnimationFrame(this.frame);\n delete this.frame;\n }\n }\n}\n\nfunction isSuccessful(statusCode) {\n return statusCode >= 200 && statusCode < 300\n}\n\nclass BrowserAdapter {\n progressBar = new ProgressBar()\n\n constructor(session) {\n this.session = session;\n }\n\n visitProposedToLocation(location, options) {\n if (locationIsVisitable(location, this.navigator.rootLocation)) {\n this.navigator.startVisit(location, options?.restorationIdentifier || uuid(), options);\n } else {\n window.location.href = location.toString();\n }\n }\n\n visitStarted(visit) {\n this.location = visit.location;\n this.redirectedToLocation = null;\n\n visit.loadCachedSnapshot();\n visit.issueRequest();\n }\n\n visitRequestStarted(visit) {\n this.progressBar.setValue(0);\n if (visit.hasCachedSnapshot() || visit.action != \"restore\") {\n this.showVisitProgressBarAfterDelay();\n } else {\n this.showProgressBar();\n }\n }\n\n visitRequestCompleted(visit) {\n visit.loadResponse();\n\n if (visit.response.redirected) {\n this.redirectedToLocation = visit.redirectedToLocation;\n }\n }\n\n visitRequestFailedWithStatusCode(visit, statusCode) {\n switch (statusCode) {\n case SystemStatusCode.networkFailure:\n case SystemStatusCode.timeoutFailure:\n case SystemStatusCode.contentTypeMismatch:\n return this.reload({\n reason: \"request_failed\",\n context: {\n statusCode\n }\n })\n default:\n return visit.loadResponse()\n }\n }\n\n visitRequestFinished(_visit) {}\n\n visitCompleted(_visit) {\n this.progressBar.setValue(1);\n this.hideVisitProgressBar();\n }\n\n pageInvalidated(reason) {\n this.reload(reason);\n }\n\n visitFailed(_visit) {\n this.progressBar.setValue(1);\n this.hideVisitProgressBar();\n }\n\n visitRendered(_visit) {}\n\n // Link prefetching\n\n linkPrefetchingIsEnabledForLocation(location) {\n return true\n }\n\n // Form Submission Delegate\n\n formSubmissionStarted(_formSubmission) {\n this.progressBar.setValue(0);\n this.showFormProgressBarAfterDelay();\n }\n\n formSubmissionFinished(_formSubmission) {\n this.progressBar.setValue(1);\n this.hideFormProgressBar();\n }\n\n // Private\n\n showVisitProgressBarAfterDelay() {\n this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n\n hideVisitProgressBar() {\n this.progressBar.hide();\n if (this.visitProgressBarTimeout != null) {\n window.clearTimeout(this.visitProgressBarTimeout);\n delete this.visitProgressBarTimeout;\n }\n }\n\n showFormProgressBarAfterDelay() {\n if (this.formProgressBarTimeout == null) {\n this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);\n }\n }\n\n hideFormProgressBar() {\n this.progressBar.hide();\n if (this.formProgressBarTimeout != null) {\n window.clearTimeout(this.formProgressBarTimeout);\n delete this.formProgressBarTimeout;\n }\n }\n\n showProgressBar = () => {\n this.progressBar.show();\n }\n\n reload(reason) {\n dispatch(\"turbo:reload\", { detail: reason });\n\n window.location.href = (this.redirectedToLocation || this.location)?.toString() || window.location.href;\n }\n\n get navigator() {\n return this.session.navigator\n }\n}\n\nclass CacheObserver {\n selector = \"[data-turbo-temporary]\"\n\n started = false\n\n start() {\n if (!this.started) {\n this.started = true;\n addEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n }\n }\n\n stop() {\n if (this.started) {\n this.started = false;\n removeEventListener(\"turbo:before-cache\", this.removeTemporaryElements, false);\n }\n }\n\n removeTemporaryElements = (_event) => {\n for (const element of this.temporaryElements) {\n element.remove();\n }\n }\n\n get temporaryElements() {\n return [...document.querySelectorAll(this.selector)]\n }\n}\n\nclass FrameRedirector {\n constructor(session, element) {\n this.session = session;\n this.element = element;\n this.linkInterceptor = new LinkInterceptor(this, element);\n this.formSubmitObserver = new FormSubmitObserver(this, element);\n }\n\n start() {\n this.linkInterceptor.start();\n this.formSubmitObserver.start();\n }\n\n stop() {\n this.linkInterceptor.stop();\n this.formSubmitObserver.stop();\n }\n\n // Link interceptor delegate\n\n shouldInterceptLinkClick(element, _location, _event) {\n return this.#shouldRedirect(element)\n }\n\n linkClickIntercepted(element, url, event) {\n const frame = this.#findFrameElement(element);\n if (frame) {\n frame.delegate.linkClickIntercepted(element, url, event);\n }\n }\n\n // Form submit observer delegate\n\n willSubmitForm(element, submitter) {\n return (\n element.closest(\"turbo-frame\") == null &&\n this.#shouldSubmit(element, submitter) &&\n this.#shouldRedirect(element, submitter)\n )\n }\n\n formSubmitted(element, submitter) {\n const frame = this.#findFrameElement(element, submitter);\n if (frame) {\n frame.delegate.formSubmitted(element, submitter);\n }\n }\n\n #shouldSubmit(form, submitter) {\n const action = getAction$1(form, submitter);\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const rootLocation = expandURL(meta?.content ?? \"/\");\n\n return this.#shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation)\n }\n\n #shouldRedirect(element, submitter) {\n const isNavigatable =\n element instanceof HTMLFormElement\n ? this.session.submissionIsNavigatable(element, submitter)\n : this.session.elementIsNavigatable(element);\n\n if (isNavigatable) {\n const frame = this.#findFrameElement(element, submitter);\n return frame ? frame != element.closest(\"turbo-frame\") : false\n } else {\n return false\n }\n }\n\n #findFrameElement(element, submitter) {\n const id = submitter?.getAttribute(\"data-turbo-frame\") || element.getAttribute(\"data-turbo-frame\");\n if (id && id != \"_top\") {\n const frame = this.element.querySelector(`#${id}:not([disabled])`);\n if (frame instanceof FrameElement) {\n return frame\n }\n }\n }\n}\n\nclass History {\n location\n restorationIdentifier = uuid()\n restorationData = {}\n started = false\n currentIndex = 0\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.started) {\n addEventListener(\"popstate\", this.onPopState, false);\n this.currentIndex = history.state?.turbo?.restorationIndex || 0;\n this.started = true;\n this.replace(new URL(window.location.href));\n }\n }\n\n stop() {\n if (this.started) {\n removeEventListener(\"popstate\", this.onPopState, false);\n this.started = false;\n }\n }\n\n push(location, restorationIdentifier) {\n this.update(history.pushState, location, restorationIdentifier);\n }\n\n replace(location, restorationIdentifier) {\n this.update(history.replaceState, location, restorationIdentifier);\n }\n\n update(method, location, restorationIdentifier = uuid()) {\n if (method === history.pushState) ++this.currentIndex;\n\n const state = { turbo: { restorationIdentifier, restorationIndex: this.currentIndex } };\n method.call(history, state, \"\", location.href);\n this.location = location;\n this.restorationIdentifier = restorationIdentifier;\n }\n\n // Restoration data\n\n getRestorationDataForIdentifier(restorationIdentifier) {\n return this.restorationData[restorationIdentifier] || {}\n }\n\n updateRestorationData(additionalData) {\n const { restorationIdentifier } = this;\n const restorationData = this.restorationData[restorationIdentifier];\n this.restorationData[restorationIdentifier] = {\n ...restorationData,\n ...additionalData\n };\n }\n\n // Scroll restoration\n\n assumeControlOfScrollRestoration() {\n if (!this.previousScrollRestoration) {\n this.previousScrollRestoration = history.scrollRestoration ?? \"auto\";\n history.scrollRestoration = \"manual\";\n }\n }\n\n relinquishControlOfScrollRestoration() {\n if (this.previousScrollRestoration) {\n history.scrollRestoration = this.previousScrollRestoration;\n delete this.previousScrollRestoration;\n }\n }\n\n // Event handlers\n\n onPopState = (event) => {\n const { turbo } = event.state || {};\n this.location = new URL(window.location.href);\n\n if (turbo) {\n const { restorationIdentifier, restorationIndex } = turbo;\n this.restorationIdentifier = restorationIdentifier;\n const direction = restorationIndex > this.currentIndex ? \"forward\" : \"back\";\n this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location, restorationIdentifier, direction);\n this.currentIndex = restorationIndex;\n } else {\n this.currentIndex++;\n this.delegate.historyPoppedWithEmptyState(this.location);\n }\n }\n}\n\nclass LinkPrefetchObserver {\n started = false\n #prefetchedLink = null\n\n constructor(delegate, eventTarget) {\n this.delegate = delegate;\n this.eventTarget = eventTarget;\n }\n\n start() {\n if (this.started) return\n\n if (this.eventTarget.readyState === \"loading\") {\n this.eventTarget.addEventListener(\"DOMContentLoaded\", this.#enable, { once: true });\n } else {\n this.#enable();\n }\n }\n\n stop() {\n if (!this.started) return\n\n this.eventTarget.removeEventListener(\"mouseenter\", this.#tryToPrefetchRequest, {\n capture: true,\n passive: true\n });\n this.eventTarget.removeEventListener(\"mouseleave\", this.#cancelRequestIfObsolete, {\n capture: true,\n passive: true\n });\n\n this.eventTarget.removeEventListener(\"turbo:before-fetch-request\", this.#tryToUsePrefetchedRequest, true);\n this.started = false;\n }\n\n #enable = () => {\n this.eventTarget.addEventListener(\"mouseenter\", this.#tryToPrefetchRequest, {\n capture: true,\n passive: true\n });\n this.eventTarget.addEventListener(\"mouseleave\", this.#cancelRequestIfObsolete, {\n capture: true,\n passive: true\n });\n\n this.eventTarget.addEventListener(\"turbo:before-fetch-request\", this.#tryToUsePrefetchedRequest, true);\n this.started = true;\n }\n\n #tryToPrefetchRequest = (event) => {\n if (getMetaContent(\"turbo-prefetch\") === \"false\") return\n\n const target = event.target;\n const isLink = target.matches && target.matches(\"a[href]:not([target^=_]):not([download])\");\n\n if (isLink && this.#isPrefetchable(target)) {\n const link = target;\n const location = getLocationForLink(link);\n\n if (this.delegate.canPrefetchRequestToLocation(link, location)) {\n this.#prefetchedLink = link;\n\n const fetchRequest = new FetchRequest(\n this,\n FetchMethod.get,\n location,\n new URLSearchParams(),\n target\n );\n\n fetchRequest.fetchOptions.priority = \"low\";\n\n prefetchCache.putLater(location, fetchRequest, this.#cacheTtl);\n }\n }\n }\n\n #cancelRequestIfObsolete = (event) => {\n if (event.target === this.#prefetchedLink) this.#cancelPrefetchRequest();\n }\n\n #cancelPrefetchRequest = () => {\n prefetchCache.clear();\n this.#prefetchedLink = null;\n }\n\n #tryToUsePrefetchedRequest = (event) => {\n if (event.target.tagName !== \"FORM\" && event.detail.fetchOptions.method === \"GET\") {\n const cached = prefetchCache.get(event.detail.url);\n\n if (cached) {\n // User clicked link, use cache response\n event.detail.fetchRequest = cached;\n }\n\n prefetchCache.clear();\n }\n }\n\n prepareRequest(request) {\n const link = request.target;\n\n request.headers[\"X-Sec-Purpose\"] = \"prefetch\";\n\n const turboFrame = link.closest(\"turbo-frame\");\n const turboFrameTarget = link.getAttribute(\"data-turbo-frame\") || turboFrame?.getAttribute(\"target\") || turboFrame?.id;\n\n if (turboFrameTarget && turboFrameTarget !== \"_top\") {\n request.headers[\"Turbo-Frame\"] = turboFrameTarget;\n }\n }\n\n // Fetch request interface\n\n requestSucceededWithResponse() {}\n\n requestStarted(fetchRequest) {}\n\n requestErrored(fetchRequest) {}\n\n requestFinished(fetchRequest) {}\n\n requestPreventedHandlingResponse(fetchRequest, fetchResponse) {}\n\n requestFailedWithResponse(fetchRequest, fetchResponse) {}\n\n get #cacheTtl() {\n return Number(getMetaContent(\"turbo-prefetch-cache-time\")) || cacheTtl\n }\n\n #isPrefetchable(link) {\n const href = link.getAttribute(\"href\");\n\n if (!href) return false\n\n if (unfetchableLink(link)) return false\n if (linkToTheSamePage(link)) return false\n if (linkOptsOut(link)) return false\n if (nonSafeLink(link)) return false\n if (eventPrevented(link)) return false\n\n return true\n }\n}\n\nconst unfetchableLink = (link) => {\n return link.origin !== document.location.origin || ![\"http:\", \"https:\"].includes(link.protocol) || link.hasAttribute(\"target\")\n};\n\nconst linkToTheSamePage = (link) => {\n return (link.pathname + link.search === document.location.pathname + document.location.search) || link.href.startsWith(\"#\")\n};\n\nconst linkOptsOut = (link) => {\n if (link.getAttribute(\"data-turbo-prefetch\") === \"false\") return true\n if (link.getAttribute(\"data-turbo\") === \"false\") return true\n\n const turboPrefetchParent = findClosestRecursively(link, \"[data-turbo-prefetch]\");\n if (turboPrefetchParent && turboPrefetchParent.getAttribute(\"data-turbo-prefetch\") === \"false\") return true\n\n return false\n};\n\nconst nonSafeLink = (link) => {\n const turboMethod = link.getAttribute(\"data-turbo-method\");\n if (turboMethod && turboMethod.toLowerCase() !== \"get\") return true\n\n if (isUJS(link)) return true\n if (link.hasAttribute(\"data-turbo-confirm\")) return true\n if (link.hasAttribute(\"data-turbo-stream\")) return true\n\n return false\n};\n\nconst isUJS = (link) => {\n return link.hasAttribute(\"data-remote\") || link.hasAttribute(\"data-behavior\") || link.hasAttribute(\"data-confirm\") || link.hasAttribute(\"data-method\")\n};\n\nconst eventPrevented = (link) => {\n const event = dispatch(\"turbo:before-prefetch\", { target: link, cancelable: true });\n return event.defaultPrevented\n};\n\nclass Navigator {\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n proposeVisit(location, options = {}) {\n if (this.delegate.allowsVisitingLocationWithAction(location, options.action)) {\n this.delegate.visitProposedToLocation(location, options);\n }\n }\n\n startVisit(locatable, restorationIdentifier, options = {}) {\n this.stop();\n this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, {\n referrer: this.location,\n ...options\n });\n this.currentVisit.start();\n }\n\n submitForm(form, submitter) {\n this.stop();\n this.formSubmission = new FormSubmission(this, form, submitter, true);\n\n this.formSubmission.start();\n }\n\n stop() {\n if (this.formSubmission) {\n this.formSubmission.stop();\n delete this.formSubmission;\n }\n\n if (this.currentVisit) {\n this.currentVisit.cancel();\n delete this.currentVisit;\n }\n }\n\n get adapter() {\n return this.delegate.adapter\n }\n\n get view() {\n return this.delegate.view\n }\n\n get rootLocation() {\n return this.view.snapshot.rootLocation\n }\n\n get history() {\n return this.delegate.history\n }\n\n // Form submission delegate\n\n formSubmissionStarted(formSubmission) {\n // Not all adapters implement formSubmissionStarted\n if (typeof this.adapter.formSubmissionStarted === \"function\") {\n this.adapter.formSubmissionStarted(formSubmission);\n }\n }\n\n async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) {\n if (formSubmission == this.formSubmission) {\n const responseHTML = await fetchResponse.responseHTML;\n if (responseHTML) {\n const shouldCacheSnapshot = formSubmission.isSafe;\n if (!shouldCacheSnapshot) {\n this.view.clearSnapshotCache();\n }\n\n const { statusCode, redirected } = fetchResponse;\n const action = this.#getActionForFormSubmission(formSubmission, fetchResponse);\n const visitOptions = {\n action,\n shouldCacheSnapshot,\n response: { statusCode, responseHTML, redirected }\n };\n this.proposeVisit(fetchResponse.location, visitOptions);\n }\n }\n }\n\n async formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n const responseHTML = await fetchResponse.responseHTML;\n\n if (responseHTML) {\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n if (fetchResponse.serverError) {\n await this.view.renderError(snapshot, this.currentVisit);\n } else {\n await this.view.renderPage(snapshot, false, true, this.currentVisit);\n }\n if (snapshot.refreshScroll !== \"preserve\") {\n this.view.scrollToTop();\n }\n this.view.clearSnapshotCache();\n }\n }\n\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n\n formSubmissionFinished(formSubmission) {\n // Not all adapters implement formSubmissionFinished\n if (typeof this.adapter.formSubmissionFinished === \"function\") {\n this.adapter.formSubmissionFinished(formSubmission);\n }\n }\n\n // Link prefetching\n\n linkPrefetchingIsEnabledForLocation(location) {\n // Not all adapters implement linkPrefetchingIsEnabledForLocation\n if (typeof this.adapter.linkPrefetchingIsEnabledForLocation === \"function\") {\n return this.adapter.linkPrefetchingIsEnabledForLocation(location)\n }\n\n return true\n }\n\n // Visit delegate\n\n visitStarted(visit) {\n this.delegate.visitStarted(visit);\n }\n\n visitCompleted(visit) {\n this.delegate.visitCompleted(visit);\n delete this.currentVisit;\n }\n\n // Same-page links are no longer handled with a Visit.\n // This method is still needed for Turbo Native adapters.\n locationWithActionIsSamePage(location, action) {\n return false\n }\n\n // Visits\n\n get location() {\n return this.history.location\n }\n\n get restorationIdentifier() {\n return this.history.restorationIdentifier\n }\n\n #getActionForFormSubmission(formSubmission, fetchResponse) {\n const { submitter, formElement } = formSubmission;\n return getVisitAction(submitter, formElement) || this.#getDefaultAction(fetchResponse)\n }\n\n #getDefaultAction(fetchResponse) {\n const sameLocationRedirect = fetchResponse.redirected && fetchResponse.location.href === this.location?.href;\n return sameLocationRedirect ? \"replace\" : \"advance\"\n }\n}\n\nconst PageStage = {\n initial: 0,\n loading: 1,\n interactive: 2,\n complete: 3\n};\n\nclass PageObserver {\n stage = PageStage.initial\n started = false\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.started) {\n if (this.stage == PageStage.initial) {\n this.stage = PageStage.loading;\n }\n document.addEventListener(\"readystatechange\", this.interpretReadyState, false);\n addEventListener(\"pagehide\", this.pageWillUnload, false);\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n document.removeEventListener(\"readystatechange\", this.interpretReadyState, false);\n removeEventListener(\"pagehide\", this.pageWillUnload, false);\n this.started = false;\n }\n }\n\n interpretReadyState = () => {\n const { readyState } = this;\n if (readyState == \"interactive\") {\n this.pageIsInteractive();\n } else if (readyState == \"complete\") {\n this.pageIsComplete();\n }\n }\n\n pageIsInteractive() {\n if (this.stage == PageStage.loading) {\n this.stage = PageStage.interactive;\n this.delegate.pageBecameInteractive();\n }\n }\n\n pageIsComplete() {\n this.pageIsInteractive();\n if (this.stage == PageStage.interactive) {\n this.stage = PageStage.complete;\n this.delegate.pageLoaded();\n }\n }\n\n pageWillUnload = () => {\n this.delegate.pageWillUnload();\n }\n\n get readyState() {\n return document.readyState\n }\n}\n\nclass ScrollObserver {\n started = false\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.started) {\n addEventListener(\"scroll\", this.onScroll, false);\n this.onScroll();\n this.started = true;\n }\n }\n\n stop() {\n if (this.started) {\n removeEventListener(\"scroll\", this.onScroll, false);\n this.started = false;\n }\n }\n\n onScroll = () => {\n this.updatePosition({ x: window.pageXOffset, y: window.pageYOffset });\n }\n\n // Private\n\n updatePosition(position) {\n this.delegate.scrollPositionChanged(position);\n }\n}\n\nclass StreamMessageRenderer {\n render({ fragment }) {\n Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), () => {\n withAutofocusFromFragment(fragment, () => {\n withPreservedFocus(() => {\n document.documentElement.appendChild(fragment);\n });\n });\n });\n }\n\n // Bardo delegate\n\n enteringBardo(currentPermanentElement, newPermanentElement) {\n newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true));\n }\n\n leavingBardo() {}\n}\n\nfunction getPermanentElementMapForFragment(fragment) {\n const permanentElementsInDocument = queryPermanentElementsAll(document.documentElement);\n const permanentElementMap = {};\n for (const permanentElementInDocument of permanentElementsInDocument) {\n const { id } = permanentElementInDocument;\n\n for (const streamElement of fragment.querySelectorAll(\"turbo-stream\")) {\n const elementInStream = getPermanentElementById(streamElement.templateElement.content, id);\n\n if (elementInStream) {\n permanentElementMap[id] = [permanentElementInDocument, elementInStream];\n }\n }\n }\n\n return permanentElementMap\n}\n\nasync function withAutofocusFromFragment(fragment, callback) {\n const generatedID = `turbo-stream-autofocus-${uuid()}`;\n const turboStreams = fragment.querySelectorAll(\"turbo-stream\");\n const elementWithAutofocus = firstAutofocusableElementInStreams(turboStreams);\n let willAutofocusId = null;\n\n if (elementWithAutofocus) {\n if (elementWithAutofocus.id) {\n willAutofocusId = elementWithAutofocus.id;\n } else {\n willAutofocusId = generatedID;\n }\n\n elementWithAutofocus.id = willAutofocusId;\n }\n\n callback();\n await nextRepaint();\n\n const hasNoActiveElement = document.activeElement == null || document.activeElement == document.body;\n\n if (hasNoActiveElement && willAutofocusId) {\n const elementToAutofocus = document.getElementById(willAutofocusId);\n\n if (elementIsFocusable(elementToAutofocus)) {\n elementToAutofocus.focus();\n }\n if (elementToAutofocus && elementToAutofocus.id == generatedID) {\n elementToAutofocus.removeAttribute(\"id\");\n }\n }\n}\n\nasync function withPreservedFocus(callback) {\n const [activeElementBeforeRender, activeElementAfterRender] = await around(callback, () => document.activeElement);\n\n const restoreFocusTo = activeElementBeforeRender && activeElementBeforeRender.id;\n\n if (restoreFocusTo) {\n const elementToFocus = document.getElementById(restoreFocusTo);\n\n if (elementIsFocusable(elementToFocus) && elementToFocus != activeElementAfterRender) {\n elementToFocus.focus();\n }\n }\n}\n\nfunction firstAutofocusableElementInStreams(nodeListOfStreamElements) {\n for (const streamElement of nodeListOfStreamElements) {\n const elementWithAutofocus = queryAutofocusableElement(streamElement.templateElement.content);\n\n if (elementWithAutofocus) return elementWithAutofocus\n }\n\n return null\n}\n\nclass StreamObserver {\n sources = new Set()\n #started = false\n\n constructor(delegate) {\n this.delegate = delegate;\n }\n\n start() {\n if (!this.#started) {\n this.#started = true;\n addEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n\n stop() {\n if (this.#started) {\n this.#started = false;\n removeEventListener(\"turbo:before-fetch-response\", this.inspectFetchResponse, false);\n }\n }\n\n connectStreamSource(source) {\n if (!this.streamSourceIsConnected(source)) {\n this.sources.add(source);\n source.addEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n\n disconnectStreamSource(source) {\n if (this.streamSourceIsConnected(source)) {\n this.sources.delete(source);\n source.removeEventListener(\"message\", this.receiveMessageEvent, false);\n }\n }\n\n streamSourceIsConnected(source) {\n return this.sources.has(source)\n }\n\n inspectFetchResponse = (event) => {\n const response = fetchResponseFromEvent(event);\n if (response && fetchResponseIsStream(response)) {\n event.preventDefault();\n this.receiveMessageResponse(response);\n }\n }\n\n receiveMessageEvent = (event) => {\n if (this.#started && typeof event.data == \"string\") {\n this.receiveMessageHTML(event.data);\n }\n }\n\n async receiveMessageResponse(response) {\n const html = await response.responseHTML;\n if (html) {\n this.receiveMessageHTML(html);\n }\n }\n\n receiveMessageHTML(html) {\n this.delegate.receivedMessageFromStream(StreamMessage.wrap(html));\n }\n}\n\nfunction fetchResponseFromEvent(event) {\n const fetchResponse = event.detail?.fetchResponse;\n if (fetchResponse instanceof FetchResponse) {\n return fetchResponse\n }\n}\n\nfunction fetchResponseIsStream(response) {\n const contentType = response.contentType ?? \"\";\n return contentType.startsWith(StreamMessage.contentType)\n}\n\nclass ErrorRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n const { documentElement, body } = document;\n\n documentElement.replaceChild(newElement, body);\n }\n\n async render() {\n this.replaceHeadAndBody();\n this.activateScriptElements();\n }\n\n replaceHeadAndBody() {\n const { documentElement, head } = document;\n documentElement.replaceChild(this.newHead, head);\n this.renderElement(this.currentElement, this.newElement);\n }\n\n activateScriptElements() {\n for (const replaceableElement of this.scriptElements) {\n const parentNode = replaceableElement.parentNode;\n if (parentNode) {\n const element = activateScriptElement(replaceableElement);\n parentNode.replaceChild(element, replaceableElement);\n }\n }\n }\n\n get newHead() {\n return this.newSnapshot.headSnapshot.element\n }\n\n get scriptElements() {\n return document.documentElement.querySelectorAll(\"script\")\n }\n}\n\nclass PageRenderer extends Renderer {\n static renderElement(currentElement, newElement) {\n if (document.body && newElement instanceof HTMLBodyElement) {\n document.body.replaceWith(newElement);\n } else {\n document.documentElement.appendChild(newElement);\n }\n }\n\n get shouldRender() {\n return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical\n }\n\n get reloadReason() {\n if (!this.newSnapshot.isVisitable) {\n return {\n reason: \"turbo_visit_control_is_reload\"\n }\n }\n\n if (!this.trackedElementsAreIdentical) {\n return {\n reason: \"tracked_element_mismatch\"\n }\n }\n }\n\n async prepareToRender() {\n this.#setLanguage();\n await this.mergeHead();\n }\n\n async render() {\n if (this.willRender) {\n await this.replaceBody();\n }\n }\n\n finishRendering() {\n super.finishRendering();\n if (!this.isPreview) {\n this.focusFirstAutofocusableElement();\n }\n }\n\n get currentHeadSnapshot() {\n return this.currentSnapshot.headSnapshot\n }\n\n get newHeadSnapshot() {\n return this.newSnapshot.headSnapshot\n }\n\n get newElement() {\n return this.newSnapshot.element\n }\n\n #setLanguage() {\n const { documentElement } = this.currentSnapshot;\n const { dir, lang } = this.newSnapshot;\n\n if (lang) {\n documentElement.setAttribute(\"lang\", lang);\n } else {\n documentElement.removeAttribute(\"lang\");\n }\n if (dir) {\n documentElement.setAttribute(\"dir\", dir);\n } else {\n documentElement.removeAttribute(\"dir\");\n }\n }\n\n async mergeHead() {\n const mergedHeadElements = this.mergeProvisionalElements();\n const newStylesheetElements = this.copyNewHeadStylesheetElements();\n this.copyNewHeadScriptElements();\n\n await mergedHeadElements;\n await newStylesheetElements;\n\n if (this.willRender) {\n this.removeUnusedDynamicStylesheetElements();\n }\n }\n\n async replaceBody() {\n await this.preservingPermanentElements(async () => {\n this.activateNewBody();\n await this.assignNewBody();\n });\n }\n\n get trackedElementsAreIdentical() {\n return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature\n }\n\n async copyNewHeadStylesheetElements() {\n const loadingElements = [];\n\n for (const element of this.newHeadStylesheetElements) {\n loadingElements.push(waitForLoad(element));\n\n document.head.appendChild(element);\n }\n\n await Promise.all(loadingElements);\n }\n\n copyNewHeadScriptElements() {\n for (const element of this.newHeadScriptElements) {\n document.head.appendChild(activateScriptElement(element));\n }\n }\n\n removeUnusedDynamicStylesheetElements() {\n for (const element of this.unusedDynamicStylesheetElements) {\n document.head.removeChild(element);\n }\n }\n\n async mergeProvisionalElements() {\n const newHeadElements = [...this.newHeadProvisionalElements];\n\n for (const element of this.currentHeadProvisionalElements) {\n if (!this.isCurrentElementInElementList(element, newHeadElements)) {\n document.head.removeChild(element);\n }\n }\n\n for (const element of newHeadElements) {\n document.head.appendChild(element);\n }\n }\n\n isCurrentElementInElementList(element, elementList) {\n for (const [index, newElement] of elementList.entries()) {\n // if title element...\n if (element.tagName == \"TITLE\") {\n if (newElement.tagName != \"TITLE\") {\n continue\n }\n if (element.innerHTML == newElement.innerHTML) {\n elementList.splice(index, 1);\n return true\n }\n }\n\n // if any other element...\n if (newElement.isEqualNode(element)) {\n elementList.splice(index, 1);\n return true\n }\n }\n\n return false\n }\n\n removeCurrentHeadProvisionalElements() {\n for (const element of this.currentHeadProvisionalElements) {\n document.head.removeChild(element);\n }\n }\n\n copyNewHeadProvisionalElements() {\n for (const element of this.newHeadProvisionalElements) {\n document.head.appendChild(element);\n }\n }\n\n activateNewBody() {\n document.adoptNode(this.newElement);\n this.removeNoscriptElements();\n this.activateNewBodyScriptElements();\n }\n\n removeNoscriptElements() {\n for (const noscriptElement of this.newElement.querySelectorAll(\"noscript\")) {\n noscriptElement.remove();\n }\n }\n\n activateNewBodyScriptElements() {\n for (const inertScriptElement of this.newBodyScriptElements) {\n const activatedScriptElement = activateScriptElement(inertScriptElement);\n inertScriptElement.replaceWith(activatedScriptElement);\n }\n }\n\n async assignNewBody() {\n await this.renderElement(this.currentElement, this.newElement);\n }\n\n get unusedDynamicStylesheetElements() {\n return this.oldHeadStylesheetElements.filter((element) => {\n return element.getAttribute(\"data-turbo-track\") === \"dynamic\"\n })\n }\n\n get oldHeadStylesheetElements() {\n return this.currentHeadSnapshot.getStylesheetElementsNotInSnapshot(this.newHeadSnapshot)\n }\n\n get newHeadStylesheetElements() {\n return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot)\n }\n\n get newHeadScriptElements() {\n return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot)\n }\n\n get currentHeadProvisionalElements() {\n return this.currentHeadSnapshot.provisionalElements\n }\n\n get newHeadProvisionalElements() {\n return this.newHeadSnapshot.provisionalElements\n }\n\n get newBodyScriptElements() {\n return this.newElement.querySelectorAll(\"script\")\n }\n}\n\nclass MorphingPageRenderer extends PageRenderer {\n static renderElement(currentElement, newElement) {\n morphElements(currentElement, newElement, {\n callbacks: {\n beforeNodeMorphed: (node, newNode) => {\n if (\n shouldRefreshFrameWithMorphing(node, newNode) &&\n !closestFrameReloadableWithMorphing(node)\n ) {\n node.reload();\n return false\n }\n return true\n }\n }\n });\n\n dispatch(\"turbo:morph\", { detail: { currentElement, newElement } });\n }\n\n async preservingPermanentElements(callback) {\n return await callback()\n }\n\n get renderMethod() {\n return \"morph\"\n }\n\n get shouldAutofocus() {\n return false\n }\n}\n\nclass SnapshotCache extends LRUCache {\n constructor(size) {\n super(size, toCacheKey);\n }\n\n get snapshots() {\n return this.entries\n }\n}\n\nclass PageView extends View {\n snapshotCache = new SnapshotCache(10)\n lastRenderedLocation = new URL(location.href)\n forceReloaded = false\n\n shouldTransitionTo(newSnapshot) {\n return this.snapshot.prefersViewTransitions && newSnapshot.prefersViewTransitions\n }\n\n renderPage(snapshot, isPreview = false, willRender = true, visit) {\n const shouldMorphPage = this.isPageRefresh(visit) && (visit?.refresh?.method || this.snapshot.refreshMethod) === \"morph\";\n const rendererClass = shouldMorphPage ? MorphingPageRenderer : PageRenderer;\n\n const renderer = new rendererClass(this.snapshot, snapshot, isPreview, willRender);\n\n if (!renderer.shouldRender) {\n this.forceReloaded = true;\n } else {\n visit?.changeHistory();\n }\n\n return this.render(renderer)\n }\n\n renderError(snapshot, visit) {\n visit?.changeHistory();\n const renderer = new ErrorRenderer(this.snapshot, snapshot, false);\n return this.render(renderer)\n }\n\n clearSnapshotCache() {\n this.snapshotCache.clear();\n }\n\n async cacheSnapshot(snapshot = this.snapshot) {\n if (snapshot.isCacheable) {\n this.delegate.viewWillCacheSnapshot();\n const { lastRenderedLocation: location } = this;\n await nextEventLoopTick();\n const cachedSnapshot = snapshot.clone();\n this.snapshotCache.put(location, cachedSnapshot);\n return cachedSnapshot\n }\n }\n\n getCachedSnapshotForLocation(location) {\n return this.snapshotCache.get(location)\n }\n\n isPageRefresh(visit) {\n return !visit || (this.lastRenderedLocation.pathname === visit.location.pathname && visit.action === \"replace\")\n }\n\n shouldPreserveScrollPosition(visit) {\n return this.isPageRefresh(visit) && (visit?.refresh?.scroll || this.snapshot.refreshScroll) === \"preserve\"\n }\n\n get snapshot() {\n return PageSnapshot.fromElement(this.element)\n }\n}\n\nclass Preloader {\n selector = \"a[data-turbo-preload]\"\n\n constructor(delegate, snapshotCache) {\n this.delegate = delegate;\n this.snapshotCache = snapshotCache;\n }\n\n start() {\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", this.#preloadAll);\n } else {\n this.preloadOnLoadLinksForView(document.body);\n }\n }\n\n stop() {\n document.removeEventListener(\"DOMContentLoaded\", this.#preloadAll);\n }\n\n preloadOnLoadLinksForView(element) {\n for (const link of element.querySelectorAll(this.selector)) {\n if (this.delegate.shouldPreloadLink(link)) {\n this.preloadURL(link);\n }\n }\n }\n\n async preloadURL(link) {\n const location = new URL(link.href);\n\n if (this.snapshotCache.has(location)) {\n return\n }\n\n const fetchRequest = new FetchRequest(this, FetchMethod.get, location, new URLSearchParams(), link);\n await fetchRequest.perform();\n }\n\n // Fetch request delegate\n\n prepareRequest(fetchRequest) {\n fetchRequest.headers[\"X-Sec-Purpose\"] = \"prefetch\";\n }\n\n async requestSucceededWithResponse(fetchRequest, fetchResponse) {\n try {\n const responseHTML = await fetchResponse.responseHTML;\n const snapshot = PageSnapshot.fromHTMLString(responseHTML);\n\n this.snapshotCache.put(fetchRequest.url, snapshot);\n } catch (_) {\n // If we cannot preload that is ok!\n }\n }\n\n requestStarted(fetchRequest) {}\n\n requestErrored(fetchRequest) {}\n\n requestFinished(fetchRequest) {}\n\n requestPreventedHandlingResponse(fetchRequest, fetchResponse) {}\n\n requestFailedWithResponse(fetchRequest, fetchResponse) {}\n\n #preloadAll = () => {\n this.preloadOnLoadLinksForView(document.body);\n }\n}\n\nclass Cache {\n constructor(session) {\n this.session = session;\n }\n\n clear() {\n this.session.clearCache();\n }\n\n resetCacheControl() {\n this.#setCacheControl(\"\");\n }\n\n exemptPageFromCache() {\n this.#setCacheControl(\"no-cache\");\n }\n\n exemptPageFromPreview() {\n this.#setCacheControl(\"no-preview\");\n }\n\n #setCacheControl(value) {\n setMetaContent(\"turbo-cache-control\", value);\n }\n}\n\nclass Session {\n navigator = new Navigator(this)\n history = new History(this)\n view = new PageView(this, document.documentElement)\n adapter = new BrowserAdapter(this)\n\n pageObserver = new PageObserver(this)\n cacheObserver = new CacheObserver()\n linkPrefetchObserver = new LinkPrefetchObserver(this, document)\n linkClickObserver = new LinkClickObserver(this, window)\n formSubmitObserver = new FormSubmitObserver(this, document)\n scrollObserver = new ScrollObserver(this)\n streamObserver = new StreamObserver(this)\n formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement)\n frameRedirector = new FrameRedirector(this, document.documentElement)\n streamMessageRenderer = new StreamMessageRenderer()\n cache = new Cache(this)\n\n enabled = true\n started = false\n #pageRefreshDebouncePeriod = 150\n\n constructor(recentRequests) {\n this.recentRequests = recentRequests;\n this.preloader = new Preloader(this, this.view.snapshotCache);\n this.debouncedRefresh = this.refresh;\n this.pageRefreshDebouncePeriod = this.pageRefreshDebouncePeriod;\n }\n\n start() {\n if (!this.started) {\n this.pageObserver.start();\n this.cacheObserver.start();\n this.linkPrefetchObserver.start();\n this.formLinkClickObserver.start();\n this.linkClickObserver.start();\n this.formSubmitObserver.start();\n this.scrollObserver.start();\n this.streamObserver.start();\n this.frameRedirector.start();\n this.history.start();\n this.preloader.start();\n this.started = true;\n this.enabled = true;\n }\n }\n\n disable() {\n this.enabled = false;\n }\n\n stop() {\n if (this.started) {\n this.pageObserver.stop();\n this.cacheObserver.stop();\n this.linkPrefetchObserver.stop();\n this.formLinkClickObserver.stop();\n this.linkClickObserver.stop();\n this.formSubmitObserver.stop();\n this.scrollObserver.stop();\n this.streamObserver.stop();\n this.frameRedirector.stop();\n this.history.stop();\n this.preloader.stop();\n this.started = false;\n }\n }\n\n registerAdapter(adapter) {\n this.adapter = adapter;\n }\n\n visit(location, options = {}) {\n const frameElement = options.frame ? document.getElementById(options.frame) : null;\n\n if (frameElement instanceof FrameElement) {\n const action = options.action || getVisitAction(frameElement);\n\n frameElement.delegate.proposeVisitIfNavigatedWithAction(frameElement, action);\n frameElement.src = location.toString();\n } else {\n this.navigator.proposeVisit(expandURL(location), options);\n }\n }\n\n refresh(url, options = {}) {\n options = typeof options === \"string\" ? { requestId: options } : options;\n\n const { method, requestId, scroll } = options;\n const isRecentRequest = requestId && this.recentRequests.has(requestId);\n const isCurrentUrl = url === document.baseURI;\n if (!isRecentRequest && !this.navigator.currentVisit && isCurrentUrl) {\n this.visit(url, { action: \"replace\", shouldCacheSnapshot: false, refresh: { method, scroll } });\n }\n }\n\n connectStreamSource(source) {\n this.streamObserver.connectStreamSource(source);\n }\n\n disconnectStreamSource(source) {\n this.streamObserver.disconnectStreamSource(source);\n }\n\n renderStreamMessage(message) {\n this.streamMessageRenderer.render(StreamMessage.wrap(message));\n }\n\n clearCache() {\n this.view.clearSnapshotCache();\n }\n\n setProgressBarDelay(delay) {\n console.warn(\n \"Please replace `session.setProgressBarDelay(delay)` with `session.progressBarDelay = delay`. The function is deprecated and will be removed in a future version of Turbo.`\"\n );\n\n this.progressBarDelay = delay;\n }\n\n set progressBarDelay(delay) {\n config.drive.progressBarDelay = delay;\n }\n\n get progressBarDelay() {\n return config.drive.progressBarDelay\n }\n\n set drive(value) {\n config.drive.enabled = value;\n }\n\n get drive() {\n return config.drive.enabled\n }\n\n set formMode(value) {\n config.forms.mode = value;\n }\n\n get formMode() {\n return config.forms.mode\n }\n\n get location() {\n return this.history.location\n }\n\n get restorationIdentifier() {\n return this.history.restorationIdentifier\n }\n\n get pageRefreshDebouncePeriod() {\n return this.#pageRefreshDebouncePeriod\n }\n\n set pageRefreshDebouncePeriod(value) {\n this.refresh = debounce(this.debouncedRefresh.bind(this), value);\n this.#pageRefreshDebouncePeriod = value;\n }\n\n // Preloader delegate\n\n shouldPreloadLink(element) {\n const isUnsafe = element.hasAttribute(\"data-turbo-method\");\n const isStream = element.hasAttribute(\"data-turbo-stream\");\n const frameTarget = element.getAttribute(\"data-turbo-frame\");\n const frame = frameTarget == \"_top\" ?\n null :\n document.getElementById(frameTarget) || findClosestRecursively(element, \"turbo-frame:not([disabled])\");\n\n if (isUnsafe || isStream || frame instanceof FrameElement) {\n return false\n } else {\n const location = new URL(element.href);\n\n return this.elementIsNavigatable(element) && locationIsVisitable(location, this.snapshot.rootLocation)\n }\n }\n\n // History delegate\n\n historyPoppedToLocationWithRestorationIdentifierAndDirection(location, restorationIdentifier, direction) {\n if (this.enabled) {\n this.navigator.startVisit(location, restorationIdentifier, {\n action: \"restore\",\n historyChanged: true,\n direction\n });\n } else {\n this.adapter.pageInvalidated({\n reason: \"turbo_disabled\"\n });\n }\n }\n\n historyPoppedWithEmptyState(location) {\n this.history.replace(location);\n this.view.lastRenderedLocation = location;\n this.view.cacheSnapshot();\n }\n\n // Scroll observer delegate\n\n scrollPositionChanged(position) {\n this.history.updateRestorationData({ scrollPosition: position });\n }\n\n // Form click observer delegate\n\n willSubmitFormLinkToLocation(link, location) {\n return this.elementIsNavigatable(link) && locationIsVisitable(location, this.snapshot.rootLocation)\n }\n\n submittedFormLinkToLocation() {}\n\n // Link hover observer delegate\n\n canPrefetchRequestToLocation(link, location) {\n return (\n this.elementIsNavigatable(link) &&\n locationIsVisitable(location, this.snapshot.rootLocation) &&\n this.navigator.linkPrefetchingIsEnabledForLocation(location)\n )\n }\n\n // Link click observer delegate\n\n willFollowLinkToLocation(link, location, event) {\n return (\n this.elementIsNavigatable(link) &&\n locationIsVisitable(location, this.snapshot.rootLocation) &&\n this.applicationAllowsFollowingLinkToLocation(link, location, event)\n )\n }\n\n followedLinkToLocation(link, location) {\n const action = this.getActionForLink(link);\n const acceptsStreamResponse = link.hasAttribute(\"data-turbo-stream\");\n\n this.visit(location.href, { action, acceptsStreamResponse });\n }\n\n // Navigator delegate\n\n allowsVisitingLocationWithAction(location, action) {\n return this.applicationAllowsVisitingLocation(location)\n }\n\n visitProposedToLocation(location, options) {\n extendURLWithDeprecatedProperties(location);\n this.adapter.visitProposedToLocation(location, options);\n }\n\n // Visit delegate\n\n visitStarted(visit) {\n if (!visit.acceptsStreamResponse) {\n markAsBusy(document.documentElement);\n this.view.markVisitDirection(visit.direction);\n }\n extendURLWithDeprecatedProperties(visit.location);\n this.notifyApplicationAfterVisitingLocation(visit.location, visit.action);\n }\n\n visitCompleted(visit) {\n this.view.unmarkVisitDirection();\n clearBusyState(document.documentElement);\n this.notifyApplicationAfterPageLoad(visit.getTimingMetrics());\n }\n\n // Form submit observer delegate\n\n willSubmitForm(form, submitter) {\n const action = getAction$1(form, submitter);\n\n return (\n this.submissionIsNavigatable(form, submitter) &&\n locationIsVisitable(expandURL(action), this.snapshot.rootLocation)\n )\n }\n\n formSubmitted(form, submitter) {\n this.navigator.submitForm(form, submitter);\n }\n\n // Page observer delegate\n\n pageBecameInteractive() {\n this.view.lastRenderedLocation = this.location;\n this.notifyApplicationAfterPageLoad();\n }\n\n pageLoaded() {\n this.history.assumeControlOfScrollRestoration();\n }\n\n pageWillUnload() {\n this.history.relinquishControlOfScrollRestoration();\n }\n\n // Stream observer delegate\n\n receivedMessageFromStream(message) {\n this.renderStreamMessage(message);\n }\n\n // Page view delegate\n\n viewWillCacheSnapshot() {\n this.notifyApplicationBeforeCachingSnapshot();\n }\n\n allowsImmediateRender({ element }, options) {\n const event = this.notifyApplicationBeforeRender(element, options);\n const {\n defaultPrevented,\n detail: { render }\n } = event;\n\n if (this.view.renderer && render) {\n this.view.renderer.renderElement = render;\n }\n\n return !defaultPrevented\n }\n\n viewRenderedSnapshot(_snapshot, _isPreview, renderMethod) {\n this.view.lastRenderedLocation = this.history.location;\n this.notifyApplicationAfterRender(renderMethod);\n }\n\n preloadOnLoadLinksForView(element) {\n this.preloader.preloadOnLoadLinksForView(element);\n }\n\n viewInvalidated(reason) {\n this.adapter.pageInvalidated(reason);\n }\n\n // Frame element\n\n frameLoaded(frame) {\n this.notifyApplicationAfterFrameLoad(frame);\n }\n\n frameRendered(fetchResponse, frame) {\n this.notifyApplicationAfterFrameRender(fetchResponse, frame);\n }\n\n // Application events\n\n applicationAllowsFollowingLinkToLocation(link, location, ev) {\n const event = this.notifyApplicationAfterClickingLinkToLocation(link, location, ev);\n return !event.defaultPrevented\n }\n\n applicationAllowsVisitingLocation(location) {\n const event = this.notifyApplicationBeforeVisitingLocation(location);\n return !event.defaultPrevented\n }\n\n notifyApplicationAfterClickingLinkToLocation(link, location, event) {\n return dispatch(\"turbo:click\", {\n target: link,\n detail: { url: location.href, originalEvent: event },\n cancelable: true\n })\n }\n\n notifyApplicationBeforeVisitingLocation(location) {\n return dispatch(\"turbo:before-visit\", {\n detail: { url: location.href },\n cancelable: true\n })\n }\n\n notifyApplicationAfterVisitingLocation(location, action) {\n return dispatch(\"turbo:visit\", { detail: { url: location.href, action } })\n }\n\n notifyApplicationBeforeCachingSnapshot() {\n return dispatch(\"turbo:before-cache\")\n }\n\n notifyApplicationBeforeRender(newBody, options) {\n return dispatch(\"turbo:before-render\", {\n detail: { newBody, ...options },\n cancelable: true\n })\n }\n\n notifyApplicationAfterRender(renderMethod) {\n return dispatch(\"turbo:render\", { detail: { renderMethod } })\n }\n\n notifyApplicationAfterPageLoad(timing = {}) {\n return dispatch(\"turbo:load\", {\n detail: { url: this.location.href, timing }\n })\n }\n\n notifyApplicationAfterFrameLoad(frame) {\n return dispatch(\"turbo:frame-load\", { target: frame })\n }\n\n notifyApplicationAfterFrameRender(fetchResponse, frame) {\n return dispatch(\"turbo:frame-render\", {\n detail: { fetchResponse },\n target: frame,\n cancelable: true\n })\n }\n\n // Helpers\n\n submissionIsNavigatable(form, submitter) {\n if (config.forms.mode == \"off\") {\n return false\n } else {\n const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true;\n\n if (config.forms.mode == \"optin\") {\n return submitterIsNavigatable && form.closest('[data-turbo=\"true\"]') != null\n } else {\n return submitterIsNavigatable && this.elementIsNavigatable(form)\n }\n }\n }\n\n elementIsNavigatable(element) {\n const container = findClosestRecursively(element, \"[data-turbo]\");\n const withinFrame = findClosestRecursively(element, \"turbo-frame\");\n\n // Check if Drive is enabled on the session or we're within a Frame.\n if (config.drive.enabled || withinFrame) {\n // Element is navigatable by default, unless `data-turbo=\"false\"`.\n if (container) {\n return container.getAttribute(\"data-turbo\") != \"false\"\n } else {\n return true\n }\n } else {\n // Element isn't navigatable by default, unless `data-turbo=\"true\"`.\n if (container) {\n return container.getAttribute(\"data-turbo\") == \"true\"\n } else {\n return false\n }\n }\n }\n\n // Private\n\n getActionForLink(link) {\n return getVisitAction(link) || \"advance\"\n }\n\n get snapshot() {\n return this.view.snapshot\n }\n}\n\n// Older versions of the Turbo Native adapters referenced the\n// `Location#absoluteURL` property in their implementations of\n// the `Adapter#visitProposedToLocation()` and `#visitStarted()`\n// methods. The Location class has since been removed in favor\n// of the DOM URL API, and accordingly all Adapter methods now\n// receive URL objects.\n//\n// We alias #absoluteURL to #toString() here to avoid crashing\n// older adapters which do not expect URL objects. We should\n// consider removing this support at some point in the future.\n\nfunction extendURLWithDeprecatedProperties(url) {\n Object.defineProperties(url, deprecatedLocationPropertyDescriptors);\n}\n\nconst deprecatedLocationPropertyDescriptors = {\n absoluteURL: {\n get() {\n return this.toString()\n }\n }\n};\n\nconst session = new Session(recentRequests);\nconst { cache, navigator } = session;\n\n/**\n * Starts the main session.\n * This initialises any necessary observers such as those to monitor\n * link interactions.\n */\nfunction start() {\n session.start();\n}\n\n/**\n * Registers an adapter for the main session.\n *\n * @param adapter Adapter to register\n */\nfunction registerAdapter(adapter) {\n session.registerAdapter(adapter);\n}\n\n/**\n * Performs an application visit to the given location.\n *\n * @param location Location to visit (a URL or path)\n * @param options Options to apply\n * @param options.action Type of history navigation to apply (\"restore\",\n * \"replace\" or \"advance\")\n * @param options.historyChanged Specifies whether the browser history has\n * already been changed for this visit or not\n * @param options.referrer Specifies the referrer of this visit such that\n * navigations to the same page will not result in a new history entry.\n * @param options.snapshotHTML Cached snapshot to render\n * @param options.response Response of the specified location\n */\nfunction visit(location, options) {\n session.visit(location, options);\n}\n\n/**\n * Connects a stream source to the main session.\n *\n * @param source Stream source to connect\n */\nfunction connectStreamSource(source) {\n session.connectStreamSource(source);\n}\n\n/**\n * Disconnects a stream source from the main session.\n *\n * @param source Stream source to disconnect\n */\nfunction disconnectStreamSource(source) {\n session.disconnectStreamSource(source);\n}\n\n/**\n * Renders a stream message to the main session by appending it to the\n * current document.\n *\n * @param message Message to render\n */\nfunction renderStreamMessage(message) {\n session.renderStreamMessage(message);\n}\n\n/**\n * Sets the delay after which the progress bar will appear during navigation.\n *\n * The progress bar appears after 500ms by default.\n *\n * Note that this method has no effect when used with the iOS or Android\n * adapters.\n *\n * @param delay Time to delay in milliseconds\n */\nfunction setProgressBarDelay(delay) {\n console.warn(\n \"Please replace `Turbo.setProgressBarDelay(delay)` with `Turbo.config.drive.progressBarDelay = delay`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n config.drive.progressBarDelay = delay;\n}\n\nfunction setConfirmMethod(confirmMethod) {\n console.warn(\n \"Please replace `Turbo.setConfirmMethod(confirmMethod)` with `Turbo.config.forms.confirm = confirmMethod`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n config.forms.confirm = confirmMethod;\n}\n\nfunction setFormMode(mode) {\n console.warn(\n \"Please replace `Turbo.setFormMode(mode)` with `Turbo.config.forms.mode = mode`. The top-level function is deprecated and will be removed in a future version of Turbo.`\"\n );\n config.forms.mode = mode;\n}\n\n/**\n * Morph the state of the currentBody based on the attributes and contents of\n * the newBody. Morphing body elements may dispatch turbo:morph,\n * turbo:before-morph-element, turbo:before-morph-attribute, and\n * turbo:morph-element events.\n *\n * @param currentBody HTMLBodyElement destination of morphing changes\n * @param newBody HTMLBodyElement source of morphing changes\n */\nfunction morphBodyElements(currentBody, newBody) {\n MorphingPageRenderer.renderElement(currentBody, newBody);\n}\n\n/**\n * Morph the child elements of the currentFrame based on the child elements of\n * the newFrame. Morphing turbo-frame elements may dispatch turbo:before-frame-morph,\n * turbo:before-morph-element, turbo:before-morph-attribute, and\n * turbo:morph-element events.\n *\n * @param currentFrame FrameElement destination of morphing children changes\n * @param newFrame FrameElement source of morphing children changes\n */\nfunction morphTurboFrameElements(currentFrame, newFrame) {\n MorphingFrameRenderer.renderElement(currentFrame, newFrame);\n}\n\nvar Turbo = /*#__PURE__*/Object.freeze({\n __proto__: null,\n navigator: navigator,\n session: session,\n cache: cache,\n PageRenderer: PageRenderer,\n PageSnapshot: PageSnapshot,\n FrameRenderer: FrameRenderer,\n fetch: fetchWithTurboHeaders,\n config: config,\n start: start,\n registerAdapter: registerAdapter,\n visit: visit,\n connectStreamSource: connectStreamSource,\n disconnectStreamSource: disconnectStreamSource,\n renderStreamMessage: renderStreamMessage,\n setProgressBarDelay: setProgressBarDelay,\n setConfirmMethod: setConfirmMethod,\n setFormMode: setFormMode,\n morphBodyElements: morphBodyElements,\n morphTurboFrameElements: morphTurboFrameElements,\n morphChildren: morphChildren,\n morphElements: morphElements\n});\n\nclass TurboFrameMissingError extends Error {}\n\nclass FrameController {\n fetchResponseLoaded = (_fetchResponse) => Promise.resolve()\n #currentFetchRequest = null\n #resolveVisitPromise = () => {}\n #connected = false\n #hasBeenLoaded = false\n #ignoredAttributes = new Set()\n #shouldMorphFrame = false\n action = null\n\n constructor(element) {\n this.element = element;\n this.view = new FrameView(this, this.element);\n this.appearanceObserver = new AppearanceObserver(this, this.element);\n this.formLinkClickObserver = new FormLinkClickObserver(this, this.element);\n this.linkInterceptor = new LinkInterceptor(this, this.element);\n this.restorationIdentifier = uuid();\n this.formSubmitObserver = new FormSubmitObserver(this, this.element);\n }\n\n // Frame delegate\n\n connect() {\n if (!this.#connected) {\n this.#connected = true;\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n } else {\n this.#loadSourceURL();\n }\n this.formLinkClickObserver.start();\n this.linkInterceptor.start();\n this.formSubmitObserver.start();\n }\n }\n\n disconnect() {\n if (this.#connected) {\n this.#connected = false;\n this.appearanceObserver.stop();\n this.formLinkClickObserver.stop();\n this.linkInterceptor.stop();\n this.formSubmitObserver.stop();\n\n if (!this.element.hasAttribute(\"recurse\")) {\n this.#currentFetchRequest?.cancel();\n }\n }\n }\n\n disabledChanged() {\n if (this.disabled) {\n this.#currentFetchRequest?.cancel();\n } else if (this.loadingStyle == FrameLoadingStyle.eager) {\n this.#loadSourceURL();\n }\n }\n\n sourceURLChanged() {\n if (this.#isIgnoringChangesTo(\"src\")) return\n\n if (!this.sourceURL) {\n this.#currentFetchRequest?.cancel();\n }\n\n if (this.element.isConnected) {\n this.complete = false;\n }\n\n if (this.loadingStyle == FrameLoadingStyle.eager || this.#hasBeenLoaded) {\n this.#loadSourceURL();\n }\n }\n\n sourceURLReloaded() {\n const { refresh, src } = this.element;\n\n this.#shouldMorphFrame = src && refresh === \"morph\";\n\n this.element.removeAttribute(\"complete\");\n this.element.src = null;\n this.element.src = src;\n return this.element.loaded\n }\n\n loadingStyleChanged() {\n if (this.loadingStyle == FrameLoadingStyle.lazy) {\n this.appearanceObserver.start();\n } else {\n this.appearanceObserver.stop();\n this.#loadSourceURL();\n }\n }\n\n async #loadSourceURL() {\n if (this.enabled && this.isActive && !this.complete && this.sourceURL) {\n this.element.loaded = this.#visit(expandURL(this.sourceURL));\n this.appearanceObserver.stop();\n await this.element.loaded;\n this.#hasBeenLoaded = true;\n }\n }\n\n async loadResponse(fetchResponse) {\n if (fetchResponse.redirected || (fetchResponse.succeeded && fetchResponse.isHTML)) {\n this.sourceURL = fetchResponse.response.url;\n }\n\n try {\n const html = await fetchResponse.responseHTML;\n if (html) {\n const document = parseHTMLDocument(html);\n const pageSnapshot = PageSnapshot.fromDocument(document);\n\n if (pageSnapshot.isVisitable) {\n await this.#loadFrameResponse(fetchResponse, document);\n } else {\n await this.#handleUnvisitableFrameResponse(fetchResponse);\n }\n }\n } finally {\n this.#shouldMorphFrame = false;\n this.fetchResponseLoaded = () => Promise.resolve();\n }\n }\n\n // Appearance observer delegate\n\n elementAppearedInViewport(element) {\n this.proposeVisitIfNavigatedWithAction(element, getVisitAction(element));\n this.#loadSourceURL();\n }\n\n // Form link click observer delegate\n\n willSubmitFormLinkToLocation(link) {\n return this.#shouldInterceptNavigation(link)\n }\n\n submittedFormLinkToLocation(link, _location, form) {\n const frame = this.#findFrameElement(link);\n if (frame) form.setAttribute(\"data-turbo-frame\", frame.id);\n }\n\n // Link interceptor delegate\n\n shouldInterceptLinkClick(element, _location, _event) {\n return this.#shouldInterceptNavigation(element)\n }\n\n linkClickIntercepted(element, location) {\n this.#navigateFrame(element, location);\n }\n\n // Form submit observer delegate\n\n willSubmitForm(element, submitter) {\n return element.closest(\"turbo-frame\") == this.element && this.#shouldInterceptNavigation(element, submitter)\n }\n\n formSubmitted(element, submitter) {\n if (this.formSubmission) {\n this.formSubmission.stop();\n }\n\n this.formSubmission = new FormSubmission(this, element, submitter);\n\n const { fetchRequest } = this.formSubmission;\n const frame = this.#findFrameElement(element, submitter);\n\n this.prepareRequest(fetchRequest, frame);\n this.formSubmission.start();\n }\n\n // Fetch request delegate\n\n prepareRequest(request, frame = this) {\n request.headers[\"Turbo-Frame\"] = frame.id;\n\n if (this.currentNavigationElement?.hasAttribute(\"data-turbo-stream\")) {\n request.acceptResponseType(StreamMessage.contentType);\n }\n }\n\n requestStarted(_request) {\n markAsBusy(this.element);\n }\n\n requestPreventedHandlingResponse(_request, _response) {\n this.#resolveVisitPromise();\n }\n\n async requestSucceededWithResponse(request, response) {\n await this.loadResponse(response);\n this.#resolveVisitPromise();\n }\n\n async requestFailedWithResponse(request, response) {\n await this.loadResponse(response);\n this.#resolveVisitPromise();\n }\n\n requestErrored(request, error) {\n console.error(error);\n this.#resolveVisitPromise();\n }\n\n requestFinished(_request) {\n clearBusyState(this.element);\n }\n\n // Form submission delegate\n\n formSubmissionStarted({ formElement }) {\n markAsBusy(formElement, this.#findFrameElement(formElement));\n }\n\n formSubmissionSucceededWithResponse(formSubmission, response) {\n const frame = this.#findFrameElement(formSubmission.formElement, formSubmission.submitter);\n\n frame.delegate.proposeVisitIfNavigatedWithAction(frame, getVisitAction(formSubmission.submitter, formSubmission.formElement, frame));\n frame.delegate.loadResponse(response);\n\n if (!formSubmission.isSafe) {\n session.clearCache();\n }\n }\n\n formSubmissionFailedWithResponse(formSubmission, fetchResponse) {\n this.element.delegate.loadResponse(fetchResponse);\n session.clearCache();\n }\n\n formSubmissionErrored(formSubmission, error) {\n console.error(error);\n }\n\n formSubmissionFinished({ formElement }) {\n clearBusyState(formElement, this.#findFrameElement(formElement));\n }\n\n // View delegate\n\n allowsImmediateRender({ element: newFrame }, options) {\n const event = dispatch(\"turbo:before-frame-render\", {\n target: this.element,\n detail: { newFrame, ...options },\n cancelable: true\n });\n\n const {\n defaultPrevented,\n detail: { render }\n } = event;\n\n if (this.view.renderer && render) {\n this.view.renderer.renderElement = render;\n }\n\n return !defaultPrevented\n }\n\n viewRenderedSnapshot(_snapshot, _isPreview, _renderMethod) {}\n\n preloadOnLoadLinksForView(element) {\n session.preloadOnLoadLinksForView(element);\n }\n\n viewInvalidated() {}\n\n // Frame renderer delegate\n\n willRenderFrame(currentElement, _newElement) {\n this.previousFrameElement = currentElement.cloneNode(true);\n }\n\n visitCachedSnapshot = ({ element }) => {\n const frame = element.querySelector(\"#\" + this.element.id);\n\n if (frame && this.previousFrameElement) {\n frame.replaceChildren(...this.previousFrameElement.children);\n }\n\n delete this.previousFrameElement;\n }\n\n // Private\n\n async #loadFrameResponse(fetchResponse, document) {\n const newFrameElement = await this.extractForeignFrameElement(document.body);\n const rendererClass = this.#shouldMorphFrame ? MorphingFrameRenderer : FrameRenderer;\n\n if (newFrameElement) {\n const snapshot = new Snapshot(newFrameElement);\n const renderer = new rendererClass(this, this.view.snapshot, snapshot, false, false);\n if (this.view.renderPromise) await this.view.renderPromise;\n this.changeHistory();\n\n await this.view.render(renderer);\n this.complete = true;\n session.frameRendered(fetchResponse, this.element);\n session.frameLoaded(this.element);\n await this.fetchResponseLoaded(fetchResponse);\n } else if (this.#willHandleFrameMissingFromResponse(fetchResponse)) {\n this.#handleFrameMissingFromResponse(fetchResponse);\n }\n }\n\n async #visit(url) {\n const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams(), this.element);\n\n this.#currentFetchRequest?.cancel();\n this.#currentFetchRequest = request;\n\n return new Promise((resolve) => {\n this.#resolveVisitPromise = () => {\n this.#resolveVisitPromise = () => {};\n this.#currentFetchRequest = null;\n resolve();\n };\n request.perform();\n })\n }\n\n #navigateFrame(element, url, submitter) {\n const frame = this.#findFrameElement(element, submitter);\n\n frame.delegate.proposeVisitIfNavigatedWithAction(frame, getVisitAction(submitter, element, frame));\n\n this.#withCurrentNavigationElement(element, () => {\n frame.src = url;\n });\n }\n\n proposeVisitIfNavigatedWithAction(frame, action = null) {\n this.action = action;\n\n if (this.action) {\n const pageSnapshot = PageSnapshot.fromElement(frame).clone();\n const { visitCachedSnapshot } = frame.delegate;\n\n frame.delegate.fetchResponseLoaded = async (fetchResponse) => {\n if (frame.src) {\n const { statusCode, redirected } = fetchResponse;\n const responseHTML = await fetchResponse.responseHTML;\n const response = { statusCode, redirected, responseHTML };\n const options = {\n response,\n visitCachedSnapshot,\n willRender: false,\n updateHistory: false,\n restorationIdentifier: this.restorationIdentifier,\n snapshot: pageSnapshot\n };\n\n if (this.action) options.action = this.action;\n\n session.visit(frame.src, options);\n }\n };\n }\n }\n\n changeHistory() {\n if (this.action) {\n const method = getHistoryMethodForAction(this.action);\n session.history.update(method, expandURL(this.element.src || \"\"), this.restorationIdentifier);\n }\n }\n\n async #handleUnvisitableFrameResponse(fetchResponse) {\n console.warn(\n `The response (${fetchResponse.statusCode}) from is performing a full page visit due to turbo-visit-control.`\n );\n\n await this.#visitResponse(fetchResponse.response);\n }\n\n #willHandleFrameMissingFromResponse(fetchResponse) {\n this.element.setAttribute(\"complete\", \"\");\n\n const response = fetchResponse.response;\n const visit = async (url, options) => {\n if (url instanceof Response) {\n this.#visitResponse(url);\n } else {\n session.visit(url, options);\n }\n };\n\n const event = dispatch(\"turbo:frame-missing\", {\n target: this.element,\n detail: { response, visit },\n cancelable: true\n });\n\n return !event.defaultPrevented\n }\n\n #handleFrameMissingFromResponse(fetchResponse) {\n this.view.missing();\n this.#throwFrameMissingError(fetchResponse);\n }\n\n #throwFrameMissingError(fetchResponse) {\n const message = `The response (${fetchResponse.statusCode}) did not contain the expected and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;\n throw new TurboFrameMissingError(message)\n }\n\n async #visitResponse(response) {\n const wrapped = new FetchResponse(response);\n const responseHTML = await wrapped.responseHTML;\n const { location, redirected, statusCode } = wrapped;\n\n return session.visit(location, { response: { redirected, statusCode, responseHTML } })\n }\n\n #findFrameElement(element, submitter) {\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n const target = this.#getFrameElementById(id);\n\n return target instanceof FrameElement ? target : this.element\n }\n\n async extractForeignFrameElement(container) {\n let element;\n const id = CSS.escape(this.id);\n\n try {\n element = activateElement(container.querySelector(`turbo-frame#${id}`), this.sourceURL);\n if (element) {\n return element\n }\n\n element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.sourceURL);\n if (element) {\n await element.loaded;\n return await this.extractForeignFrameElement(element)\n }\n } catch (error) {\n console.error(error);\n return new FrameElement()\n }\n\n return null\n }\n\n #formActionIsVisitable(form, submitter) {\n const action = getAction$1(form, submitter);\n\n return locationIsVisitable(expandURL(action), this.rootLocation)\n }\n\n #shouldInterceptNavigation(element, submitter) {\n const id = getAttribute(\"data-turbo-frame\", submitter, element) || this.element.getAttribute(\"target\");\n\n if (element instanceof HTMLFormElement && !this.#formActionIsVisitable(element, submitter)) {\n return false\n }\n\n if (!this.enabled || id == \"_top\") {\n return false\n }\n\n if (id) {\n const frameElement = this.#getFrameElementById(id);\n if (frameElement) {\n return !frameElement.disabled\n } else if (id == \"_parent\") {\n return false\n }\n }\n\n if (!session.elementIsNavigatable(element)) {\n return false\n }\n\n if (submitter && !session.elementIsNavigatable(submitter)) {\n return false\n }\n\n return true\n }\n\n // Computed properties\n\n get id() {\n return this.element.id\n }\n\n get disabled() {\n return this.element.disabled\n }\n\n get enabled() {\n return !this.disabled\n }\n\n get sourceURL() {\n if (this.element.src) {\n return this.element.src\n }\n }\n\n set sourceURL(sourceURL) {\n this.#ignoringChangesToAttribute(\"src\", () => {\n this.element.src = sourceURL ?? null;\n });\n }\n\n get loadingStyle() {\n return this.element.loading\n }\n\n get isLoading() {\n return this.formSubmission !== undefined || this.#resolveVisitPromise() !== undefined\n }\n\n get complete() {\n return this.element.hasAttribute(\"complete\")\n }\n\n set complete(value) {\n if (value) {\n this.element.setAttribute(\"complete\", \"\");\n } else {\n this.element.removeAttribute(\"complete\");\n }\n }\n\n get isActive() {\n return this.element.isActive && this.#connected\n }\n\n get rootLocation() {\n const meta = this.element.ownerDocument.querySelector(`meta[name=\"turbo-root\"]`);\n const root = meta?.content ?? \"/\";\n return expandURL(root)\n }\n\n #isIgnoringChangesTo(attributeName) {\n return this.#ignoredAttributes.has(attributeName)\n }\n\n #ignoringChangesToAttribute(attributeName, callback) {\n this.#ignoredAttributes.add(attributeName);\n callback();\n this.#ignoredAttributes.delete(attributeName);\n }\n\n #withCurrentNavigationElement(element, callback) {\n this.currentNavigationElement = element;\n callback();\n delete this.currentNavigationElement;\n }\n\n #getFrameElementById(id) {\n if (id != null) {\n const element = id === \"_parent\" ?\n this.element.parentElement.closest(\"turbo-frame\") :\n document.getElementById(id);\n if (element instanceof FrameElement) {\n return element\n }\n }\n }\n}\n\nfunction activateElement(element, currentURL) {\n if (element) {\n const src = element.getAttribute(\"src\");\n if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) {\n throw new Error(`Matching element has a source URL which references itself`)\n }\n if (element.ownerDocument !== document) {\n element = document.importNode(element, true);\n }\n\n if (element instanceof FrameElement) {\n element.connectedCallback();\n element.disconnectedCallback();\n return element\n }\n }\n}\n\nconst StreamActions = {\n after() {\n this.removeDuplicateTargetSiblings();\n this.targetElements.forEach((e) => e.parentElement?.insertBefore(this.templateContent, e.nextSibling));\n },\n\n append() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach((e) => e.append(this.templateContent));\n },\n\n before() {\n this.removeDuplicateTargetSiblings();\n this.targetElements.forEach((e) => e.parentElement?.insertBefore(this.templateContent, e));\n },\n\n prepend() {\n this.removeDuplicateTargetChildren();\n this.targetElements.forEach((e) => e.prepend(this.templateContent));\n },\n\n remove() {\n this.targetElements.forEach((e) => e.remove());\n },\n\n replace() {\n const method = this.getAttribute(\"method\");\n\n this.targetElements.forEach((targetElement) => {\n if (method === \"morph\") {\n morphElements(targetElement, this.templateContent);\n } else {\n targetElement.replaceWith(this.templateContent);\n }\n });\n },\n\n update() {\n const method = this.getAttribute(\"method\");\n\n this.targetElements.forEach((targetElement) => {\n if (method === \"morph\") {\n morphChildren(targetElement, this.templateContent);\n } else {\n targetElement.innerHTML = \"\";\n targetElement.append(this.templateContent);\n }\n });\n },\n\n refresh() {\n const method = this.getAttribute(\"method\");\n const requestId = this.requestId;\n const scroll = this.getAttribute(\"scroll\");\n\n session.refresh(this.baseURI, { method, requestId, scroll });\n }\n};\n\n//