Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle paths with special characters in injectQuery (fix #2585) #2614

Merged
merged 2 commits into from
Mar 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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:///')
patak-dev marked this conversation as resolved.
Show resolved Hide resolved
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