import { readFile } from 'node:fs/promises'; import * as path from 'node:path'; import { basename } from 'node:path/posix'; import { ErrorCategory, ErrorDomain, MastraBaseError } from '@internal/core/error'; import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin'; import commonjs from '@rollup/plugin-commonjs'; import json from '@rollup/plugin-json'; import nodeResolve from '@rollup/plugin-node-resolve'; import virtual from '@rollup/plugin-virtual'; import * as resolve from 'resolve.exports'; import { rollup } from 'rollup'; import type { OutputChunk, OutputAsset, Plugin } from 'rollup'; import type { WorkspacePackageInfo } from '../../bundler/workspaceDependencies'; import { getPackageRootPath, getPackageInfo } from '../package-info'; import { esbuild } from '../plugins/esbuild'; import { esmShim } from '../plugins/esm-shim'; import { aliasHono } from '../plugins/hono-alias'; import { moduleAlias } from '../plugins/module-alias'; import { moduleResolveMap } from '../plugins/module-resolve-map'; import { nodeGypDetector } from '../plugins/node-gyp-detector'; import { protocolExternalResolver } from '../plugins/protocol-external-resolver'; import { subpathExternalsResolver } from '../plugins/subpath-externals-resolver'; import { tsConfigPaths } from '../plugins/tsconfig-paths'; import type { DependencyMetadata } from '../types'; import { getCompiledDepCachePath, getNodeResolveOptions, isDependencyPartOfPackage, rollupSafeName, slash, } from '../utils'; import type { BundlerPlatform } from '../utils'; import { DEPS_TO_IGNORE } from './constants'; import type { NormalizedExternals } from './externals'; type VirtualDependency = { name: string; virtual: string; }; function prepareEntryFileName(name: string, rootDir: string) { return rollupSafeName(name, rootDir); } /** * Creates virtual dependency modules for optimized bundling by generating virtual entry points for each dependency with their specific exports and handling workspace package path resolution. */ export function createVirtualDependencies( depsToOptimize: Map, { projectRoot, workspaceRoot, outputDir, bundlerOptions, }: { workspaceRoot: string | null; projectRoot: string; outputDir: string; bundlerOptions?: { isDev?: boolean; externalsPreset?: boolean }; }, ): { optimizedDependencyEntries: Map; fileNameToDependencyMap: Map; } { const { isDev = false, externalsPreset = false } = bundlerOptions || {}; const fileNameToDependencyMap = new Map(); const optimizedDependencyEntries = new Map(); const rootDir = workspaceRoot || projectRoot; for (const [dep, { exports }] of depsToOptimize.entries()) { // Use __ as separator to avoid conflicts with hyphens in package names // e.g., @inner/inner-tools -> @inner__inner-tools (preserves the hyphen) const fileName = dep.replaceAll('/', '__'); const virtualFile: string[] = []; const exportStringBuilder = []; for (const local of exports) { if (local === '*') { virtualFile.push(`export * from '${dep}';`); continue; } else if (local === 'default') { exportStringBuilder.push('default'); } else { exportStringBuilder.push(local); } } const chunks = []; if (exportStringBuilder.length) { chunks.push(`{ ${exportStringBuilder.join(', ')} }`); } if (chunks.length) { virtualFile.push(`export ${chunks.join(', ')} from '${dep}';`); } // Determine the entry name based on the complexity of exports let entryName = prepareEntryFileName(path.join(outputDir, fileName), rootDir); fileNameToDependencyMap.set(entryName, dep); optimizedDependencyEntries.set(dep, { name: entryName, virtual: virtualFile.join('\n'), }); } // For workspace packages, we still want the dependencies to be imported from the original path // We rewrite the path to the original folder inside node_modules/.cache if (isDev || externalsPreset) { for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) { if (!isWorkspace || !rootPath || !workspaceRoot) { continue; } const currentDepPath = optimizedDependencyEntries.get(dep); if (!currentDepPath) { continue; } const fileName = basename(currentDepPath.name); const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir); fileNameToDependencyMap.set(entryName, dep); optimizedDependencyEntries.set(dep, { ...currentDepPath, name: entryName, }); } } return { optimizedDependencyEntries, fileNameToDependencyMap }; } /** * Configures and returns Rollup plugins for bundling external dependencies. * Sets up virtual modules, TypeScript compilation, CommonJS transformation, and workspace resolution. */ async function getInputPlugins( virtualDependencies: Map, { transpilePackages, workspaceMap, bundlerOptions, projectRoot, rootDir, externals, platform, alias, }: { transpilePackages: Set; workspaceMap: Map; bundlerOptions: { noBundling: boolean }; projectRoot: string; rootDir: string; externals: string[]; platform: BundlerPlatform; alias: Record; }, ) { const transpilePackagesMap = new Map(); for (const pkg of transpilePackages) { const dir = await getPackageRootPath(pkg); if (dir) { transpilePackagesMap.set(pkg, slash(dir)); } else { transpilePackagesMap.set(pkg, workspaceMap.get(pkg)?.location ?? pkg); } } return [ virtual( Array.from(virtualDependencies.entries()).reduce>((acc, [dep, virtualDep]) => { acc[`#virtual-${dep}`] = virtualDep.virtual; return acc; }, {}), ), moduleAlias(alias, path.join(rootDir, 'package.json'), platform), tsConfigPaths({ cwd: projectRoot }), protocolExternalResolver(), subpathExternalsResolver(externals, workspaceMap), transpilePackagesMap.size ? esbuild({ format: 'esm', include: [ // Match files from transpilePackages by their actual directory paths // but exclude any nested node_modules ...[...transpilePackagesMap.values()].map(p => { if (path.isAbsolute(p)) { return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/(?!.*node_modules).*$`); } return new RegExp(`\/${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/(?!.*node_modules).*$`); }), // Also match workspace packages resolved through node_modules symlinks // (common in pnpm workspaces). Match by package name in node_modules path. ...[...transpilePackagesMap.keys()].map(pkgName => { const escapedPkgName = pkgName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return new RegExp(`/node_modules/${escapedPkgName}/(?!.*node_modules).*$`); }), ], // Disable the default /node_modules/ exclusion from rollup-plugin-esbuild. // In pnpm workspaces, nodeResolve resolves workspace packages through node_modules // symlinks, so the resolved paths contain "node_modules". Without this, workspace // package .ts files won't be transpiled even if they match the include patterns. exclude: [], }) : null, bundlerOptions.noBundling ? ({ name: 'alias-optimized-deps', async resolveId(id, importer, options) { if (!virtualDependencies.has(id)) { return null; } const info = virtualDependencies.get(id)!; // go from ./node_modules/.cache/index.js to ./pkg const packageRootPath = path.join(rootDir, path.dirname(path.dirname(path.dirname(info.name)))); const pkgJsonBuffer = await readFile(path.join(packageRootPath, 'package.json'), 'utf-8'); const pkgJson = JSON.parse(pkgJsonBuffer); if (!pkgJson) { return null; } const pkgName = pkgJson.name || ''; let resolvedPath: string | undefined = resolve.exports(pkgJson, id.replace(pkgName, '.'))?.[0]; if (!resolvedPath) { resolvedPath = pkgJson!.main ?? 'index.js'; } const resolved = await this.resolve(path.posix.join(packageRootPath, resolvedPath!), importer, options); return resolved; }, } satisfies Plugin) : null, optimizeLodashImports({ include: '**/*.{js,ts,mjs,cjs}', // v6 rewrites lodash. imports to lodash/, which breaks projects that don't install lodash. optimizeModularizedImports: false, }), commonjs({ strictRequires: 'strict', transformMixedEsModules: true, ignoreTryCatch: false, }), bundlerOptions.noBundling ? null : nodeResolve({ ...getNodeResolveOptions(platform), rootDir: projectRoot, modulePaths: [path.join(rootDir, 'node_modules')], }), bundlerOptions.noBundling ? esmShim() : null, // hono is imported from deployer, so we need to resolve from here instead of the project root aliasHono(), json(), nodeGypDetector(), moduleResolveMap(externals, rootDir), { name: 'not-found-resolver', resolveId: { order: 'post', async handler(id, importer) { if (!importer) { return null; } if (!id.endsWith('.node')) { return null; } const pkgInfo = await getPackageInfo(importer); const packageName = pkgInfo?.packageJson?.name || id; throw new MastraBaseError({ id: 'DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD', domain: ErrorDomain.DEPLOYER, category: ErrorCategory.USER, details: { importFile: importer, packageName, }, text: `We found a possible binary dependency in your bundle. ${id} was not found when imported at ${importer}. Please consider adding \`${packageName}\` to your externals, or updating this import to not end with ".node". export const mastra = new Mastra({ bundler: { externals: ["${packageName}"], } })`, }); }, }, } satisfies Plugin, ].filter(Boolean); } /** * Executes the Rollup build process for virtual dependencies using configured plugins. * Bundles all virtual dependency modules into optimized ESM files with proper external handling. */ async function buildExternalDependencies( virtualDependencies: Map, { externals, packagesToTranspile, workspaceMap, projectRoot, rootDir, outputDir, bundlerOptions, platform, alias, }: { externals: string[]; packagesToTranspile: Set; workspaceMap: Map; projectRoot: string; rootDir: string; outputDir: string; bundlerOptions: { isDev: boolean; externalsPreset: boolean; }; platform: BundlerPlatform; alias: Record; }, ) { /** * If there are no virtual dependencies to bundle, return an empty array to avoid Rollup errors. */ if (virtualDependencies.size === 0) { return [] as unknown as [OutputChunk, ...(OutputAsset | OutputChunk)[]]; } const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset; const plugins = await getInputPlugins(virtualDependencies, { transpilePackages: packagesToTranspile, workspaceMap, bundlerOptions: { noBundling, }, projectRoot, rootDir, externals, platform, alias, }); const aliasSources = new Set(Object.keys(alias)); const rollupExternals = externals.filter(external => !aliasSources.has(external)); const bundler = await rollup({ logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent', input: Array.from(virtualDependencies.entries()).reduce>((acc, [dep, virtualDep]) => { acc[virtualDep.name] = `#virtual-${dep}`; return acc; }, {}), external: rollupExternals, treeshake: noBundling ? false : 'safest', plugins, }); const outputDirRelative = prepareEntryFileName(outputDir, rootDir); const { output } = await bundler.write({ format: 'esm', dir: rootDir, entryFileNames: '[name].mjs', // used to get the filename of the actual error sourcemap: true, /** * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure. * So we want to write them to the `.mastra/output` folder as well. */ chunkFileNames: chunkInfo => { /** * This whole bunch of logic directly below is for the edge case shown in the e2e-tests/monorepo with "tinyrainbow" package. It's used in multiple places in the package and as such Rollup creates a shared chunk for it. During 'mastra dev' / with externals: true, we don't want that chunk to show up in the '.mastra/output' folder (outputDirRelative) but inside /node_modules/.cache instead. * We only care about this for the "noBundling" case! */ if (noBundling) { const importedFromPackages = new Set(); for (const moduleId of chunkInfo.moduleIds) { const normalized = slash(moduleId); for (const [pkgName, pkgInfo] of workspaceMap.entries()) { const location = slash(pkgInfo.location); if (normalized.startsWith(location)) { importedFromPackages.add(pkgName); break; } } } // A chunk spanning multiple workspace packages has no single owning cache dir, so it falls through to the output dir. if (importedFromPackages.size === 1) { const [pkgName] = importedFromPackages; const workspaceLocation = workspaceMap.get(pkgName!)!.location; return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, '[name].mjs'), rootDir); } } return `${outputDirRelative}/[name].mjs`; }, assetFileNames: `${outputDirRelative}/[name][extname]`, hoistTransitiveImports: false, }); await bundler.close(); return output; } /** * Recursively searches through Rollup output chunks to find which module imports a specific external dependency. * Used to build the module resolution map for proper external dependency tracking. */ function findExternalImporter( module: OutputChunk, external: string, allOutputs: OutputChunk[], visited = new Set(), ): OutputChunk | null { if (visited.has(module.fileName)) { return null; } visited.add(module.fileName); const capturedFiles = new Set(); for (const id of [...module.imports, ...module.dynamicImports]) { if (isDependencyPartOfPackage(id, external)) { return module; } else if (id.endsWith('.mjs')) { capturedFiles.add(id); } } for (const file of capturedFiles) { const nextModule = allOutputs.find(o => o.fileName === file); if (nextModule) { const importer = findExternalImporter(nextModule, external, allOutputs, visited); if (importer) { return importer; } } } return null; } /** * Bundles vendor dependencies identified in the analysis step. * Creates virtual modules for each dependency and bundles them using rollup. * * @param depsToOptimize - Map of dependencies to optimize with their metadata (exported bindings, rootPath, isWorkspace) * @param outputDir - Directory where bundled files will be written * @param logger - Logger instance for debugging * @returns Object containing bundle output and reference map for validation */ export async function bundleExternals( depsToOptimize: Map, outputDir: string, options: { bundlerOptions: NormalizedExternals & { isDev?: boolean; transpilePackages?: string[]; alias?: Record; }; projectRoot?: string; workspaceRoot?: string; workspaceMap?: Map; platform?: BundlerPlatform; }, ) { const { workspaceRoot = null, workspaceMap = new Map(), projectRoot = outputDir, bundlerOptions, platform = 'node', } = options; const { externalsPreset, mergedExternals, transpilePackages = [], isDev = false, alias = {} } = bundlerOptions; const workspacePackagesNames = Array.from(workspaceMap.keys()); const packagesToTranspile = new Set([...transpilePackages, ...workspacePackagesNames]); /** * When externals: true, we need to extract non-workspace deps from depsToOptimize * and add them directly to usedExternals instead of bundling them. */ const extractedExternals = new Map(); if (externalsPreset) { for (const [dep, metadata] of depsToOptimize.entries()) { if (!metadata.isWorkspace) { // Add to extracted externals - use rootPath or fallback to package name extractedExternals.set(dep, metadata.rootPath ?? dep); // Remove from depsToOptimize so it won't be bundled depsToOptimize.delete(dep); } } } const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, { workspaceRoot, outputDir, projectRoot, bundlerOptions: { isDev, externalsPreset, }, }); const output = await buildExternalDependencies(optimizedDependencyEntries, { externals: mergedExternals, packagesToTranspile, workspaceMap, projectRoot, rootDir: workspaceRoot || projectRoot, outputDir, bundlerOptions: { isDev, externalsPreset, }, platform, alias, }); const moduleResolveMap = new Map>(); const filteredChunks = output.filter(o => o.type === 'chunk'); for (const o of filteredChunks.filter(o => o.isEntry || o.isDynamicEntry)) { for (const external of mergedExternals) { if (DEPS_TO_IGNORE.includes(external)) { continue; } const importer = findExternalImporter(o, external, filteredChunks); if (importer) { const fullPath = path.join(workspaceRoot || projectRoot, importer.fileName); let innerMap = moduleResolveMap.get(fullPath); if (!innerMap) { innerMap = new Map(); moduleResolveMap.set(fullPath, innerMap); } if (importer.moduleIds.length) { innerMap.set( external, importer.moduleIds[importer.moduleIds.length - 1]?.startsWith('\x00virtual:#virtual') ? importer.moduleIds[importer.moduleIds.length - 2]! : importer.moduleIds[importer.moduleIds.length - 1]!, ); } } } } /** * Convert moduleResolveMap to a plain object with prototype-less objects */ const usedExternals = Object.create(null) as Record>; for (const [fullPath, innerMap] of moduleResolveMap) { const innerObj = Object.create(null) as Record; for (const [external, value] of innerMap) { innerObj[external] = value; } usedExternals[fullPath] = innerObj; } /** * When externals: true, add the extracted non-workspace deps to usedExternals * using a synthetic entry path to track them. */ if (extractedExternals.size > 0) { const syntheticPath = path.join(workspaceRoot || projectRoot, '__externals__'); const externalsObj = Object.create(null) as Record; for (const [dep, rootPath] of extractedExternals) { externalsObj[dep] = rootPath; } usedExternals[syntheticPath] = externalsObj; } return { output, fileNameToDependencyMap, usedExternals }; }