(urlObj: UrlObject)
| 27 | const slashedProtocols = /https?|ftp|gopher|file/ |
| 28 | |
| 29 | export function formatUrl(urlObj: UrlObject) { |
| 30 | let { auth, hostname } = urlObj |
| 31 | let protocol = urlObj.protocol || '' |
| 32 | let pathname = urlObj.pathname || '' |
| 33 | let hash = urlObj.hash || '' |
| 34 | let query = urlObj.query || '' |
| 35 | let host: string | false = false |
| 36 | |
| 37 | auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : '' |
| 38 | |
| 39 | if (urlObj.host) { |
| 40 | host = auth + urlObj.host |
| 41 | } else if (hostname) { |
| 42 | host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname) |
| 43 | if (urlObj.port) { |
| 44 | host += ':' + urlObj.port |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | if (query && typeof query === 'object') { |
| 49 | query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery)) |
| 50 | } |
| 51 | |
| 52 | let search = urlObj.search || (query && `?${query}`) || '' |
| 53 | |
| 54 | if (protocol && !protocol.endsWith(':')) protocol += ':' |
| 55 | |
| 56 | if ( |
| 57 | urlObj.slashes || |
| 58 | ((!protocol || slashedProtocols.test(protocol)) && host !== false) |
| 59 | ) { |
| 60 | host = '//' + (host || '') |
| 61 | if (pathname && pathname[0] !== '/') pathname = '/' + pathname |
| 62 | } else if (!host) { |
| 63 | host = '' |
| 64 | } |
| 65 | |
| 66 | if (hash && hash[0] !== '#') hash = '#' + hash |
| 67 | if (search && search[0] !== '?') search = '?' + search |
| 68 | |
| 69 | pathname = pathname.replace(/[?#]/g, encodeURIComponent) |
| 70 | search = search.replace('#', '%23') |
| 71 | |
| 72 | return `${protocol}${host}${pathname}${search}${hash}` |
| 73 | } |
| 74 | |
| 75 | export const urlObjectKeys = [ |
| 76 | 'auth', |
no test coverage detected