Skip to content
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
32 changes: 31 additions & 1 deletion packages/vite/src/node/__tests__/html.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
import { init, parse as parseImports } from 'es-module-lexer'
import type { OutputBundle, OutputChunk } from 'rolldown'
import { describe, expect, test } from 'vitest'
import { getCssFilesForChunk } from '../plugins/html'
import { PartialEnvironment } from '../baseEnvironment'
import { resolveConfig } from '../config'
import { buildHtmlPlugin, getCssFilesForChunk } from '../plugins/html'
import { normalizePath } from '../utils'

test('buildHtmlPlugin escapes HTML proxy imports', async () => {
await init()

const config = await resolveConfig(
{ configFile: false, build: { modulePreload: false } },
'build',
)
const plugin = buildHtmlPlugin(config)
const environment = new PartialEnvironment('client', config)
const id = normalizePath(`${config.root}/index'"\n.html`)

const html = `
<script type="module">console.log("hello")</script>
<div style="background: url(./image.png)"></div>
<style>body { color: red }</style>
`
// @ts-expect-error transform.handler should exist
const result = await plugin.transform.handler.call({ environment }, html, id)
const [imports] = parseImports(result.code)
expect(imports.map((specifier) => specifier.specifier)).toStrictEqual([
`${id}?html-proxy&index=0.js`,
`${id}?html-proxy&inline-css&style-attr&index=1.css`,
`${id}?html-proxy&inline-css&index=2.css`,
])
})

