1
1
import type { Location as Location6 , To } from 'react-router-dom' ;
2
+ import * as Sentry from '@sentry/react' ;
2
3
import type { Location as Location3 , LocationDescriptor , Query } from 'history' ;
3
4
import * as qs from 'query-string' ;
4
5
@@ -10,18 +11,61 @@ export function locationDescriptorToTo(path: LocationDescriptor): To {
10
11
return path ;
11
12
}
12
13
14
+ let query = path . query ? { ...path . query } : undefined ;
15
+
13
16
const to : To = {
14
17
pathname : path . pathname ,
15
18
} ;
16
19
20
+ // XXX(epurkhiser): In react router 3 it was possible to include the search
21
+ // query parameters in te pathname field of a LocationDescriptor. You can no
22
+ // longer do this with 6 and it will result in an error
23
+ //
24
+ // > Cannot include a '?' character in a manually specified `to.pathname` field
25
+ //
26
+ // To shim for this, since there may be some hiding around, we can extract
27
+ // out the query string, parse it, and merge it into the path query object.
28
+
29
+ if ( to . pathname ?. endsWith ( '?' ) ) {
30
+ to . pathname = to . pathname . slice ( 0 , - 1 ) ;
31
+ }
32
+
33
+ if ( to . pathname ?. includes ( '?' ) ) {
34
+ const parts = to . pathname . split ( '?' ) ;
35
+
36
+ Sentry . captureMessage ( 'Got pathname with `?`' , scope =>
37
+ scope . setExtra ( 'LocationDescriptor' , path )
38
+ ) ;
39
+
40
+ if ( parts . length > 2 ) {
41
+ Sentry . captureMessage (
42
+ 'Unexpected number of `?` when shimming search params in pathname for react-router 6'
43
+ ) ;
44
+ }
45
+
46
+ const [ pathname , search ] = parts ;
47
+
48
+ if ( search && path . search ) {
49
+ Sentry . captureMessage ( 'Got search in pathname and as part of LocationDescriptor' ) ;
50
+ }
51
+
52
+ to . pathname = pathname ;
53
+
54
+ if ( query ) {
55
+ query = { ...query , ...qs . parse ( search ) } ;
56
+ } else {
57
+ query = qs . parse ( search ) ;
58
+ }
59
+ }
60
+
17
61
if ( path . hash ) {
18
62
to . hash = path . hash ;
19
63
}
20
64
if ( path . search ) {
21
65
to . search = path . search ;
22
66
}
23
- if ( path . query ) {
24
- to . search = `?${ qs . stringify ( path . query ) } ` ;
67
+ if ( query ) {
68
+ to . search = `?${ qs . stringify ( query ) } ` ;
25
69
}
26
70
27
71
// XXX(epurkhiser): We ignore the location state param
0 commit comments