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

Code before:
          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/ },
        async handler(code, id) {
          if (!id.includes('node_modules')) return null

          const s = new MagicString(code)

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

          let match
          while ((match = workerRE.exec(code))) {
            const [fullMatch, url] = match
            const absolutePath = path.resolve(path.dirname(id), url)
            const fsUrl = FS_PREFIX + normalizePath(absolutePath)

            // NOTE: add `'' +` to opt-out of Rolldown's static asset analysis.
            // This prevents the optimizer from trying to bundle the absolute path
            // as a relative asset.
            const replacement = `new URL('' + ${JSON.stringify(fsUrl)}, 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)
            }
          }
          return { code: s.toString(), map: s.generateMap({ hires: true }) }
        },
      },
    },

Review comment (performance):
We shouldn't use absolute paths here so that the optimized cache doesn't rely on the project path. I think we should generate a resolved relative path to the file from the output file path.

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)