Skip to content

Commit

Permalink
fix: handle paths with special characters in injectQuery (fix #2585)
Browse files Browse the repository at this point in the history
  • Loading branch information
GrygrFlzr committed Mar 20, 2021
1 parent 3a7cfba commit 92ff42d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
37 changes: 37 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { injectQuery } from '../utils'

test('normalize windows path', () => {
expect(injectQuery('C:\\User\\Vite\\Project', 'direct')).toEqual(
'C:/User/Vite/Project?direct'
)
})

test('path with multiple spaces', () => {
expect(injectQuery('/usr/vite/path with space', 'direct')).toEqual(
'/usr/vite/path with space?direct'
)
})

test('path with multiple % characters', () => {
expect(injectQuery('/usr/vite/not%20a%20space', 'direct')).toEqual(
'/usr/vite/not%20a%20space?direct'
)
})

test('path with %25', () => {
expect(injectQuery('/usr/vite/%25hello%25', 'direct')).toEqual(
'/usr/vite/%25hello%25?direct'
)
})

test('path with unicode', () => {
expect(injectQuery('/usr/vite/東京', 'direct')).toEqual(
'/usr/vite/東京?direct'
)
})

test('path with unicode, space, and %', () => {
expect(injectQuery('/usr/vite/東京 %20 hello', 'direct')).toEqual(
'/usr/vite/東京 %20 hello?direct'
)
})
3 changes: 2 additions & 1 deletion packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,15 @@ export function removeImportQuery(url: string) {
}

export function injectQuery(url: string, queryToInject: string) {
let resolvedUrl = new URL(url, 'relative:///')
let resolvedUrl = new URL(url.replace(/%/g, '%25'), 'relative:///')
if (resolvedUrl.protocol !== 'relative:') {
resolvedUrl = pathToFileURL(url)
}
let { protocol, pathname, search, hash } = resolvedUrl
if (protocol === 'file:') {
pathname = pathname.slice(1)
}
pathname = decodeURIComponent(pathname)
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${
hash || ''
}`
Expand Down

0 comments on commit 92ff42d

Please sign in to comment.