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 authored Mar 25, 2021
1 parent be76a30 commit ed321ba
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
42 changes: 42 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { injectQuery } from '../utils'

const isWindows = process.platform === 'win32'

if (isWindows) {
// this test will work incorrectly on unix systems
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'
)
})
5 changes: 4 additions & 1 deletion packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,17 @@ export function removeImportQuery(url: string) {
}

export function injectQuery(url: string, queryToInject: string) {
let resolvedUrl = new URL(url, 'relative:///')
// encode percents for consistent behavior with pathToFileURL
// see #2614 for details
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 ed321ba

Please sign in to comment.