Skip to content

Commit

Permalink
fix: injectQuery double encoding (vitejs#18246)
Browse files Browse the repository at this point in the history
Co-authored-by: mykwillis <myk@mykwillis.com>
  • Loading branch information
sapphi-red and mykwillis authored Oct 4, 2024
1 parent 4389a91 commit 2c5f948
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
6 changes: 6 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ describe('injectQuery', () => {
'/usr/vite/東京 %20 hello?direct',
)
})

test('path with url-encoded path as query parameter', () => {
const src = '/src/module.ts?url=https%3A%2F%2Fusr.vite%2F'
const expected = '/src/module.ts?t=1234&url=https%3A%2F%2Fusr.vite%2F'
expect(injectQuery(src, 't=1234')).toEqual(expected)
})
})

describe('resolveHostname', () => {
Expand Down
24 changes: 10 additions & 14 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@ import type MagicString from 'magic-string'

import type { TransformResult } from 'rollup'
import { createFilter as _createFilter } from '@rollup/pluginutils'
import { cleanUrl, isWindows, slash, withTrailingSlash } from '../shared/utils'
import {
cleanUrl,
isWindows,
slash,
splitFileAndPostfix,
withTrailingSlash,
} from '../shared/utils'
import { VALID_ID_PREFIX } from '../shared/constants'
import {
CLIENT_ENTRY,
Expand Down Expand Up @@ -311,20 +317,10 @@ export function removeRawQuery(url: string): string {
return url.replace(rawRE, '$1').replace(trailingSeparatorRE, '')
}

const replacePercentageRE = /%/g
export function injectQuery(url: string, queryToInject: string): string {
// encode percents for consistent behavior with pathToFileURL
// see #2614 for details
const resolvedUrl = new URL(
url.replace(replacePercentageRE, '%25'),
'relative:///',
)
const { search, hash } = resolvedUrl
let pathname = cleanUrl(url)
pathname = isWindows ? slash(pathname) : pathname
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${
hash ?? ''
}`
const { file, postfix } = splitFileAndPostfix(url)
const normalizedFile = isWindows ? slash(file) : file
return `${normalizedFile}?${queryToInject}${postfix[0] === '?' ? `&${postfix.slice(1)}` : /* hash only */ postfix}`
}

const timestampRE = /\bt=\d{13}&?\b/
Expand Down

0 comments on commit 2c5f948

Please sign in to comment.