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 26, 2024
1 parent 244130a commit b368435
Showing 1 changed file with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ export function selectedVersionCorrespondingURL(
selectedVersionBaseURL,
currentLocation,
currentBaseURL} = params
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 @@ -47,17 +50,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

/** Strip a given prefix from a function
Expand Down

0 comments on commit b368435

Please sign in to comment.