Skip to content

Commit

Permalink
only check pathname
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi committed Jun 11, 2024
1 parent 54c1781 commit 44872db
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
4 changes: 4 additions & 0 deletions packages/next/src/lib/metadata/resolvers/resolve-url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ describe('resolveAbsoluteUrlWithPathname', () => {

it('should not add trailing slash to relative url that matches file pattern', () => {
expect(resolver('/foo.html')).toBe('https://example.com/foo.html')
expect(resolver('/foo.html?q=v')).toBe('https://example.com/foo.html?q=v')
expect(resolver(new URL('/.well-known/bar.jpg', metadataBase))).toBe(
'https://example.com/.well-known/bar.jpg/'
)
expect(resolver(new URL('/foo.html', metadataBase))).toBe(
'https://example.com/foo.html'
)
Expand Down
16 changes: 11 additions & 5 deletions packages/next/src/lib/metadata/resolvers/resolve-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ function resolveRelativeUrl(url: string | URL, pathname: string): string | URL {

// The regex is matching logic from packages/next/src/lib/load-custom-routes.ts
const FILE_REGEX =
/^(?:\/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+))\/[/#?]?$/i
/^(?:\/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+))(\/?|$)/i
function isFilePattern(pathname: string): boolean {
return FILE_REGEX.test(pathname)
}
Expand Down Expand Up @@ -117,21 +117,27 @@ function resolveAbsoluteUrlWithPathname(
// - Doesn't have query
if (trailingSlash && !resolvedUrl.endsWith('/')) {
let isRelative = resolvedUrl.startsWith('/')
let isExternal = false
let hasQuery = resolvedUrl.includes('?')
// Do not apply trailing slash for file like urls, aligning with the behavior with `trailingSlash`
let isFileUrl = isFilePattern(resolvedUrl)
let isExternal = false
let isFileUrl = false

if (!isRelative) {
try {
const parsedUrl = new URL(resolvedUrl)
isExternal =
metadataBase != null && parsedUrl.origin !== metadataBase.origin
isFileUrl = isFilePattern(parsedUrl.pathname)
} catch {
// If it's not a valid URL, treat it as external
isExternal = true
}
if (!isFileUrl && !isExternal && !hasQuery) return `${resolvedUrl}/`
if (
// Do not apply trailing slash for file like urls, aligning with the behavior with `trailingSlash`
!isFileUrl &&
!isExternal &&
!hasQuery
)
return `${resolvedUrl}/`
}
}

Expand Down

0 comments on commit 44872db

Please sign in to comment.