Skip to content

Commit

Permalink
Make sure selectedVersionCorrespondingURL never throws an exception
Browse files Browse the repository at this point in the history
I polyfilled `URL.parse` since many browsers don't support it yet,
apparently.

I'd like this function to never throw an exception, any error should
lead to it simply returning `undefined`.
  • Loading branch information
ilyagr committed Sep 24, 2024
1 parent dcfda73 commit 815eeae
Showing 1 changed file with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ export function selectedVersionCorrespondingURL(
currentLocation,
currentBaseURL}: CorrespondingURLParams
): URL | undefined {
const current_path = (new URL(currentBaseURL)).pathname
const current_path = safeURLParse(currentBaseURL)?.pathname
if (current_path === undefined) {
return
}
const currentRelativePath = stripPrefix(currentLocation.pathname, current_path)
if (currentRelativePath === undefined) {
return
Expand All @@ -37,17 +40,37 @@ export function selectedVersionCorrespondingURL(
return
}

const potentialSitemapURL = new URL(currentRelativePath, sitemapCommonPrefix)
if (!selectedVersionSitemap.has(potentialSitemapURL.href)) {
const potentialSitemapURL = safeURLParse(currentRelativePath, sitemapCommonPrefix)
if (!potentialSitemapURL || !selectedVersionSitemap.has(potentialSitemapURL.href)) {
return
}

const result = new URL(currentRelativePath, selectedVersionBaseURL)
const result = safeURLParse(currentRelativePath, selectedVersionBaseURL)
if (!result) {
return
}
result.hash = currentLocation.hash
result.search = currentLocation.search
return result
}

/**
* A version of `new URL` that never throws. A polyfill for URL.parse() which is
* not yet ubuquitous.
*
* @param url - passed to `new URL` constructor
* @param base - passed to `new URL` constructor
*
* @returns `new URL(url, base)` or undefined if the URL is invalid.
*/
function safeURLParse(url: string|URL, base?: string|URL): URL | undefined {
try {
return new URL(url, base)
} catch {
return
}
}

// Basic string manipulation

/**
Expand Down

0 comments on commit 815eeae

Please sign in to comment.