|
| 1 | +import { isPlainObject } from '@sentry/core'; |
| 2 | +import { readFileSync } from 'node:fs'; |
| 3 | +import { createRequire, isBuiltin } from 'node:module'; |
| 4 | +import { isAbsolute } from 'node:path'; |
| 5 | +import type { Plugin } from 'vite'; |
| 6 | + |
| 7 | +type ResolveIdHandler = Extract<NonNullable<Plugin['resolveId']>, (...args: never[]) => unknown>; |
| 8 | +type ResolveIdParameters = Parameters<ResolveIdHandler>; |
| 9 | + |
| 10 | +const NODE_MODULES = '/node_modules/'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Creates a `resolveId` handler that bundles the external packages that bundled CommonJS `require()`s. |
| 14 | + * |
| 15 | + * Rolldown keeps these calls as `__require()`, which a second bundler over the server output can't follow: |
| 16 | + * - https://vite.dev/guide/migration#require-calls-for-externalized-modules |
| 17 | + * - https://rolldown.rs/in-depth/bundling-cjs#require-external-modules |
| 18 | + * |
| 19 | + * Only handles requires from packages bundled for orchestrion, and from packages bundled because of them. |
| 20 | + */ |
| 21 | +export function createExternalRequireResolver( |
| 22 | + moduleNames: readonly string[], |
| 23 | +): (this: ThisParameterType<ResolveIdHandler>, ...args: ResolveIdParameters) => Promise<string | null> { |
| 24 | + const bundledPackagesByEnvironment = new Map<string, Set<string>>(); |
| 25 | + |
| 26 | + return async function resolveExternalRequire(source, importer, options) { |
| 27 | + if ( |
| 28 | + !this.meta.rolldownVersion || |
| 29 | + this.environment.mode !== 'build' || |
| 30 | + options.kind !== 'require-call' || |
| 31 | + !importer || |
| 32 | + !isPackageSpecifier(source) |
| 33 | + ) { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + const bundledPackages = bundledPackagesByEnvironment.get(this.environment.name) ?? new Set(moduleNames); |
| 38 | + bundledPackagesByEnvironment.set(this.environment.name, bundledPackages); |
| 39 | + |
| 40 | + const owner = ownerPackage(importer); |
| 41 | + const name = packageName(source); |
| 42 | + if ( |
| 43 | + !owner || |
| 44 | + !bundledPackages.has(owner.name) || |
| 45 | + isUserExternal(this.environment.config.resolve.external, source, name) || |
| 46 | + isOptionalDependency(owner.dir, name) |
| 47 | + ) { |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + const resolved = await this.resolve(source, importer, { ...options, skipSelf: true }); |
| 52 | + if (!resolved) { |
| 53 | + return null; |
| 54 | + } |
| 55 | + // Vite bundles it anyway (e.g. under pnpm), so its own requires count too. |
| 56 | + if (!resolved.external) { |
| 57 | + bundledPackages.add(name); |
| 58 | + return null; |
| 59 | + } |
| 60 | + |
| 61 | + const file = resolveWithNode(source, importer); |
| 62 | + if (file) { |
| 63 | + bundledPackages.add(name); |
| 64 | + } |
| 65 | + return file ?? null; |
| 66 | + }; |
| 67 | +} |
| 68 | + |
| 69 | +function isPackageSpecifier(source: string): boolean { |
| 70 | + return !isBuiltin(source) && !isAbsolute(source) && !/^[.\0]/.test(source); |
| 71 | +} |
| 72 | + |
| 73 | +// `pg-types/lib/x` → `pg-types`, `@scope/pkg/x` → `@scope/pkg`. |
| 74 | +function packageName(specifier: string): string { |
| 75 | + const [first = '', second] = specifier.split('/'); |
| 76 | + return first.startsWith('@') && second ? `${first}/${second}` : first; |
| 77 | +} |
| 78 | + |
| 79 | +// Uses the last `node_modules` segment, so nested and pnpm store paths work. |
| 80 | +function ownerPackage(file: string): { name: string; dir: string } | undefined { |
| 81 | + const path = file.replace(/\\/g, '/'); |
| 82 | + const start = path.lastIndexOf(NODE_MODULES); |
| 83 | + if (start === -1) { |
| 84 | + return undefined; |
| 85 | + } |
| 86 | + const name = packageName(path.slice(start + NODE_MODULES.length)); |
| 87 | + return { name, dir: `${path.slice(0, start)}${NODE_MODULES}${name}` }; |
| 88 | +} |
| 89 | + |
| 90 | +// Matches like Vite. `external: true` is Vite's SSR default, not a choice for this package. |
| 91 | +function isUserExternal(external: readonly string[] | true, source: string, name: string): boolean { |
| 92 | + return Array.isArray(external) && external.some(entry => entry === source || entry === name); |
| 93 | +} |
| 94 | + |
| 95 | +// These can be missing or native, like `pg-native`. |
| 96 | +function isOptionalDependency(packageDir: string, name: string): boolean { |
| 97 | + const manifest = readManifest(`${packageDir}/package.json`); |
| 98 | + if (!manifest) { |
| 99 | + return false; |
| 100 | + } |
| 101 | + const { peerDependenciesMeta, optionalDependencies } = manifest; |
| 102 | + const peerMeta = isPlainObject(peerDependenciesMeta) ? peerDependenciesMeta[name] : undefined; |
| 103 | + return ( |
| 104 | + (isPlainObject(peerMeta) && peerMeta.optional === true) || |
| 105 | + (isPlainObject(optionalDependencies) && name in optionalDependencies) |
| 106 | + ); |
| 107 | +} |
| 108 | + |
| 109 | +// The file that `require()` loads at runtime. |
| 110 | +function resolveWithNode(source: string, importer: string): string | undefined { |
| 111 | + try { |
| 112 | + return createRequire(importer).resolve(source); |
| 113 | + } catch { |
| 114 | + return undefined; |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +function readManifest(file: string): Record<string, unknown> | undefined { |
| 119 | + try { |
| 120 | + const manifest: unknown = JSON.parse(readFileSync(file, 'utf8')); |
| 121 | + return isPlainObject(manifest) ? manifest : undefined; |
| 122 | + } catch { |
| 123 | + return undefined; |
| 124 | + } |
| 125 | +} |
0 commit comments