1
1
import { captureException } from '@sentry/browser' ;
2
2
import { Transaction , TransactionContext } from '@sentry/types' ;
3
- import VueRouter from 'vue-router' ;
4
-
5
- export type Action = 'PUSH' | 'REPLACE' | 'POP' ;
6
3
7
4
export type VueRouterInstrumentation = < T extends Transaction > (
8
5
startTransaction : ( context : TransactionContext ) => T | undefined ,
9
6
startTransactionOnPageLoad ?: boolean ,
10
7
startTransactionOnLocationChange ?: boolean ,
11
8
) => void ;
12
9
13
- let firstLoad = true ;
10
+ // This is not great, but kinda necessary to make it work with VueRouter@3 and VueRouter@4 at the same time.
11
+ type Route = {
12
+ params : any ;
13
+ query : any ;
14
+ name : any ;
15
+ path : any ;
16
+ matched : any [ ] ;
17
+ } ;
18
+ interface VueRouter {
19
+ onError : ( fn : ( err : Error ) => void ) => void ;
20
+ beforeEach : ( fn : ( to : Route , from : Route , next : ( ) => void ) => void ) => void ;
21
+ }
14
22
15
23
/**
16
24
* Creates routing instrumentation for Vue Router v2
@@ -25,17 +33,24 @@ export function vueRouterInstrumentation(router: VueRouter): VueRouterInstrument
25
33
) => {
26
34
router . onError ( error => captureException ( error ) ) ;
27
35
28
- const tags = {
29
- 'routing.instrumentation' : 'vue-router' ,
30
- } ;
36
+ router . beforeEach ( ( to , from , next ) => {
37
+ // According to docs we could use `from === VueRouter.START_LOCATION` but I couldnt get it working for Vue 2
38
+ // https://router.vuejs.org/api/#router-start-location
39
+ // https://next.router.vuejs.org/api/#start-location
31
40
32
- router . beforeEach ( ( to , _from , next ) => {
41
+ // Vue2 - null
42
+ // Vue3 - undefined
43
+ const isPageLoadNavigation = from . name == null && from . matched . length === 0 ;
44
+
45
+ const tags = {
46
+ 'routing.instrumentation' : 'vue-router' ,
47
+ } ;
33
48
const data = {
34
49
params : to . params ,
35
50
query : to . query ,
36
51
} ;
37
52
38
- if ( startTransactionOnPageLoad && firstLoad ) {
53
+ if ( startTransactionOnPageLoad && isPageLoadNavigation ) {
39
54
startTransaction ( {
40
55
name : to . name || to . path ,
41
56
op : 'pageload' ,
@@ -44,7 +59,7 @@ export function vueRouterInstrumentation(router: VueRouter): VueRouterInstrument
44
59
} ) ;
45
60
}
46
61
47
- if ( startTransactionOnLocationChange && ! firstLoad ) {
62
+ if ( startTransactionOnLocationChange && ! isPageLoadNavigation ) {
48
63
startTransaction ( {
49
64
name : to . name || to . matched [ 0 ] . path || to . path ,
50
65
op : 'navigation' ,
@@ -53,7 +68,6 @@ export function vueRouterInstrumentation(router: VueRouter): VueRouterInstrument
53
68
} ) ;
54
69
}
55
70
56
- firstLoad = false ;
57
71
next ( ) ;
58
72
} ) ;
59
73
} ;
0 commit comments