function createChunk(
fileName: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { describe, expect, test } from 'vitest'
import { rolldownDepPlugin } from '../../optimizer/rolldownDepPlugin'
import { optionalPeerDepId } from '../../plugins/resolve'
import { normalizePath } from '../../utils'

async function createRolldownDepPluginTransform(cacheDir: string) {
function createRolldownDepPlugins(cacheDir: string) {
const baseConfig = {
cacheDir: normalizePath(cacheDir),
optimizeDeps: { extensions: [] },
Expand All @@ -16,7 +17,11 @@ async function createRolldownDepPluginTransform(cacheDir: string) {
getTopLevelConfig: () => baseConfig,
} as any

const plugins = rolldownDepPlugin(mockEnvironment, {}, [])
return rolldownDepPlugin(mockEnvironment, {}, [])
}

async function createRolldownDepPluginTransform(cacheDir: string) {
const plugins = createRolldownDepPlugins(cacheDir)
const plugin = plugins.find(
(p: any) => p.name === 'vite:dep-pre-bundle',
) as any
Expand All @@ -33,6 +38,64 @@ async function createRolldownDepPluginTransform(cacheDir: string) {
}
}

describe('rolldownDepPlugin escaped specifiers', () => {
const [assetsPlugin, depPlugin] = createRolldownDepPlugins('/root/.vite')
const specialCharacters = '\'"`\\\n${value}'

test('escapes CSS imports', () => {
// @ts-expect-error load.handler should exist
const { code } = assetsPlugin.load.handler(
'vite:dep-pre-bundle:external-conversion/root/asset".css',
)
expect(code).toMatchInlineSnapshot(
`"import "vite-dep-pre-bundle-external:/root/asset\\".css";"`,
)
})

test('escapes CSS module re-exports', () => {
// @ts-expect-error load.handler should exist
const { code } = assetsPlugin.load.handler(
'vite:dep-pre-bundle:external-conversion/root/asset".module.css',
)
expect(code).toMatchInlineSnapshot(
`"export { default } from "vite-dep-pre-bundle-external:/root/asset\\".module.css";export * from "vite-dep-pre-bundle-external:/root/asset\\".module.css";"`,
)
})

test('escapes browser external module names', () => {
const path = `dep${specialCharacters}`
// @ts-expect-error load.handler should exist
const { code } = depPlugin.load.handler(`browser-external:${path}`)
expect(code).toMatchInlineSnapshot(`
" module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (
key !== '__esModule' &&
key !== '__proto__' &&
key !== 'constructor' &&
key !== 'splice'
) {
const path = "dep'\\"\`\\\\\\n\${value}"
console.warn(\`Module "\${path}" has been externalized for browser compatibility. Cannot access "\${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
}
}
}))"
`)
})

test('escapes optional peer dependency names', () => {
const peerDep = `peer${specialCharacters}`
const parentDep = `parent${specialCharacters}`
// @ts-expect-error load.handler should exist
const { code } = depPlugin.load.handler(
`optional-peer-dep:${optionalPeerDepId}:${peerDep}:${parentDep}`,
)
expect(code).toMatchInlineSnapshot(
`"module.exports = {};const peerDep = "peer'\\"\`\\\\\\n\${value}";const parentDep = "parent'\\"\`\\\\\\n\${value}";throw new Error(\`Could not resolve "\${peerDep}" imported by "\${parentDep}". Is it installed?\`)"`,
)
})
})

describe('rolldownDepPlugin transform', async () => {
const transform = await createRolldownDepPluginTransform('/root/.vite')

Expand Down
34 changes: 33 additions & 1 deletion packages/vite/src/node/__tests__/plugins/import.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { init, parse as parseImports } from 'es-module-lexer'
import MagicString from 'magic-string'
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { transformCjsImport } from '../../plugins/importAnalysis'
import {
interopNamedImports,
transformCjsImport,
} from '../../plugins/importAnalysis'

describe('runTransform', () => {
const config: any = {
Expand Down Expand Up @@ -33,6 +38,33 @@ describe('runTransform', () => {
config.logger.warn.mockClear()
})

describe('escaped URLs', async () => {
await init()
const url = '/node_modules/.vite/deps/dep\'"\\\n\r\t.js'

for (const source of [
'import "dep"',
'import value from "dep"',
'import(\n "dep"\n)',
"export * from 'dep'",
'export * from "dep"',
"export * from 'de\\\np'",
]) {
test(`preserves the URL and line count in ${source}`, () => {
const str = new MagicString(source)
const [imports] = parseImports(source)
interopNamedImports(str, imports[0], url, 0, 'modA', false, config)
const code = str.toString()
const [rewrittenImports] = parseImports(code)
expect(
rewrittenImports.map((specifier) => specifier.specifier),
).toStrictEqual([url])
// keep the number of lines for sourcemap
expect(code.split('\n')).toHaveLength(source.split('\n').length)
})
}
})

test('import specifier', () => {
expect(
runTransformCjsImport(
Expand Down
9 changes: 6 additions & 3 deletions packages/vite/src/node/optimizer/rolldownDepPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ export function rolldownDepPlugin(
handler(id) {
const path = id.slice(externalWithConversionNamespace.length)
// import itself with prefix (this is the actual part of require-import conversion)
const modulePath = `"${convertedExternalPrefix}${path}"`
const modulePath = JSON.stringify(`${convertedExternalPrefix}${path}`)
return {
code:
isCSSRequest(path) && !isModuleCSSRequest(path)
Expand Down Expand Up @@ -302,7 +302,8 @@ export function rolldownDepPlugin(
key !== 'constructor' &&
key !== 'splice'
) {
console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
const path = ${JSON.stringify(path)}
console.warn(\`Module "\${path}" has been externalized for browser compatibility. Cannot access "\${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
}
}
}))`,
Expand All @@ -316,7 +317,9 @@ export function rolldownDepPlugin(
return {
code:
'module.exports = {};' +
`throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
`const peerDep = ${JSON.stringify(peerDep)};` +
`const parentDep = ${JSON.stringify(parentDep)};` +
`throw new Error(\`Could not resolve "\${peerDep}" imported by "\${parentDep}". Is it installed?\`)`,
}
}
},
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
code: contents,
})
js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`
js += `\nimport ${JSON.stringify(`${id}?html-proxy&index=${inlineModuleIndex}.js`)}`
shouldRemove = true
}

Expand Down Expand Up @@ -735,7 +735,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
const filePath = id.replace(normalizePath(config.root), '')
addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code })
// will transform with css plugin and cache result with css-post plugin
js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`
js += `\nimport ${JSON.stringify(`${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css`)}`
const hash = getHash(cleanUrl(id))
// will transform in `applyHtmlTransforms`
overwriteAttrValue(
Expand All @@ -754,7 +754,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
addToHTMLProxyCache(config, filePath, inlineModuleIndex, {
code: styleNode.value,
})
js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`
js += `\nimport ${JSON.stringify(`${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css`)}`
const hash = getHash(cleanUrl(id))
// will transform in `applyHtmlTransforms`
s.update(
Expand Down
12 changes: 6 additions & 6 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -990,7 +990,7 @@ export function interopNamedImports(
str.overwrite(
expStart,
expEnd,
`import('${rewrittenUrl}').then(m => (${interopHelperStr})(m.default, ${+isNodeMode}))` +
`import(${JSON.stringify(rewrittenUrl)}).then(m => (${interopHelperStr})(m.default, ${+isNodeMode}))` +
getLineBreaks(exp),
{ contentOnly: true },
)
Expand Down Expand Up @@ -1021,9 +1021,9 @@ export function interopNamedImports(
} else {
// #1439 export * from '...'
str.overwrite(
start,
end,
rewrittenUrl + getLineBreaks(source.slice(start, end)),
start - 1,
end + 1,
JSON.stringify(rewrittenUrl) + getLineBreaks(source.slice(start, end)),
{
contentOnly: true,
},
Expand Down Expand Up @@ -1079,7 +1079,7 @@ export function transformCjsImport(
node.type === 'ExportNamedDeclaration'
) {
if (!node.specifiers.length) {
return { importLine: `import "${url}"` }
return { importLine: `import ${JSON.stringify(url)}` }
}

const importNames: ImportNameSpecifier[] = []
Expand Down Expand Up @@ -1127,7 +1127,7 @@ export function transformCjsImport(
const cjsModuleName = makeLegalIdentifier(
`__vite__cjsImport${importIndex}_${rawUrl}`,
)
const importLine = `import ${cjsModuleName} from "${url}"`
const importLine = `import ${cjsModuleName} from ${JSON.stringify(url)}`
const lines: string[] = []
importNames.forEach(({ importedName, localName }) => {
if (importedName === '*') {
Expand Down
Loading