@@ -258,3 +258,54 @@ export function toPathIfFileURL(fileURLOrPath: URL | string): string {
258
258
if ( ! isURL ( fileURLOrPath ) ) return fileURLOrPath ;
259
259
return fileURLToPath ( fileURLOrPath ) ;
260
260
}
261
+
262
+ /**
263
+ * Utility function that converts a URL object into an ordinary options object
264
+ * as expected by the `http.request` and `https.request` APIs.
265
+ * @param {URL } url
266
+ * @returns {Record<string, unknown> }
267
+ */
268
+ export function urlToHttpOptions ( url : URL ) : Record < string , unknown > {
269
+ const { hostname, pathname, port, username, password, search } = url ;
270
+ const options : Record < string , unknown > = {
271
+ __proto__ : null ,
272
+ ...url , // In case the url object was extended by the user.
273
+ protocol : url . protocol ,
274
+ hostname :
275
+ hostname && hostname [ 0 ] === '[' ? hostname . slice ( 1 , - 1 ) : hostname ,
276
+ hash : url . hash ,
277
+ search : search ,
278
+ pathname : pathname ,
279
+ path : `${ pathname || '' } ${ search || '' } ` ,
280
+ href : url . href ,
281
+ } ;
282
+ if ( port !== '' ) {
283
+ options . port = Number ( port ) ;
284
+ }
285
+ if ( username || password ) {
286
+ options . auth = `${ decodeURIComponent ( username ) } :${ decodeURIComponent ( password ) } ` ;
287
+ }
288
+ return options ;
289
+ }
290
+
291
+ // Protocols that can allow "unsafe" and "unwise" chars.
292
+ export const unsafeProtocol = new Set < string > ( [ 'javascript' , 'javascript:' ] ) ;
293
+ // Protocols that never have a hostname.
294
+ export const hostlessProtocol = new Set < string > ( [ 'javascript' , 'javascript:' ] ) ;
295
+ // Protocols that always contain a // bit.
296
+ export const slashedProtocol = new Set < string > ( [
297
+ 'http' ,
298
+ 'http:' ,
299
+ 'https' ,
300
+ 'https:' ,
301
+ 'ftp' ,
302
+ 'ftp:' ,
303
+ 'gopher' ,
304
+ 'gopher:' ,
305
+ 'file' ,
306
+ 'file:' ,
307
+ 'ws' ,
308
+ 'ws:' ,
309
+ 'wss' ,
310
+ 'wss:' ,
311
+ ] ) ;
0 commit comments