Skip to content

Commit 446954c

Browse files
authored
refactor(dev): share ModuleURL and BrowserURL conversions (#23790)
1 parent 2601eed commit 446954c

15 files changed

Lines changed: 137 additions & 91 deletions

File tree

‎packages/vite/src/client/client.ts‎

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77
createWebSocketModuleRunnerTransport,
88
normalizeModuleRunnerTransport,
99
} from '../shared/moduleRunnerTransport'
10-
import { wrapId } from '../shared/utils'
10+
import { moduleUrlToBrowserUrl } from '../shared/utils'
1111
import type { BundledDevHMRClient } from './bundledDevHmrClient'
1212
import { ErrorOverlay, cspNonce, overlayId } from './overlay'
1313
// @ts-expect-error internal virtual module
@@ -140,10 +140,6 @@ const debounceReload = (time: number) => {
140140
}
141141
export const pageReload = debounceReload(20)
142142

143-
function wrapIdIfNeeded(id: string): string {
144-
return id[0] === '.' || id[0] === '/' ? id : wrapId(id)
145-
}
146-
147143
const hmrClient = new HMRClient(
148144
{
149145
error: (err) => console.error('[vite]', err),
@@ -157,15 +153,11 @@ const hmrClient = new HMRClient(
157153
isWithinCircularImport,
158154
}) {
159155
const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`)
160-
const browserPath = wrapIdIfNeeded(acceptedPathWithoutQuery)
161-
const importPromise = import(
162-
/* @vite-ignore */
163-
base +
164-
browserPath.slice(1) +
165-
`?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${
166-
query ? `&${query}` : ''
167-
}`
168-
)
156+
const moduleUrl = `${acceptedPathWithoutQuery}?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${
157+
query ? `&${query}` : ''
158+
}`
159+
const browserUrl = moduleUrlToBrowserUrl(moduleUrl, base)
160+
const importPromise = import(/* @vite-ignore */ browserUrl)
169161
if (isWithinCircularImport) {
170162
importPromise.catch(() => {
171163
console.info(
@@ -244,9 +236,8 @@ async function handleMessage(payload: HotPayload) {
244236
return
245237
}
246238

247-
const newPath = `${base}${searchUrl.slice(1)}${
248-
searchUrl.includes('?') ? '&' : '?'
249-
}t=${timestamp}`
239+
const moduleUrl = `${searchUrl}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`
240+
const browserUrl = moduleUrlToBrowserUrl(moduleUrl, base)
250241

251242
// rather than swapping the href on the existing tag, we will
252243
// create a new link tag. Once the new stylesheet has loaded we
@@ -255,7 +246,7 @@ async function handleMessage(payload: HotPayload) {
255246
// directly, as the new stylesheet has not yet been loaded.
256247
return new Promise((resolve) => {
257248
const newLinkTag = el.cloneNode() as HTMLLinkElement
258-
newLinkTag.href = new URL(newPath, el.href).href
249+
newLinkTag.href = new URL(browserUrl, el.href).href
259250
const removeOldEl = () => {
260251
el.remove()
261252
console.debug(`[vite] css hot updated: ${searchUrl}`)
@@ -605,8 +596,8 @@ export function removeStyle(id: string): void {
605596
}
606597
}
607598

608-
export function createHotContext(ownerPath: string): ViteHotContext {
609-
return new HMRContext(hmrClient, ownerPath)
599+
export function createHotContext(moduleUrl: string): ViteHotContext {
600+
return new HMRContext(hmrClient, moduleUrl)
610601
}
611602

612603
/**

‎packages/vite/src/node/build.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import type { RollupCommonJSOptions } from '#dep-types/commonjs'
2929
import type { RollupDynamicImportVarsOptions } from '#dep-types/dynamicImportVars'
3030
import type { EsbuildTarget } from '#types/internal/esbuildOptions'
3131
import type { AssetMetadata, ChunkMetadata } from '#types/metadata'
32+
import { joinUrlSegments } from '../shared/utils'
3233
import type { PartialEnvironment } from './baseEnvironment'
3334
import { BaseEnvironment } from './baseEnvironment'
3435
import type {
@@ -75,7 +76,6 @@ import {
7576
createDebugger,
7677
displayTime,
7778
getPkgName,
78-
joinUrlSegments,
7979
mergeConfig,
8080
mergeWithDefaults,
8181
partialEncodeURIPath,

‎packages/vite/src/node/optimizer/index.ts‎

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
} from '../constants'
2323
import type { Environment } from '../environment'
2424
import { transformWithOxc } from '../plugins/oxc'
25+
import { fileToModuleUrl } from '../server/moduleUrl'
2526
import {
2627
arraify,
2728
asyncFlatten,
@@ -32,7 +33,6 @@ import {
3233
lookupFile,
3334
normalizeId,
3435
normalizePath,
35-
removeLeadingSlash,
3636
tryStatSync,
3737
unique,
3838
} from '../utils'
@@ -997,17 +997,7 @@ export function createIsOptimizedDepUrl(
997997
): (url: string) => boolean {
998998
const { root } = environment.config
999999
const depsCacheDir = getDepsCacheDirPrefix(environment)
1000-
1001-
// determine the url prefix of files inside cache directory
1002-
const depsCacheDirRelative = normalizePath(path.relative(root, depsCacheDir))
1003-
const depsCacheDirPrefix = depsCacheDirRelative.startsWith('../')
1004-
? // if the cache directory is outside root, the url prefix would be something
1005-
// like '/@fs/absolute/path/to/node_modules/.vite'
1006-
`/@fs/${removeLeadingSlash(normalizePath(depsCacheDir))}`
1007-
: // if the cache directory is inside root, the url prefix would be something
1008-
// like '/node_modules/.vite'
1009-
`/${depsCacheDirRelative}`
1010-
1000+
const depsCacheDirPrefix = fileToModuleUrl(depsCacheDir, root)
10111001
return function isOptimizedDepUrl(url: string): boolean {
10121002
return url.startsWith(depsCacheDirPrefix)
10131003
}

‎packages/vite/src/node/plugins/asset.ts‎

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,27 @@ import type {
1515
import { makeIdFiltersToMatchWithQuery } from 'rolldown/filter'
1616
import {
1717
cleanUrl,
18+
joinUrlSegments,
19+
moduleUrlToBrowserUrl,
1820
splitFileAndPostfix,
19-
withTrailingSlash,
2021
} from '../../shared/utils'
2122
import type { PartialEnvironment } from '../baseEnvironment'
2223
import {
2324
createToImportMetaURLBasedRelativeRuntime,
2425
toOutputFilePathInJS,
2526
} from '../build'
2627
import type { ResolvedConfig } from '../config'
27-
import {
28-
DEFAULT_ASSETS_INLINE_LIMIT,
29-
DEFAULT_ASSETS_RE,
30-
FS_PREFIX,
31-
} from '../constants'
28+
import { DEFAULT_ASSETS_INLINE_LIMIT, DEFAULT_ASSETS_RE } from '../constants'
3229
import type { Environment } from '../environment'
3330
import type { Plugin } from '../plugin'
3431
import { checkPublicFile } from '../publicDir'
32+
import { fileToModuleUrl } from '../server/moduleUrl'
3533
import {
3634
encodeURIPath,
3735
getHash,
3836
injectQuery,
39-
joinUrlSegments,
4037
normalizePath,
4138
rawRE,
42-
removeLeadingSlash,
4339
removeUrlQuery,
4440
urlRE,
4541
} from '../utils'
@@ -485,20 +481,9 @@ export async function fileToDevUrl(
485481
return pathToFileURL(cleanedId).href
486482
}
487483

488-
let rtn: string
489-
if (publicFile) {
490-
// in public dir during dev, keep the url as-is
491-
rtn = id
492-
} else if (id.startsWith(withTrailingSlash(config.root))) {
493-
// in project root, infer short public path
494-
rtn = '/' + path.posix.relative(config.root, id)
495-
} else {
496-
// outside of project root, use absolute fs path
497-
// (this is special handled by the serve static middleware
498-
rtn = path.posix.join(FS_PREFIX, id)
499-
}
484+
const moduleUrl = publicFile ? id : fileToModuleUrl(id, config.root)
500485
const base = joinUrlSegments(config.server.origin ?? '', config.decodedBase)
501-
return joinUrlSegments(base, removeLeadingSlash(rtn))
486+
return moduleUrlToBrowserUrl(moduleUrl, base)
502487
}
503488

504489
export function getPublicAssetFilename(

‎packages/vite/src/node/plugins/css.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import type { LightningCSSOptions } from '#types/internal/lightningcssOptions'
3838
import type { CustomPluginOptionsVite } from '#types/metadata'
3939
import { type DevEnvironment } from '..'
4040
import { NULL_BYTE_PLACEHOLDER } from '../../shared/constants'
41-
import { cleanUrl, isWindows, slash } from '../../shared/utils'
41+
import { cleanUrl, isWindows, joinUrlSegments, slash } from '../../shared/utils'
4242
import { PartialEnvironment } from '../baseEnvironment'
4343
import {
4444
createToImportMetaURLBasedRelativeRuntime,
@@ -87,7 +87,6 @@ import {
8787
isDataUrl,
8888
isExternalUrl,
8989
isObject,
90-
joinUrlSegments,
9190
lineTerminatorRE,
9291
mergeWithDefaults,
9392
normalizePath,

‎packages/vite/src/node/plugins/importAnalysis.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { parseAst } from 'rolldown/parseAst'
1717
import type { ESTree } from 'rolldown/utils'
1818
import {
1919
cleanUrl,
20+
joinUrlSegments,
2021
unwrapId,
2122
withTrailingSlash,
2223
wrapId,
@@ -59,7 +60,6 @@ import {
5960
isFilePathFormatExplicit,
6061
isInNodeModules,
6162
isJSRequest,
62-
joinUrlSegments,
6363
moduleListContains,
6464
normalizePath,
6565
prettifyUrl,
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import path from 'node:path'
2+
import { describe, expect, it } from 'vitest'
3+
import { moduleUrlToBrowserUrl } from '../../../shared/utils'
4+
import { normalizePath } from '../../utils'
5+
import { browserUrlToModuleUrl, fileToModuleUrl } from '../moduleUrl'
6+
7+
describe('ModuleURL and BrowserURL conversions', () => {
8+
const root = normalizePath(path.resolve('/project'))
9+
it('maps normalized file paths to root-relative or filesystem URLs', () => {
10+
const cases = [
11+
{ input: root, output: '/' },
12+
{ input: `${root}/.hidden.js`, output: '/.hidden.js' },
13+
{ input: `${root}/src/file.js?raw`, output: '/src/file.js?raw' },
14+
{
15+
input: `${root}-sibling/file.js`,
16+
output: path.posix.join('/@fs/', `${root}-sibling/file.js`),
17+
},
18+
{ input: 'C:/outside/file.js', output: '/@fs/C:/outside/file.js' },
19+
{ input: 'C:/src/file.js', inputRoot: 'C:/', output: '/src/file.js' },
20+
{ input: '/src/file.js', inputRoot: '/', output: '/src/file.js' },
21+
]
22+
23+
for (const { input, inputRoot = root, output } of cases) {
24+
expect(fileToModuleUrl(input, inputRoot)).toBe(output)
25+
}
26+
})
27+
28+
for (const [moduleUrl, browserPath] of [
29+
[
30+
'/src/a%25 b-あ.js?raw&plugin=a%2Fb',
31+
'/src/a%25 b-あ.js?raw&plugin=a%2Fb',
32+
],
33+
[
34+
'\0virtual:demo?direct&index=0.css',
35+
'/@id/__x00__virtual:demo?direct&index=0.css',
36+
],
37+
['virtual:demo?v=old&worker', '/@id/virtual:demo?v=old&worker'],
38+
['/@fs/C:/outside/file.js?url', '/@fs/C:/outside/file.js?url'],
39+
]) {
40+
it(`preserves ModuleURL through BrowserURL transport: ${moduleUrl}`, () => {
41+
expect(moduleUrlToBrowserUrl(moduleUrl, '')).toBe(browserPath)
42+
const browserUrl = moduleUrlToBrowserUrl(moduleUrl, '/base/')
43+
expect(browserUrl).toBe('/base' + browserPath)
44+
expect(browserUrlToModuleUrl(browserUrl, '/base/')).toBe(moduleUrl)
45+
})
46+
}
47+
})

‎packages/vite/src/node/server/middlewares/base.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import type { Connect } from '#dep-types/connect'
2-
import { cleanUrl, withTrailingSlash } from '../../../shared/utils'
3-
import { joinUrlSegments, stripBase } from '../../utils'
2+
import {
3+
cleanUrl,
4+
joinUrlSegments,
5+
withTrailingSlash,
6+
} from '../../../shared/utils'
7+
import { stripBase } from '../../utils'
48

59
// this middleware is only active when (base !== '/')
610

‎packages/vite/src/node/server/middlewares/htmlFallback.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import fs from 'node:fs'
22
import path from 'node:path'
33
import type { Connect } from '#dep-types/connect'
4-
import { cleanUrl } from '../../../shared/utils'
5-
import { createDebugger, joinUrlSegments } from '../../utils'
4+
import { cleanUrl, joinUrlSegments } from '../../../shared/utils'
5+
import { createDebugger } from '../../utils'
66
import type { DevEnvironment } from '../environment'
77

88
const debug = createDebugger('vite:html-fallback')

‎packages/vite/src/node/server/middlewares/indexHtml.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import type { DefaultTreeAdapterMap, Token } from 'parse5'
66
import type { SourceMapInput } from 'rolldown'
77
import type { Connect } from '#dep-types/connect'
88
import type { PreviewServer, ResolvedConfig, ViteDevServer } from '../..'
9-
import { cleanUrl, unwrapId, wrapId } from '../../../shared/utils'
9+
import {
10+
cleanUrl,
11+
joinUrlSegments,
12+
unwrapId,
13+
wrapId,
14+
} from '../../../shared/utils'
1015
import { getNodeAssetAttributes } from '../../assetSource'
1116
import { CLIENT_PUBLIC_PATH, FS_PREFIX } from '../../constants'
1217
import { getHmrImplementation } from '../../plugins/clientInjections'
@@ -39,7 +44,6 @@ import {
3944
isDevServer,
4045
isJSRequest,
4146
isParentDirectory,
42-
joinUrlSegments,
4347
normalizePath,
4448
processSrcSetSync,
4549
stripBase,

0 commit comments

Comments
 (0)