import { browserTracingIntegration, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan, WINDOW, } from '@sentry/browser'; import type { Integration, TransactionSource } from '@sentry/core'; import { defineIntegration, hasSpanStreamingEnabled, NAVIGATION_SPAN_NAME_FALLBACK, PAGELOAD_SPAN_NAME_FALLBACK, } from '@sentry/core'; import type { Location } from './types'; import { SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, URL_TEMPLATE, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { NAVIGATION, PAGELOAD } from '@sentry/conventions/op'; // Many of the types below had to be mocked out to prevent typescript issues // these types are required for correct functionality. type HistoryV3 = { location?: Location; listen?(cb: (location: Location) => void): void; // eslint-disable-next-line @typescript-eslint/no-explicit-any } & Record; export type Route = { path?: string; childRoutes?: Route[] }; export type Match = ( props: { location: Location; routes: Route[] }, cb: (error?: Error, _redirectLocation?: Location, renderProps?: { routes?: Route[] }) => void, ) => void; type ReactRouterV3TransactionSource = Extract; interface ReactRouterOptions { history: HistoryV3; routes: Route[]; match: Match; } function _reactRouterV3BrowserTracingIntegration( options: Parameters[0] & ReactRouterOptions, ): Integration { const integration = browserTracingIntegration({ ...options, instrumentPageLoad: false, instrumentNavigation: false, }); const { history, routes, match, instrumentPageLoad = true, instrumentNavigation = true } = options; return { ...integration, afterAllSetup(client) { integration.afterAllSetup(client); if (instrumentPageLoad && WINDOW.location) { normalizeTransactionName( routes, WINDOW.location, match, (localName: string, source: ReactRouterV3TransactionSource = 'url') => { startBrowserTracingPageLoadSpan(client, { // With span streaming, span names have to be low cardinality, so we can't fall back to the URL. name: source === 'route' || !hasSpanStreamingEnabled(client) ? localName : PAGELOAD_SPAN_NAME_FALLBACK, attributes: { [SENTRY_OP]: PAGELOAD, [SENTRY_ORIGIN]: 'auto.pageload.react.reactrouter_v3', [SENTRY_SEGMENT_NAME_SOURCE]: source, ...(source === 'route' && { [URL_TEMPLATE]: localName }), }, }); }, ); } if (instrumentNavigation && history.listen) { history.listen(location => { if (location.action === 'PUSH' || location.action === 'POP') { normalizeTransactionName( routes, location, match, (localName: string, source: TransactionSource = 'url') => { startBrowserTracingNavigationSpan(client, { // With span streaming, span names have to be low cardinality, so we can't fall back to the URL. name: source === 'route' || !hasSpanStreamingEnabled(client) ? localName : NAVIGATION_SPAN_NAME_FALLBACK, attributes: { [SENTRY_OP]: NAVIGATION, [SENTRY_ORIGIN]: 'auto.navigation.react.reactrouter_v3', [SENTRY_SEGMENT_NAME_SOURCE]: source, ...(source === 'route' && { [URL_TEMPLATE]: localName }), }, }); }, ); } }); } }, }; } /** * A browser tracing integration that uses React Router v3 to instrument navigations. * Expects `history` (and optionally `routes` and `matchPath`) to be passed as options. */ export const reactRouterV3BrowserTracingIntegration: typeof _reactRouterV3BrowserTracingIntegration = defineIntegration( _reactRouterV3BrowserTracingIntegration, ); /** * Normalize transaction names using `Router.match` */ function normalizeTransactionName( appRoutes: Route[], location: Location, match: Match, callback: (pathname: string, source?: ReactRouterV3TransactionSource) => void, ): void { let name = location.pathname; match( { location, routes: appRoutes, }, (error, _redirectLocation, renderProps) => { if (error || !renderProps) { return callback(name); } const routePath = getRouteStringFromRoutes(renderProps.routes || []); if (routePath.length === 0 || routePath === '/*') { return callback(name); } name = routePath; return callback(name, 'route'); }, ); } /** * Generate route name from array of routes */ function getRouteStringFromRoutes(routes: Route[]): string { if (!Array.isArray(routes) || routes.length === 0) { return ''; } const routesWithPaths: Route[] = routes.filter((route: Route) => !!route.path); let index = -1; for (let x = routesWithPaths.length - 1; x >= 0; x--) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const route = routesWithPaths[x]!; if (route.path?.startsWith('/')) { index = x; break; } } return routesWithPaths.slice(index).reduce((acc, { path }) => { const pathSegment = acc === '/' || acc === '' ? path : `/${path}`; return `${acc}${pathSegment}`; }, ''); }