@@ -69,13 +69,17 @@ export interface MultiaddrFromUriOpts {
69
69
export function uriToMultiaddr ( uriStr : string , opts ?: MultiaddrFromUriOpts ) : Multiaddr {
70
70
opts = opts ?? { }
71
71
const defaultDnsType = opts . defaultDnsType ?? 'dns4'
72
- const { scheme, hostname, port } = parseUri ( uriStr )
72
+ const { scheme, hostname, port, path } = parseUri ( uriStr )
73
73
const parts = [
74
74
tupleForHostname ( hostname , defaultDnsType ) ,
75
75
tupleForPort ( port , scheme ) ,
76
76
tupleForScheme ( scheme )
77
77
]
78
78
79
+ if ( path != null ) {
80
+ parts . push ( tupleForPath ( path ) )
81
+ }
82
+
79
83
const multiaddrStr = '/' + parts
80
84
. filter ( x => Boolean ( x ) )
81
85
// @ts -expect-error ts cannot see we filter falsy values
@@ -85,7 +89,7 @@ export function uriToMultiaddr (uriStr: string, opts?: MultiaddrFromUriOpts): Mu
85
89
return multiaddr ( multiaddrStr )
86
90
}
87
91
88
- function parseUri ( uriStr : string ) : { scheme : string , hostname : string , port : string } {
92
+ function parseUri ( uriStr : string ) : { scheme : string , hostname : string , port : string , path ?: string } {
89
93
const [ scheme ] = uriStr . split ( ':' )
90
94
91
95
// browsers will only parse URLs with schemes they understand
@@ -94,7 +98,7 @@ function parseUri (uriStr: string): { scheme: string, hostname: string, port: st
94
98
}
95
99
96
100
// Use the WHATWG URL global, in node >= 10 and the browser
97
- let { protocol, hostname, port } = new URL ( uriStr )
101
+ let { protocol, hostname, port, pathname , search } = new URL ( uriStr )
98
102
99
103
if ( port == null || port === '' ) {
100
104
const protocolPort = portForProtocol ( scheme )
@@ -110,7 +114,22 @@ function parseUri (uriStr: string): { scheme: string, hostname: string, port: st
110
114
}
111
115
}
112
116
113
- return { scheme, hostname, port }
117
+ let path : string | undefined
118
+
119
+ if ( pathname != null && pathname !== '' && pathname !== '/' ) {
120
+ if ( pathname . startsWith ( '/' ) ) {
121
+ pathname = pathname . substring ( 1 )
122
+ }
123
+
124
+ path = pathname
125
+ }
126
+
127
+ if ( search != null && search !== '' ) {
128
+ path = path ?? ''
129
+ path += search
130
+ }
131
+
132
+ return { scheme, hostname, port, path }
114
133
}
115
134
116
135
function tupleForHostname ( hostname : string , defaultDnsType : string ) : [ string , string ] | undefined {
@@ -158,6 +177,14 @@ function tupleForScheme (scheme: string): [string] | undefined {
158
177
return [ scheme ]
159
178
}
160
179
180
+ function tupleForPath ( path : string ) : [ string , string ] | undefined {
181
+ if ( path == null || path === '' ) {
182
+ return undefined
183
+ }
184
+
185
+ return [ 'http-path' , encodeURIComponent ( path ) ]
186
+ }
187
+
161
188
function portForProtocol ( protocol : string ) : string | undefined {
162
189
if ( protocol == null || protocol === '' || portFor [ protocol ] == null ) {
163
190
return undefined
0 commit comments