import { startSpan } from '@sentry/browser'; import { CODE_FUNCTION_NAME, SENTRY_DESCRIPTION, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { FUNCTION } from '@sentry/conventions/op'; import { getClient, hasSpanStreamingEnabled } from '@sentry/core'; import type Route from '@ember/routing/route'; type RouteConstructor = new (...args: ConstructorParameters) => Route; /** * Enables monitoring the performance of an Ember app. * * This wraps the route's lifecycle hooks (beforeModel, model, afterModel, setupController) * with Sentry spans to track their performance. * * @param BaseRoute - The Route class to instrument * @returns The instrumented Route class * * @example * ```ts * import Route from '@ember/routing/route'; * import { instrumentRoutePerformance } from '@sentry/ember'; * * class ApplicationRoute extends Route { * async model() { * return this.store.findAll('post'); * } * } * * export default instrumentRoutePerformance(ApplicationRoute); * ``` */ export function instrumentRoutePerformance(BaseRoute: T): T { const instrumentFunction = async ( hookName: string, fullRouteName: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Route hooks have varied signatures that can't be unified with unknown fn: (...args: any[]) => any, args: unknown[], ): Promise => { const client = getClient(); const isStreaming = !!client && hasSpanStreamingEnabled(client); return startSpan( { attributes: { [SENTRY_ORIGIN]: 'auto.ui.ember', [SENTRY_OP]: FUNCTION, [CODE_FUNCTION_NAME]: hookName, ...(isStreaming && { [SENTRY_DESCRIPTION]: fullRouteName }), }, name: isStreaming ? hookName : fullRouteName, onlyIfParent: true, }, () => { return fn(...args); }, ); }; const routeName = BaseRoute.name; return { // @ts-expect-error TS2545 We do not need to redefine a constructor here [routeName]: class extends BaseRoute { public beforeModel(...args: unknown[]): void | Promise { return instrumentFunction('beforeModel', this.fullRouteName, super.beforeModel.bind(this), args); } public async model(...args: unknown[]): Promise { return instrumentFunction('model', this.fullRouteName, super.model.bind(this), args); } public afterModel(...args: unknown[]): void | Promise { return instrumentFunction('afterModel', this.fullRouteName, super.afterModel.bind(this), args); } public setupController(...args: unknown[]): void | Promise { return instrumentFunction('setupController', this.fullRouteName, super.setupController.bind(this), args); } }, }[routeName] as T; }