diff --git a/packages/vite/src/node/__tests__/html.spec.ts b/packages/vite/src/node/__tests__/html.spec.ts index 0eff4742628c20..528776e9bb372c 100644 --- a/packages/vite/src/node/__tests__/html.spec.ts +++ b/packages/vite/src/node/__tests__/html.spec.ts @@ -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 = ` + +
+ + ` + // @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, diff --git a/packages/vite/src/node/__tests__/optimizer/rolldownDepPlugin.spec.ts b/packages/vite/src/node/__tests__/optimizer/rolldownDepPlugin.spec.ts index 69e9319f177766..86a1b214b1103d 100644 --- a/packages/vite/src/node/__tests__/optimizer/rolldownDepPlugin.spec.ts +++ b/packages/vite/src/node/__tests__/optimizer/rolldownDepPlugin.spec.ts @@ -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: [] }, @@ -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 @@ -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') diff --git a/packages/vite/src/node/__tests__/plugins/import.spec.ts b/packages/vite/src/node/__tests__/plugins/import.spec.ts index 5214380573d709..3c810387694bde 100644 --- a/packages/vite/src/node/__tests__/plugins/import.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/import.spec.ts @@ -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 = { @@ -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( diff --git a/packages/vite/src/node/optimizer/rolldownDepPlugin.ts b/packages/vite/src/node/optimizer/rolldownDepPlugin.ts index 0761be377df113..2bfdd798916486 100644 --- a/packages/vite/src/node/optimizer/rolldownDepPlugin.ts +++ b/packages/vite/src/node/optimizer/rolldownDepPlugin.ts @@ -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) @@ -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.\`) } } }))`, @@ -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?\`)`, } } }, diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index b361bb63d111cf..89ea6c20f6a701 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -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 } @@ -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( @@ -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( diff --git a/packages/vite/src/node/plugins/importAnalysis.ts b/packages/vite/src/node/plugins/importAnalysis.ts index 2b8d32fe487595..8a346403c23693 100644 --- a/packages/vite/src/node/plugins/importAnalysis.ts +++ b/packages/vite/src/node/plugins/importAnalysis.ts @@ -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 }, ) @@ -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, }, @@ -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[] = [] @@ -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 === '*') {