Skip to content

Commit

Permalink
fix: normalize asset prefix for socket if start with http
Browse files Browse the repository at this point in the history
refactor: use URL obj

refactor: use URL canParse

Co-authored-by: Sebastian Silbermann <[email protected]>

refactor
  • Loading branch information
devjiwonchoi committed Aug 6, 2024
1 parent dc1088a commit c721b8c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ function getSocketProtocol(assetPrefix: string): string {
protocol = new URL(assetPrefix).protocol
} catch {}

return protocol === 'http:' ? 'ws' : 'wss'
return protocol === 'http:' ? 'ws:' : 'wss:'
}

export function getSocketUrl(assetPrefix: string | undefined): string {
const { hostname, port } = window.location
const protocol = getSocketProtocol(assetPrefix || '')
const prefix = normalizedAssetPrefix(assetPrefix)
const protocol = getSocketProtocol(assetPrefix || '')

// if original assetPrefix is a full URL with protocol
// we just update to use the correct `ws` protocol
if (assetPrefix?.replace(/^\/+/, '').includes('://')) {
return `${protocol}://${prefix}`
if (URL.canParse(prefix)) {
// since normalized asset prefix is ensured to be a URL format,
// we can safely replace the protocol
return prefix.replace(/^http/, 'ws')
}

return `${protocol}://${hostname}:${port}${prefix}`
const { hostname, port } = window.location
return `${protocol}//${hostname}${port ? `:${port}` : ''}${prefix}`
}
17 changes: 10 additions & 7 deletions packages/next/src/shared/lib/normalized-asset-prefix.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
export function normalizedAssetPrefix(assetPrefix: string | undefined): string {
// remove all leading slashes
const escapedAssetPrefix = assetPrefix?.replace(/^\/+/, '') || false

// assetPrefix as a url
if (escapedAssetPrefix && escapedAssetPrefix.startsWith('://')) {
return escapedAssetPrefix.split('://', 2)[1]
}

// assetPrefix is set to `undefined` or '/'
// if an assetPrefix was '/', we return empty string
// because it could be an unnecessary trailing slash
if (!escapedAssetPrefix) {
return ''
}

// assetPrefix is a common path but escaped so let's add one leading slash
if (URL.canParse(escapedAssetPrefix)) {
const { hostname, port, protocol, pathname } = new URL(escapedAssetPrefix)
return `${protocol}//${hostname}${port ? `:${port}` : ''}${pathname}`
}

// assuming assetPrefix here is a pathname-style,
// restore the leading slash
return `/${escapedAssetPrefix}`
}

0 comments on commit c721b8c

Please sign in to comment.