Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ const router = createRouter({
path: '/users/:id',
component: () => import('../views/UserIdView.vue'),
},
{
path: '/route-provider/:id',
component: () => import('../views/RouteProviderView.vue'),
},
{
path: '/users-error/:id',
component: () => import('../views/UserIdErrorView.vue'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script setup lang="ts">
import * as Sentry from '@sentry/vue';
import { onMounted, ref } from 'vue';

const route = ref<string>();

onMounted(() => {
route.value = Sentry.resolveCurrentRoute() ?? 'unresolved';
});
</script>

<template>
<div id="resolved-route">{{ route }}</div>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { expect, test } from '@playwright/test';

// The route provider reads the router off the app passed to `Sentry.init`, so this fails if it can't
// find it there.
test('resolves the parameterized route through the route provider', async ({ page }) => {
await page.goto('/route-provider/123');

await expect(page.locator('#resolved-route')).toHaveText('/route-provider/:id');
});
1 change: 1 addition & 0 deletions packages/vue/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export { browserTracingIntegration } from './browserTracingIntegration';
export { attachErrorHandler } from './errorhandler';
export { createTracingMixins } from './tracing';
export { vueIntegration } from './integration';
export { createVueRouteProvider } from './routeProvider';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we should prefix this with _INTERNAL_ as users are not supposed to use this, right? Just Nuxt

export type { VueIntegrationOptions } from './integration';
export { createSentryPiniaPlugin } from './pinia';
44 changes: 44 additions & 0 deletions packages/vue/src/routeProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { RouteProvider } from '@sentry/browser';
import { createUrlRouteProvider } from '@sentry/browser';
import type { Route } from './router';

// Vue Router 3 resolves to `{ route }`, Vue Router 4+ returns the route itself.
type ResolvedLocation = Route | { route: Route };

interface InstalledRouter {
resolve?: (to: string) => ResolvedLocation;
}

interface AppWithRouter {
config?: { globalProperties?: { $router?: InstalledRouter } };
}

/**
* Builds a route provider from a `vue-router` instance, however the SDK got hold of one.
*
* The router is looked up per call rather than captured once, because `app.use(router)` may run
* either side of `Sentry.init()` and only the app itself is guaranteed to exist by then.
*/
export function createVueRouteProvider(getRouter: () => InstalledRouter | undefined): RouteProvider {
return createUrlRouteProvider(url => {
const resolved = getRouter()?.resolve?.(`${url.pathname}${url.search}${url.hash}`);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With createWebHashHistory every URL has pathname / and the route lives in the hash, so e.g. resolve('/#/users/42') matches the shell route and we'd report / for every page. Could we detect hash history off router.options.history and bail to undefined (or resolve from the hash) instead?

see https://router.vuejs.org/api/functions/createWebHashHistory.html

if (!resolved) {
return undefined;
}

const route = 'matched' in resolved ? resolved : resolved.route;

// Always the matched path, never `route.name`. Callers set `url.template` from this, and a route
// name is an identifier rather than a template.
return route.matched[route.matched.length - 1]?.path;
Comment thread
cursor[bot] marked this conversation as resolved.
});
}

/**
* Reads the router `vue-router` installed onto a Vue app.
*/
export function getRouterFromApp(app: unknown): InstalledRouter | undefined {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
export function getRouterFromApp(app: unknown): InstalledRouter | undefined {
export function getRouterFromApp(app: Vue | Vue[] | undefined): InstalledRouter | undefined {

Should we do this maybe?

const firstApp: AppWithRouter | undefined = Array.isArray(app) ? app[0] : (app as AppWithRouter | undefined);

return firstApp?.config?.globalProperties?.$router;
}
4 changes: 4 additions & 0 deletions packages/vue/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@ import { applySdkMetadata, setNormalizeStringifier } from '@sentry/core';
import { vueIntegration } from './integration';
import type { Options } from './types';
import { normalizeStringifyValue } from './normalizeStringifyValue';
import { createVueRouteProvider, getRouterFromApp } from './routeProvider';

/**
* Inits the Vue SDK
*/
export function init(options: Partial<Omit<Options, 'tracingOptions'>> = {}): Client | undefined {
const opts = {
defaultIntegrations: [...getDefaultIntegrations(options), vueIntegration()],
// The router is read off the app on each call, so `app.use(router)` can run either side of `init`, and
// users who never pass `router` to the tracing integration still get parameterized routes.
...(options.app && { routeProvider: createVueRouteProvider(() => getRouterFromApp(options.app)) }),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if someone passes app to vueIntegration? Will/Should they still get the provider?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Vue 2, this would be options.App (make sure to also test Vue 2 E2E)

...options,
};

Expand Down
70 changes: 70 additions & 0 deletions packages/vue/test/routeProvider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';
import { createVueRouteProvider, getRouterFromApp } from '../src/routeProvider';
import type { Route } from '../src/router';

function makeRoute(overrides: Partial<Route> = {}): Route {
return { path: '/users/42', query: {}, params: {}, matched: [{ path: '/users/:id' }], ...overrides };
}

/** Vue Router 4+ returns the route itself. */
const v4Router = (route: Route | undefined) => ({ resolve: () => route as Route });
/** Vue Router 3 wraps it in `{ route }`. */
const v3Router = (route: Route) => ({ resolve: () => ({ route }) });

/** A Vue 3 app with `vue-router` installed, which sets `config.globalProperties.$router`. */
const appWithRouter = (router: unknown) => ({ config: { globalProperties: { $router: router } } });

describe('getRouterFromApp', () => {
it('reads the router vue-router installed on the app', () => {
const router = v4Router(makeRoute());

expect(getRouterFromApp(appWithRouter(router))).toBe(router);
});

it('reads from the first app when several were passed', () => {
const router = v4Router(makeRoute());

expect(getRouterFromApp([appWithRouter(router), appWithRouter(undefined)])).toBe(router);
});

it('returns undefined when no router is installed yet', () => {
expect(getRouterFromApp({ config: { globalProperties: {} } })).toBeUndefined();
expect(getRouterFromApp(undefined)).toBeUndefined();
});
});

describe('createVueRouteProvider', () => {
it('resolves the matched path for Vue Router 4+', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute()));

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('unwraps the `{ route }` shape Vue Router 3 resolves to', () => {
const provider = createVueRouteProvider(() => v3Router(makeRoute()));

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('returns the matched path even for a named route, since a name is not a template', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute({ name: 'UserProfile' })));

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('picks the router up late, since `app.use(router)` may run after `Sentry.init`', () => {
let router: ReturnType<typeof v4Router> | undefined;
const provider = createVueRouteProvider(() => router);

expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBeUndefined();

router = v4Router(makeRoute());
expect(provider.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('returns undefined when nothing matched', () => {
const provider = createVueRouteProvider(() => v4Router(makeRoute({ matched: [] })));

expect(provider.resolveRoute(new URL('https://example.com/nope'))).toBeUndefined();
});
});
Comment thread
cursor[bot] marked this conversation as resolved.
43 changes: 43 additions & 0 deletions packages/vue/test/sdk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as SentryBrowser from '@sentry/browser';
import { getMainCarrier } from '@sentry/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { init } from '../src/sdk';

const browserInit = vi.spyOn(SentryBrowser, 'init');

const DSN = 'https://public@dsn.ingest.sentry.io/1337';

const app = {
config: {
globalProperties: {
$router: { resolve: () => ({ matched: [{ path: '/users/:id' }] }) },
},
},
};

describe('init', () => {
afterEach(() => {
vi.clearAllMocks();
getMainCarrier().__SENTRY__ = undefined;
});

it('passes a route provider that reads the router off the app', () => {
init({ dsn: DSN, app: app as never, defaultIntegrations: false });

const { routeProvider } = browserInit.mock.lastCall![0]!;
expect(routeProvider?.resolveRoute(new URL('https://example.com/users/42'))).toBe('/users/:id');
});

it('does not pass a route provider without an app to read the router from', () => {
init({ dsn: DSN, defaultIntegrations: false });

expect(browserInit).toHaveBeenLastCalledWith(expect.not.objectContaining({ routeProvider: expect.anything() }));
});

it('keeps a route provider passed by the user', () => {
const routeProvider = { resolveRoute: () => '/custom', resolveCurrentRoute: () => '/custom' };
init({ dsn: DSN, app: app as never, defaultIntegrations: false, routeProvider });

expect(browserInit).toHaveBeenLastCalledWith(expect.objectContaining({ routeProvider }));
});
});
Loading