MCPcopy
hub / github.com/vercel/next.js / formatUrl

Function formatUrl

packages/next/src/shared/lib/router/utils/format-url.ts:29–73  ·  view source on GitHub ↗
(urlObj: UrlObject)

Source from the content-addressed store, hash-verified

27const slashedProtocols = /https?|ftp|gopher|file/
28
29export 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
75export const urlObjectKeys = [
76 'auth',

Callers 13

formatStringOrUrlFunction · 0.90
formatStringOrUrlFunction · 0.90
getLocaleRedirectFunction · 0.90
normalizeCdnUrlFunction · 0.90
getRequestHandlerMethod · 0.90
renderMethod · 0.90
getHandlerFunction · 0.90
doRenderFunction · 0.90
initializeFunction · 0.85
formatWithValidationFunction · 0.85
base-server.tsFile · 0.85

Calls 6

encodeURIComponentFunction · 0.85
replaceMethod · 0.65
testMethod · 0.65
StringFunction · 0.50
indexOfMethod · 0.45
endsWithMethod · 0.45

Tested by

no test coverage detected