UNPKG

@sentry/browser

Version:
366 lines (365 loc) • 16.4 kB
import { DEBUG_BUILD } from "../debug-build.js"; import { WINDOW, getHttpRequestData } from "../helpers.js"; import { webVitalsIntegration } from "../integrations/webVitals.js"; import { registerBackgroundTabDetection } from "./backgroundtab.js"; import { linkedTracesIntegration } from "../integrations/linkedTraces.js"; import { fetchTracingIntegration } from "../integrations/fetchTracing.js"; import { xhrTracingIntegration } from "../integrations/xhrTracing.js"; import { NAVIGATION_SPAN_NAME_FALLBACK, PAGELOAD_SPAN_NAME_FALLBACK, TRACING_DEFAULTS, addNonEnumerableProperty, browserPerformanceTimeOrigin, consoleSandbox, dateTimestampInSeconds, debug, filterCollectedUrl, generateSpanId, generateTraceId, getClient, getCurrentScope, getDynamicSamplingContextFromSpan, hasSpanStreamingEnabled, hasSpansEnabled, isURLObjectRelative, parseStringToURLObject, propagationContextFromHeaders, registerSpanErrorInstrumentation, spanIsSampled, spanToJSON, timestampInSeconds } from "@sentry/core"; import { addHistoryInstrumentationHandler, addPerformanceEntries, getLocationHref, isBotUserAgent, longTasksIntegration, resourcesIntegration } from "@sentry/browser-utils"; import { BROWSER_NAVIGATION_TYPE, SENTRY_IDLE_SPAN_FINISH_REASON, SENTRY_OP, SENTRY_ORIGIN, SENTRY_SEGMENT_NAME_SOURCE, URL_FULL, URL_PATH } from "@sentry/conventions/attributes"; import { _INTERNAL_ensureBrowserSpanStreaming, startIdleSpan, startInactiveSpan } from "@sentry/core/browser"; import { NAVIGATION, NAVIGATION_REDIRECT, PAGELOAD } from "@sentry/conventions/op"; // src/tracing/browserTracingIntegration.ts const BROWSER_TRACING_INTEGRATION_ID = "BrowserTracing"; const DEFAULT_BROWSER_TRACING_OPTIONS = { ...TRACING_DEFAULTS, instrumentNavigation: true, instrumentBfcacheRestore: true, instrumentPageLoad: true, markBackgroundSpan: true, detectRedirects: true, enableReportPageLoaded: false }; /** * Defaults for the options that `browserTracingIntegration` forwards to the integrations it registers. * They are spread rather than destructured, so an explicit `undefined` still overrides them. */ const DEFAULT_FORWARDED_OPTIONS = { enableInp: true, enableLongTask: true, enableLongAnimationFrame: true, traceFetch: true, traceXHR: true, linkPreviousTrace: "in-memory" }; /** * The Browser Tracing integration automatically instruments browser pageload/navigation * actions as transactions, and captures requests, metrics and errors as spans. * * The integration can be configured with a variety of options, and can be extended to use * any routing library. * * We explicitly export the proper type here, as this has to be extended in some cases. */ const browserTracingIntegration = ((options = {}) => { if ("enableElementTiming" in options) consoleSandbox(() => { console.warn("[Sentry] `enableElementTiming` is deprecated and no longer has any effect. Use the standalone `elementTimingIntegration` instead."); }); const { enableInp, webVitals, enableLongTask, enableLongAnimationFrame, ignoreResourceSpans, traceFetch, traceXHR, shouldCreateSpanForRequest, enableHTTPTimings, onRequestSpanStart, onRequestSpanEnd, linkPreviousTrace, consistentTraceSampling } = { ...DEFAULT_FORWARDED_OPTIONS, ...options }; return _browserTracingIntegration(options, (client) => { if (!client.addIntegration) return; const ignore = webVitals?.ignore ?? []; client.addIntegration(webVitalsIntegration({ ...webVitals, ignore: enableInp || ignore.includes("inp") ? ignore : [...ignore, "inp"] })); if (enableLongTask || enableLongAnimationFrame) client.addIntegration(longTasksIntegration({ enableLongTask, enableLongAnimationFrame })); client.addIntegration(resourcesIntegration({ ignoreResourceSpans })); const requestOptions = { shouldCreateSpanForRequest, enableHTTPTimings, onRequestSpanStart, onRequestSpanEnd }; if (traceFetch) client.addIntegration(fetchTracingIntegration(requestOptions)); if (traceXHR) client.addIntegration(xhrTracingIntegration(requestOptions)); if (linkPreviousTrace !== "off") client.addIntegration(linkedTracesIntegration({ storage: linkPreviousTrace, consistentTraceSampling })); }); }); /** * The pageload and navigation spans of `browserTracingIntegration`, without the features it registers as * standalone integrations (such as `webVitalsIntegration`). * * Use it instead of `browserTracingIntegration` to only bundle the integrations you add yourself. */ const browserTracingCoreIntegration = ((options = {}) => _browserTracingIntegration(options)); function _browserTracingIntegration(options, addDefaultIntegrations) { /** * This is just a small wrapper that makes `document` optional. * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up. */ const optionalWindowDocument = WINDOW.document; const { beforeStartSpan, idleTimeout, finalTimeout, childSpanTimeout, markBackgroundSpan, instrumentPageLoad, instrumentNavigation, instrumentBfcacheRestore, detectRedirects, enableReportPageLoaded } = { ...DEFAULT_BROWSER_TRACING_OPTIONS, ...options }; const _isBot = isBotUserAgent(); let lastInteractionTimestamp; let _pageloadSpan; /** Create routing idle transaction. */ function _createRouteSpan(client, startSpanOptions, makeActive = true, url) { const isPageloadSpan = startSpanOptions.op === "pageload"; const initialSpanName = startSpanOptions.name; const finalStartSpanOptions = beforeStartSpan ? beforeStartSpan(startSpanOptions) : startSpanOptions; const urlObject = parseStringToURLObject(url || getLocationHref()); const attributes = { [URL_PATH]: urlObject?.pathname, ...urlObject && !isURLObjectRelative(urlObject) && { [URL_FULL]: filterCollectedUrl(urlObject.href) }, ...finalStartSpanOptions.attributes }; if (initialSpanName !== finalStartSpanOptions.name) attributes[SENTRY_SEGMENT_NAME_SOURCE] = "custom"; finalStartSpanOptions.attributes = attributes; if (!makeActive) { const now = dateTimestampInSeconds(); startInactiveSpan({ ...finalStartSpanOptions, startTime: now }).end(now); return; } const idleSpan = startIdleSpan(finalStartSpanOptions, { idleTimeout, finalTimeout, childSpanTimeout, disableAutoFinish: isPageloadSpan, trimIdleSpanEndTimestamp: !enableReportPageLoaded }); if (isPageloadSpan && enableReportPageLoaded) _pageloadSpan = idleSpan; setActiveIdleSpan(client, idleSpan); function emitFinish() { if (optionalWindowDocument && ["interactive", "complete"].includes(optionalWindowDocument.readyState)) { client.emit("idleSpanEnableAutoFinish", idleSpan); optionalWindowDocument.removeEventListener("readystatechange", emitFinish); } } if (isPageloadSpan && !enableReportPageLoaded && optionalWindowDocument) { optionalWindowDocument.addEventListener("readystatechange", emitFinish); emitFinish(); } } return { name: BROWSER_TRACING_INTEGRATION_ID, setup(client) { if (_isBot) { DEBUG_BUILD && debug.log("[Tracing] Skipping browserTracingIntegration setup for bot user agent."); return; } registerSpanErrorInstrumentation(); if (detectRedirects && optionalWindowDocument) { const interactionHandler = () => { lastInteractionTimestamp = timestampInSeconds(); }; addEventListener("click", interactionHandler, { capture: true }); addEventListener("keydown", interactionHandler, { capture: true, passive: true }); } function maybeEndActiveSpan() { const activeSpan = getActiveIdleSpan(client); if (activeSpan && !spanToJSON(activeSpan).end_timestamp) { DEBUG_BUILD && debug.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).attributes[SENTRY_OP]}`); activeSpan.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, "cancelled"); activeSpan.end(); } } client.on("beforeIdleSpanEnd", (span) => { if (getActiveIdleSpan(client) !== span) return; addPerformanceEntries(span, { spanStreamingEnabled: hasSpanStreamingEnabled(client) }); setActiveIdleSpan(client, void 0); const scope = getCurrentScope(); const oldPropagationContext = scope.getPropagationContext(); scope.setPropagationContext({ ...oldPropagationContext, traceId: span.spanContext().traceId, sampled: spanIsSampled(span), dsc: getDynamicSamplingContextFromSpan(span) }); if (_pageloadSpan === span) _pageloadSpan = void 0; }); client.on("startNavigationSpan", (startSpanOptions, navigationOptions) => { if (getClient() !== client) return; if (navigationOptions?.isRedirect) { DEBUG_BUILD && debug.warn("[Tracing] Detected redirect, navigation span will not be the root span, but a child span."); _createRouteSpan(client, { op: NAVIGATION_REDIRECT, ...startSpanOptions }, false, navigationOptions.url); return; } lastInteractionTimestamp = void 0; maybeEndActiveSpan(); const scope = getCurrentScope(); scope.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random(), propagationSpanId: hasSpansEnabled() ? void 0 : generateSpanId() }); scope.setSDKProcessingMetadata({ normalizedRequest: void 0 }); _createRouteSpan(client, { op: NAVIGATION, ...startSpanOptions, parentSpan: null }, true, navigationOptions?.url); }); client.on("startPageLoadSpan", (startSpanOptions, traceOptions = {}) => { if (getClient() !== client) return; maybeEndActiveSpan(); const sentryTrace = traceOptions.sentryTrace || getMetaContent("sentry-trace") || getServerTiming("sentry-trace"); const baggage = traceOptions.baggage || getMetaContent("baggage") || getServerTiming("baggage"); const propagationContext = propagationContextFromHeaders(sentryTrace, baggage); const scope = getCurrentScope(); scope.setPropagationContext(propagationContext); if (!hasSpansEnabled()) scope.getPropagationContext().propagationSpanId = generateSpanId(); const requestData = getHttpRequestData(client); scope.setSDKProcessingMetadata({ normalizedRequest: { ...requestData, url: filterCollectedUrl(requestData.url, client) } }); _createRouteSpan(client, { op: PAGELOAD, ...startSpanOptions }); }); client.on("endPageloadSpan", () => { if (enableReportPageLoaded && _pageloadSpan) { _pageloadSpan.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, "reportPageLoaded"); _pageloadSpan.end(); } }); WINDOW.addEventListener?.("pagehide", () => { const activeSpan = getActiveIdleSpan(client); if (activeSpan && !spanToJSON(activeSpan).end_timestamp) { activeSpan.setAttribute(SENTRY_IDLE_SPAN_FINISH_REASON, "documentHidden"); activeSpan.end(); } client.flush(); }); }, afterAllSetup(client) { if (_isBot) return; _INTERNAL_ensureBrowserSpanStreaming(client); addDefaultIntegrations?.(client); let startingUrl = getLocationHref(); if (WINDOW.location) { if (instrumentPageLoad) startBrowserTracingPageLoadSpan(client, { name: hasSpanStreamingEnabled(client) ? PAGELOAD_SPAN_NAME_FALLBACK : WINDOW.location.pathname, attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: "url", [SENTRY_ORIGIN]: "auto.pageload.browser" } }); if (instrumentNavigation) addHistoryInstrumentationHandler(({ to, from }) => { /** * This early return is there to account for some cases where a navigation transaction starts right after * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't * create an uneccessary navigation transaction. * * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also * only be caused in certain development environments where the usage of a hot module reloader is causing * errors. */ if (from === void 0 && startingUrl !== void 0 && startingUrl.indexOf(to) !== -1) { startingUrl = void 0; return; } startingUrl = void 0; const parsed = parseStringToURLObject(to); const activeSpan = getActiveIdleSpan(client); const navigationIsRedirect = activeSpan && detectRedirects && isRedirect(activeSpan, lastInteractionTimestamp); startBrowserTracingNavigationSpan(client, { name: hasSpanStreamingEnabled(client) ? NAVIGATION_SPAN_NAME_FALLBACK : parsed?.pathname || WINDOW.location.pathname, attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: "url", [SENTRY_ORIGIN]: "auto.navigation.browser" } }, { url: to, isRedirect: navigationIsRedirect }); }); if (instrumentBfcacheRestore) WINDOW.addEventListener?.("pageshow", (event) => { if (!event.persisted) return; startingUrl = void 0; startBrowserTracingNavigationSpan(client, { name: hasSpanStreamingEnabled(client) ? NAVIGATION_SPAN_NAME_FALLBACK : WINDOW.location?.pathname || "/", attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: "url", [SENTRY_ORIGIN]: "auto.navigation.browser.bfcache", [BROWSER_NAVIGATION_TYPE]: "back-forward-cache" } }, { url: WINDOW.location?.href }); }); } if (markBackgroundSpan) registerBackgroundTabDetection(); } }; } /** * Manually start a page load span. * This will only do something if a browser tracing integration integration has been setup. * * If you provide a custom `traceOptions` object, it will be used to continue the trace * instead of the default behavior, which is to look it up on the <meta> tags. */ function startBrowserTracingPageLoadSpan(client, spanOptions, traceOptions) { const isFallbackSpanName = spanOptions.name === PAGELOAD_SPAN_NAME_FALLBACK; getCurrentScope().setTransactionName(isFallbackSpanName ? WINDOW.location?.pathname : spanOptions.name); const timeOrigin = browserPerformanceTimeOrigin(); const pageloadSpanOptions = { ...spanOptions, startTime: spanOptions.startTime ?? (timeOrigin ? timeOrigin / 1e3 : void 0) }; client.emit("startPageLoadSpan", pageloadSpanOptions, traceOptions); const pageloadSpan = getActiveIdleSpan(client); if (pageloadSpan) client.emit("afterStartPageLoadSpan", pageloadSpan); return pageloadSpan; } /** * Manually start a navigation span. * This will only do something if a browser tracing integration has been setup. */ function startBrowserTracingNavigationSpan(client, spanOptions, options) { const { url, isRedirect } = options || {}; client.emit("beforeStartNavigationSpan", spanOptions, { isRedirect, url }); client.emit("startNavigationSpan", spanOptions, { isRedirect, url }); const scope = getCurrentScope(); const isFallbackSpanName = spanOptions.name === NAVIGATION_SPAN_NAME_FALLBACK; scope.setTransactionName(isFallbackSpanName ? url && parseStringToURLObject(url)?.pathname || WINDOW.location?.pathname : spanOptions.name); if (url && !isRedirect) scope.setSDKProcessingMetadata({ normalizedRequest: { ...getHttpRequestData(client), url: filterCollectedUrl(url, client) } }); return getActiveIdleSpan(client); } /** Returns the value of a meta tag */ function getMetaContent(metaName) { return (WINDOW.document?.querySelector(`meta[name=${metaName}]`))?.getAttribute("content") || void 0; } /** Returns the description of a server timing entry */ function getServerTiming(name) { return ((WINDOW.performance?.getEntriesByType?.("navigation")[0])?.serverTiming?.find((entry) => entry.name === name))?.description; } const ACTIVE_IDLE_SPAN_PROPERTY = "_sentry_idleSpan"; function getActiveIdleSpan(client) { return client[ACTIVE_IDLE_SPAN_PROPERTY]; } function setActiveIdleSpan(client, span) { addNonEnumerableProperty(client, ACTIVE_IDLE_SPAN_PROPERTY, span); } const REDIRECT_THRESHOLD = 1.5; function isRedirect(activeSpan, lastInteractionTimestamp) { const spanData = spanToJSON(activeSpan); const now = dateTimestampInSeconds(); if (now - spanData.start_timestamp > REDIRECT_THRESHOLD) return false; if (lastInteractionTimestamp && now - lastInteractionTimestamp <= REDIRECT_THRESHOLD) return false; return true; } export { BROWSER_TRACING_INTEGRATION_ID, browserTracingCoreIntegration, browserTracingIntegration, getMetaContent, getServerTiming, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan }; //# sourceMappingURL=browserTracingIntegration.js.map