Skip to content

Commit

Permalink
fix: improve url protocol parsing (#1719)
Browse files Browse the repository at this point in the history
  • Loading branch information
brillout authored Jun 27, 2024
1 parent d3e591d commit 027858d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
4 changes: 2 additions & 2 deletions vike/utils/parseUrl.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,11 +478,11 @@ describe('isUriWithProtocol()', () => {
expect(isUriWithProtocol('a:')).toBe(true)
expect(isUriWithProtocol('a-b:')).toBe(true)
expect(isUriWithProtocol('a+b:')).toBe(true)
expect(isUriWithProtocol('a.b:')).toBe(true)
expect(isUriWithProtocol('a2:')).toBe(true)
expect(isUriWithProtocol('2a:')).toBe(true)

// Invalid
expect(isUriWithProtocol('a.b:')).toBe(false)
expect(isUriWithProtocol('2a:')).toBe(false)
expect(isUriWithProtocol('a!b:')).toBe(false)
expect(isUriWithProtocol('a_b:')).toBe(false)
expect(isUriWithProtocol('.ab:')).toBe(false)
Expand Down
24 changes: 14 additions & 10 deletions vike/utils/parseUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ function getPathname(url: string, baseServer: string): { origin: null | string;

function parseOrigin(url: string): { pathname: string; origin: null | string } {
if (!isUrlWithProtocol(url)) {
assert(!isUriWithProtocol(url))
return { pathname: url, origin: null }
} else {
const [originPart1, originPart2, originPart3, ...pathnameParts] = url.split('/')
Expand Down Expand Up @@ -279,16 +280,19 @@ function createUrlFromComponents(
return urlRecreated
}

function isUriWithProtocol(uri: string): boolean {
function isUriWithProtocol(str: string): boolean {
// https://en.wikipedia.org/wiki/List_of_URI_schemes
return /^[a-z0-9][a-z0-9\.\+\-]*:/i.test(uri)
// https://www.rfc-editor.org/rfc/rfc7595
// https://github.com/vikejs/vike/commit/886a99ff21e86a8ca699a25cee7edc184aa058e4#r143308934
// Examples:
// http://
// https://
// tauri:// # [Tauri](https://tauri.app)
// file:// # [Electron](https://github.com/vikejs/vike/issues/1557)
// capacitor:// # [Capacitor](https://github.com/vikejs/vike/issues/1706)
return /^[a-z][a-z0-9\+\-]*:/i.test(str)
}

function isUrlWithProtocol(url: string) {
// http://
// https://
// tauri:// # For [Tauri](https://tauri.app/)
// file:// # For Electron: https://github.com/vikejs/vike/issues/1557
// capacitor:// # For Capacitor: https://github.com/vikejs/vike/issues/1706
return /[a-z]+\:\/\//i.test(url)
// Same as isUriWithProtocol() but with trailing :// which is needed for parseOrigin()
function isUrlWithProtocol(str: string): boolean {
return /^[a-z][a-z0-9\+\-]*:\/\//i.test(str)
}

0 comments on commit 027858d

Please sign in to comment.