Skip to content
Open
Show file tree
Hide file tree
Changes from 15 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
102 changes: 102 additions & 0 deletions packages/vite/src/node/__tests__/optimizer/rolldownDepPlugin.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { describe, expect, it } from 'vitest'
import { rolldownDepPlugin } from '../../optimizer/rolldownDepPlugin'

describe('rolldownDepPlugin transform', () => {
const createMockEnv = (cacheDir: string) =>
({
config: {
cacheDir,
optimizeDeps: { extensions: [] },
server: { fs: { allow: [] } },
resolve: { builtins: [] },
},
getTopLevelConfig: () => ({
createResolver: () => ({}),
}),
}) as any

const getTransformHandler = (env: any) => {
const plugins = rolldownDepPlugin(env, {}, [])

const plugin = plugins.find(
(p: any) => p.name === 'vite:dep-pre-bundle',
) as any

if (!plugin || !plugin.transform) {
throw new Error(
'Could not find the vite:dep-pre-bundle plugin or its transform hook',
)
}

return plugin.transform.handler
}

it('returns null if id is not in node_modules', async () => {
const env = createMockEnv('/root/node_modules/.vite')
const handler = getTransformHandler(env)

const id = '/root/src/main.js'
const code = `new URL('./worker.js', import.meta.url)`

const result = await handler.call({}, code, id)
expect(result).toBeNull()
})

it('returns null if code contains new URL but no worker pattern', async () => {
const env = createMockEnv('/root/node_modules/.vite')
const handler = getTransformHandler(env)

const id = '/root/node_modules/my-lib/index.js'
const code = `const img = new URL('./logo.png', import.meta.url).href`

const result = await handler.call({}, code, id)
expect(result).toBeNull()
})

it('rebases a single worker URL correctly', async () => {
const env = createMockEnv('/root/node_modules/.vite')
const handler = getTransformHandler(env)

const id = '/root/node_modules/my-lib/dist/index.js'
const code = `const w = new Worker(new URL('./worker.js', import.meta.url))`

const result = await handler.call({}, code, id)

// Path jump from .vite/deps to my-lib/dist/worker.js
expect(result.code).toContain(
'new URL(\'\' + "../../my-lib/dist/worker.js"',
)
expect(result.map).toBeDefined()
})

it('handles multiple workers in a single file', async () => {
const env = createMockEnv('/root/node_modules/.vite')
const handler = getTransformHandler(env)

const id = '/root/node_modules/my-lib/dist/index.js'
const code = `
const w1 = new Worker(new URL('./w1.js', import.meta.url))
const w2 = new Worker(new URL('./nested/w2.js', import.meta.url))
`

const result = await handler.call({}, code, id)

expect(result.code).toContain('"../../my-lib/dist/w1.js"')
expect(result.code).toContain('"../../my-lib/dist/nested/w2.js"')
})

it('handles workers with single and double quotes', async () => {
const env = createMockEnv('/root/node_modules/.vite')
const handler = getTransformHandler(env)
const id = '/root/node_modules/my-lib/index.js'

const code = `
new Worker(new URL('./a.js', import.meta.url))
new SharedWorker(new URL("./b.js", import.meta.url))
`
const result = await handler.call({}, code, id)

expect(result.code).toContain('"../../my-lib/a.js"')
expect(result.code).toContain('"../../my-lib/b.js"')
})
})
8 changes: 4 additions & 4 deletions packages/vite/src/node/__tests__/plugins/import.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ describe('runTransform', () => {
test('import all specifier', () => {
expect(runTransformCjsImport('import * as react from "react"', false))
.toMatchInlineSnapshot(`
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 0)"
`)
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 0)"
`)
expect(runTransformCjsImport('import * as react from "react"', true))
.toMatchInlineSnapshot(`
"import __vite__cjsImport0_react from "./node_modules/.vite/deps/react.js";
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 1)"
const react = ((m, n) => n || !m?.__esModule ? { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m} : m)(__vite__cjsImport0_react, 1)"
`)
})

Expand Down
49 changes: 49 additions & 0 deletions packages/vite/src/node/optimizer/rolldownDepPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'node:path'
import type { ImportKind, Plugin, RolldownPlugin } from 'rolldown'
import { prefixRegex } from '@rolldown/pluginutils'
import MagicString from 'magic-string'
import { JS_TYPES_RE, KNOWN_ASSET_TYPES } from '../constants'
import type { PackageCache } from '../packages'
import {
Expand All @@ -11,6 +12,7 @@ import {
isExternalUrl,
isNodeBuiltin,
moduleListContains,
normalizePath,
} from '../utils'
import { browserExternalId, optionalPeerDepId } from '../plugins/resolve'
import { isModuleCSSRequest } from '../plugins/css'
Expand Down Expand Up @@ -298,6 +300,53 @@ export function rolldownDepPlugin(
}
},
},
transform: {
filter: { code: /new\s+URL/ },
async handler(code, id) {
if (!id.includes('node_modules')) return null

Comment on lines +306 to +307
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!id.includes('node_modules')) return null

If the file is bundled by the optimizer, I think we need to resolve the path in new URL.

const s = new MagicString(code)

const workerRE =
/(new\s+(?:Shared)?Worker\s*\(\s*)new\s+URL\s*\(\s*['"]([^'"]+)['"]\s*,\s*import\.meta\.url\s*\)/g

// Optimized dependencies are always written to the 'deps' sub-directory
// within the configured cache directory.
const bundleDir = path.join(environment.config.cacheDir, 'deps')

let hasReplacements = false
let match
while ((match = workerRE.exec(code))) {
hasReplacements = true
const [fullMatch, prefix, url] = match
const absolutePath = path.resolve(path.dirname(id), url)
const relativePath = path.relative(bundleDir, absolutePath)
const normalizedRelativePath = normalizePath(relativePath)

// NOTE: add `'' +` to opt-out rolldown's transform: https://github.com/rolldown/rolldown/issues/2745
const replacement = `${prefix}new URL('' + ${JSON.stringify(normalizedRelativePath)}, import.meta.url)`

s.overwrite(
match.index,
match.index + fullMatch.length,
replacement,
)

const assetDir = path.dirname(absolutePath)

if (
environment.config.server.fs.allow &&
!environment.config.server.fs.allow.includes(assetDir)
) {
environment.config.server.fs.allow.push(assetDir)
}
Comment on lines +335 to +342
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this part is not needed because it'll be handled by the other internal plugins.

}

if (!hasReplacements) return null

return { code: s.toString(), map: s.generateMap({ hires: true }) }
},
},
},
]
}
Expand Down
11 changes: 11 additions & 0 deletions playground/optimize-deps/__tests__/optimize-deps.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import {
browserErrors,
Expand Down Expand Up @@ -370,3 +372,12 @@ test.runIf(isServe)(
expect(scanErrors).toHaveLength(0)
},
)

test('should fix standard web worker URLs in optimized dependencies', async () => {
await expect
.poll(() => browserLogs.join('\n'))
.toMatch(/Message from lib: worker-success/)
await expect
.poll(() => browserLogs.join('\n'))
.toMatch(/Message from nested: worker-success/)
})
8 changes: 8 additions & 0 deletions playground/optimize-deps/dep-with-worker-repro/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export function urlImportWorker() {
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module',
})
return new Promise((res) => {
worker.onmessage = (e) => res(e.data)
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function urlImportWorker() {
// Testing the ../ path traversal
const worker = new Worker(new URL('../worker.js', import.meta.url), {
type: 'module',
})
return new Promise((res) => {
worker.onmessage = (e) => res(e.data)
})
}
9 changes: 9 additions & 0 deletions playground/optimize-deps/dep-with-worker-repro/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@vitejs/test-dep-with-worker-repro",
"version": "1.0.0",
"type": "module",
"exports": {
".": "./index.js",
"./nested": "./nested/index.js"
}
}
1 change: 1 addition & 0 deletions playground/optimize-deps/dep-with-worker-repro/worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
self.postMessage('worker-success')
7 changes: 7 additions & 0 deletions playground/optimize-deps/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,10 @@ <h2>Virtual module with .vue extension</h2>
`${VirtualComponent.name === 'VirtualComponent' ? 'ok' : 'ng'}`,
)
</script>
<script type="module">
import * as lib from '@vitejs/test-dep-with-worker-repro'
import * as nested from '@vitejs/test-dep-with-worker-repro/nested'

lib.urlImportWorker().then((m) => console.log('Message from lib:', m))
nested.urlImportWorker().then((m) => console.log('Message from nested:', m))
</script>
1 change: 1 addition & 0 deletions playground/optimize-deps/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"@vitejs/test-dep-non-optimized": "file:./dep-non-optimized",
"@vitejs/test-added-in-entries": "file:./added-in-entries",
"@vitejs/test-dep-cjs-external-package-omit-js-suffix": "file:./dep-cjs-external-package-omit-js-suffix",
"@vitejs/test-dep-with-worker-repro": "file:./dep-with-worker-repro",
"lodash-es": "^4.17.22",
"@vitejs/test-nested-exclude": "file:./nested-exclude",
"phoenix": "^1.8.3",
Expand Down
Loading
Loading