Repository: vitejs/vite
File: packages/vite/src/node/optimizer/rolldownDepPlugin.ts (TypeScript)

Code before:
              code:
                'module.exports = {};' +
                `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
            }
          }
        },
      },
      transform: {
        filter: { code: /new\s+URL/ },
        async handler(code, id) {
          if (!id.includes('node_modules')) return null

          const s = new MagicString(code)

          const workerRE =
            /(new\s+(?:Shared)?Worker\s*\(\s*)new\s+URL\s*\(\s*(['"])((?:(?!\2).|\\.)*)\2\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)
            }
          }

          if (!hasReplacements) return null


Review comment (suggestion):
Let's skip URLs that starts with protocols:
```js
if (isDataUrl(url)) {
  continue
}
```
and `new URL` with `/* @vite-ignore */`.

I think you can copy some code from https://github.com/vitejs/vite/blob/ebda8fd3c14f60e63d13d22102cb3d79a12f47a9/packages/vite/src/node/plugins/assetImportMetaUrl.ts#L62-L75


Code after:

          if (id.startsWith(optionalPeerDepNamespace)) {
            const path = id.slice(optionalPeerDepNamespace.length)
            const [, peerDep, parentDep] = path.split(':')
            return {
              code:
                'module.exports = {};' +
                `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`,
            }
          }
        },
      },
      transform: {
        filter: {
          code: /new\s+URL.+import\.meta\.url/s,
        },
        async handler(code, id) {
          let s: MagicString | undefined
          const assetImportMetaUrlRE =
            /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg
          const cleanString = stripLiteral(code)

          let match: RegExpExecArray | null
          while ((match = assetImportMetaUrlRE.exec(cleanString))) {
            const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices!
            if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue

            const rawUrl = code.slice(urlStart, urlEnd)

            if (rawUrl[0] === '`' && rawUrl.includes('${')) {
              // We skip dynamic template strings in the optimizer for now as they
              // require complex glob transformation that is handled by the main asset plugin.
              continue
            }

            const url = rawUrl.slice(1, -1)
            if (isDataUrl(url) || isExternalUrl(url) || url.startsWith('/')) {
              continue
            }

            if (!s) s = new MagicString(code)

            // we resolve the relative path from the original library file (id) and
            // then rewrite it relative to the bundle (deps) directory.
            const absolutePath = path.resolve(path.dirname(id), url)
            const relativePath = path.relative(bundleOutputDir, absolutePath)
            const normalizedRelativePath = normalizePath(relativePath)
            s.update(
              startIndex,
              endIndex,
              // NOTE: add `'' +` to opt-out rolldown's transform: https://github.com/rolldown/rolldown/issues/2745