'use strict'; var chunkYW7AIVNG_cjs = require('./chunk-YW7AIVNG.cjs'); var chunk3T7FP546_cjs = require('./chunk-3T7FP546.cjs'); var fs = require('fs'); var promises = require('fs/promises'); var path = require('path'); var babel2 = require('@babel/core'); var error = require('@mastra/core/error'); var pkg = require('empathic/package'); var findWorkspaces = require('find-workspaces'); var child_process = require('child_process'); var url = require('url'); var logger = require('@mastra/core/logger'); var commonjs = require('@rollup/plugin-commonjs'); var json = require('@rollup/plugin-json'); var virtual = require('@rollup/plugin-virtual'); var esm = require('fs-extra/esm'); var localPkg = require('local-pkg'); var rollup = require('rollup'); var posix = require('path/posix'); var rollupPlugin = require('@optimize-lodash/rollup-plugin'); var nodeResolve = require('@rollup/plugin-node-resolve'); var resolve = require('resolve.exports'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var path__namespace = /*#__PURE__*/_interopNamespace(path); var babel2__namespace = /*#__PURE__*/_interopNamespace(babel2); var pkg__namespace = /*#__PURE__*/_interopNamespace(pkg); var commonjs__default = /*#__PURE__*/_interopDefault(commonjs); var json__default = /*#__PURE__*/_interopDefault(json); var virtual__default = /*#__PURE__*/_interopDefault(virtual); var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve); var resolve__namespace = /*#__PURE__*/_interopNamespace(resolve); // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/stacktrace-parser/0.1.11/63406bc765474556691ebd1b24eaa0c5b032f058a26bbaff13797a2780d98220/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js var UNKNOWN_FUNCTION = ""; function parse(stackString) { var lines = stackString.split("\n"); return lines.reduce(function(stack, line) { var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line); if (parseResult) { stack.push(parseResult); } return stack; }, []); } var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc||\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/; function parseChrome(line) { var parts = chromeRe.exec(line); if (!parts) { return null; } var isNative = parts[2] && parts[2].indexOf("native") === 0; var isEval = parts[2] && parts[2].indexOf("eval") === 0; var submatch = chromeEvalRe.exec(parts[2]); if (isEval && submatch != null) { parts[2] = submatch[1]; parts[3] = submatch[2]; parts[4] = submatch[3]; } return { file: !isNative ? parts[2] : null, methodName: parts[1] || UNKNOWN_FUNCTION, arguments: isNative ? [parts[2]] : [], lineNumber: parts[3] ? +parts[3] : null, column: parts[4] ? +parts[4] : null }; } var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; function parseWinjs(line) { var parts = winjsRe.exec(line); if (!parts) { return null; } return { file: parts[2], methodName: parts[1] || UNKNOWN_FUNCTION, arguments: [], lineNumber: +parts[3], column: parts[4] ? +parts[4] : null }; } var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i; var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; function parseGecko(line) { var parts = geckoRe.exec(line); if (!parts) { return null; } var isEval = parts[3] && parts[3].indexOf(" > eval") > -1; var submatch = geckoEvalRe.exec(parts[3]); if (isEval && submatch != null) { parts[3] = submatch[1]; parts[4] = submatch[2]; parts[5] = null; } return { file: parts[3], methodName: parts[1] || UNKNOWN_FUNCTION, arguments: parts[2] ? parts[2].split(",") : [], lineNumber: parts[4] ? +parts[4] : null, column: parts[5] ? +parts[5] : null }; } var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i; function parseJSC(line) { var parts = javaScriptCoreRe.exec(line); if (!parts) { return null; } return { file: parts[3], methodName: parts[1] || UNKNOWN_FUNCTION, arguments: [], lineNumber: +parts[4], column: parts[5] ? +parts[5] : null }; } var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i; function parseNode(line) { var parts = nodeRe.exec(line); if (!parts) { return null; } return { file: parts[2], methodName: parts[1] || UNKNOWN_FUNCTION, arguments: [], lineNumber: +parts[3], column: parts[4] ? +parts[4] : null }; } var workspacesCache = findWorkspaces.createWorkspacesCache(); async function getWorkspaceInformation({ dir = process.cwd(), mastraEntryFile }) { const closestPkgJson = pkg__namespace.up({ cwd: path.dirname(mastraEntryFile) }); const location = closestPkgJson ? path.dirname(chunk3T7FP546_cjs.slash(closestPkgJson)) : chunk3T7FP546_cjs.slash(process.cwd()); const workspaces = await findWorkspaces.findWorkspaces(dir, { cache: workspacesCache }); const _workspaceMap = new Map( workspaces?.map((workspace) => [ workspace.package.name, { location: workspace.location, dependencies: workspace.package.dependencies, version: workspace.package.version } ]) ?? [] ); const isWorkspacePackage = (workspaces ?? []).some((ws) => ws.location === location); const workspaceRoot = isWorkspacePackage ? findWorkspaces.findWorkspacesRoot(dir, { cache: workspacesCache })?.location : void 0; return { // If the current package is not part of the workspace, the bundling down the line shouldn't look at any workspace packages workspaceMap: isWorkspacePackage ? _workspaceMap : /* @__PURE__ */ new Map(), workspaceRoot, isWorkspacePackage }; } var ValidationError = class extends Error { type; stack; constructor(args) { super(args.message); this.type = args.type; this.stack = args.stack; } }; function spawn(command, args = [], options = {}) { return new Promise((resolve2, reject) => { let validationError = null; const childProcess = child_process.spawn(command, args, { stdio: ["ignore", "ignore", "pipe"], ...options }); childProcess.on("error", (error) => { reject(error); }); let stderr = ""; childProcess.stderr?.on("data", (message) => { try { validationError = JSON.parse(message.toString()); } catch { stderr += message; } }); childProcess.on("close", (code) => { if (code === 0) { resolve2(); } else { if (validationError) { reject(new ValidationError(validationError)); } else { reject(new Error(stderr)); } } }); }); } function validate(file, { injectESMShim = false, moduleResolveMapLocation, stubbedExternals = [] }) { let prefixCode = ""; if (injectESMShim) { prefixCode = `import { fileURLToPath } from 'url'; import { dirname } from 'path'; globalThis.__filename = fileURLToPath(import.meta.url); globalThis.__dirname = dirname(__filename); `; } function errorHandler(err) { console.error( JSON.stringify({ type: err.name, message: err.message, stack: err.stack }) ); process.exit(1); } return spawn( process.execPath, [ "--import", undefined("@mastra/deployer/loader"), "--input-type=module", "--enable-source-maps", "-e", `${prefixCode};import('${url.pathToFileURL(file).href}').catch(err => { ${errorHandler.toString()} errorHandler(err); })`.replaceAll(/\n/g, "") ], { env: { ...process.env, MODULE_MAP: `${moduleResolveMapLocation}`, STUBBED_EXTERNALS: JSON.stringify(stubbedExternals) }, cwd: path.dirname(file) } ); } // src/build/analyze/constants.ts var DEPS_TO_IGNORE = ["#tools", "execa"]; var GLOBAL_EXTERNALS = [ "pino", "pino-pretty", "@libsql/client", "pg", "libsql", "#tools", "typescript", "undici", "readable-stream", "bufferutil", "utf-8-validate", "execa" ]; var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"]; // src/build/analyze/analyzeEntry.ts function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) { const normalizedMastraEntry = chunk3T7FP546_cjs.slash(mastraEntry); let virtualPlugin = null; if (isVirtualFile) { virtualPlugin = virtual__default.default({ "#entry": entry }); entry = "#entry"; } const plugins = []; if (virtualPlugin) { plugins.push(virtualPlugin); } plugins.push( ...[ chunkYW7AIVNG_cjs.tsConfigPaths(), chunkYW7AIVNG_cjs.protocolExternalResolver(), { name: "custom-alias-resolver", resolveId(id) { if (id === "#server") { return chunk3T7FP546_cjs.slash(url.fileURLToPath(undefined("@mastra/deployer/server"))); } if (id === "#mastra") { return normalizedMastraEntry; } if (id.startsWith("@mastra/server")) { return url.fileURLToPath(undefined(id)); } } }, json__default.default(), chunkYW7AIVNG_cjs.esbuild(), commonjs__default.default({ strictRequires: "debug", ignoreTryCatch: false, transformMixedEsModules: true, extensions: [".js", ".ts"] }), chunkYW7AIVNG_cjs.removeDeployer(mastraEntry, { sourcemap: sourcemapEnabled }), chunkYW7AIVNG_cjs.esbuild() ] ); return plugins; } async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, { logger: logger$1, shouldCheckTransitiveDependencies, analyzeCache }) { const depsToOptimize = /* @__PURE__ */ new Map(); if (!output.facadeModuleId) { throw new Error( "Something went wrong, we could not find the package name of the entry file. Please open an issue." ); } let entryRootPath = projectRoot; if (!output.facadeModuleId.startsWith("\0virtual:")) { entryRootPath = await chunkYW7AIVNG_cjs.getPackageRootPath(output.facadeModuleId) || projectRoot; } for (const [dependency, bindings] of Object.entries(output.importedBindings)) { if (!chunk3T7FP546_cjs.isBareModuleSpecifier(dependency)) { continue; } const pkgName = chunk3T7FP546_cjs.getPackageName(dependency); let rootPath = null; let isWorkspace = false; let version; if (pkgName) { rootPath = await chunkYW7AIVNG_cjs.getPackageRootPath(dependency, entryRootPath); isWorkspace = workspaceMap.has(pkgName); if (rootPath) { try { const pkgJson = await esm.readJSON(`${rootPath}/package.json`); version = pkgJson.version; } catch { } } } const normalizedRootPath = rootPath ? chunk3T7FP546_cjs.slash(rootPath) : null; depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace, version }); } async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) { if (currentDepth >= maxDepth) { logger$1.warn("Maximum dependency depth reached while checking transitive dependencies."); return; } const depsSnapshot = new Map(depsToOptimize); let hasAddedDeps = false; for (const [dep, meta] of depsSnapshot) { if (!meta.isWorkspace || internalMap.has(dep)) { continue; } try { const importerPath = output.facadeModuleId ? url.pathToFileURL(output.facadeModuleId).href : url.pathToFileURL(projectRoot).href; const resolvedPath = localPkg.resolveModule(dep, { paths: [importerPath] }); if (!resolvedPath) { logger$1.warn("Could not resolve path for workspace dependency", { dep }); continue; } const analysis = await analyzeEntry({ entry: resolvedPath, isVirtualFile: false }, "", { workspaceMap, projectRoot, logger: logger.noopLogger, sourcemapEnabled: false, initialDepsToOptimize: depsToOptimize, analyzeCache }); if (!analysis?.dependencies) { continue; } for (const [innerDep, innerMeta] of analysis.dependencies) { if (innerMeta.isWorkspace && !internalMap.has(innerDep) && !depsToOptimize.has(innerDep)) { depsToOptimize.set(innerDep, innerMeta); internalMap.set(innerDep, innerMeta); hasAddedDeps = true; } } } catch (err) { logger$1.error("Failed to resolve or analyze dependency", { dep, error: err.message }); } } if (hasAddedDeps) { await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1); } } if (shouldCheckTransitiveDependencies) { await checkTransitiveDependencies(initialDepsToOptimize); } const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d)); if (dynamicImports.length) { for (const dynamicImport of dynamicImports) { if (!depsToOptimize.has(dynamicImport) && chunk3T7FP546_cjs.isBareModuleSpecifier(dynamicImport)) { const pkgName = chunk3T7FP546_cjs.getPackageName(dynamicImport); let version; let rootPath = null; if (pkgName) { rootPath = await chunkYW7AIVNG_cjs.getPackageRootPath(dynamicImport, entryRootPath); if (rootPath) { try { const pkgJson = await esm.readJSON(`${rootPath}/package.json`); version = pkgJson.version; } catch { } } } depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: rootPath ? chunk3T7FP546_cjs.slash(rootPath) : null, isWorkspace: false, version }); } } } return depsToOptimize; } async function analyzeEntry({ entry, isVirtualFile }, mastraEntry, { logger, sourcemapEnabled, workspaceMap, projectRoot, initialDepsToOptimize = /* @__PURE__ */ new Map(), // used to avoid infinite recursion shouldCheckTransitiveDependencies = false, analyzeCache }) { const cacheKey = isVirtualFile ? void 0 : chunk3T7FP546_cjs.slash(entry); if (cacheKey && analyzeCache?.has(cacheKey)) { return analyzeCache.get(cacheKey); } const optimizerBundler = await rollup.rollup({ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent", input: isVirtualFile ? "#entry" : entry, treeshake: false, preserveSymlinks: true, plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }), external: DEPS_TO_IGNORE }); const { output } = await optimizerBundler.generate({ format: "esm", inlineDynamicImports: true }); await optimizerBundler.close(); const depsToOptimize = await captureDependenciesToOptimize( output[0], workspaceMap, projectRoot, initialDepsToOptimize, { logger, shouldCheckTransitiveDependencies, analyzeCache } ); const result = { dependencies: depsToOptimize, output: { code: output[0].code, map: output[0].map } }; if (cacheKey && analyzeCache) { analyzeCache.set(cacheKey, result); } return result; } function aliasHono() { return { name: "hono-alias", resolveId(id) { if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") { return; } const path2 = undefined(id); return url.fileURLToPath(path2); } }; } function moduleResolveMap(externals, projectRoot) { const importMap = /* @__PURE__ */ new Map(); return { name: "module-resolve-map", moduleParsed(info) { if (info.importedIds.length === 0 || !info.id) { return; } for (const importedId of info.importedIds) { for (const external of externals) { if (chunk3T7FP546_cjs.isDependencyPartOfPackage(importedId, external)) { importMap.set(external, info.id); } } } }, async generateBundle(options, bundle) { const resolveMap = /* @__PURE__ */ new Map(); for (const [fileName, chunk] of Object.entries(bundle)) { if (chunk.type === "chunk") { for (const [external, resolvedFrom] of importMap) { if (chunk.moduleIds.includes(resolvedFrom)) { const fullPath = url.pathToFileURL(chunk3T7FP546_cjs.slash(path.join(projectRoot, fileName))).toString(); const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map(); innerMap.set(external, url.pathToFileURL(chunk3T7FP546_cjs.slash(resolvedFrom)).toString()); resolveMap.set(fullPath, innerMap); } } } } const resolveMapJson = Object.fromEntries( Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())]) ); this.emitFile({ type: "asset", name: "module-resolve-map.json", source: `${JSON.stringify(resolveMapJson, null, 2)}` }); } }; } function nodeGypDetector() { const modulesToTrack = /* @__PURE__ */ new Set(); const modulesToTrackPackageInfo = /* @__PURE__ */ new Map(); return { name: "node-gyp-build-detector", moduleParsed(info) { if (!info.meta?.commonjs?.requires?.length) { return; } const hasNodeGypBuild = info.meta.commonjs.requires.some( (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js") ); if (!hasNodeGypBuild) { return; } modulesToTrack.add(info.id); modulesToTrackPackageInfo.set(info.id, localPkg.getPackageInfo(info.id)); }, async generateBundle(options, bundle) { const binaryMapByChunk = /* @__PURE__ */ new Map(); for (const [fileName, chunk] of Object.entries(bundle)) { if (chunk.type === "chunk") { for (const moduleId of chunk.moduleIds) { if (modulesToTrackPackageInfo.has(moduleId)) { const pkgInfo = await modulesToTrackPackageInfo.get(moduleId); if (!binaryMapByChunk.has(fileName)) { binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set()); } if (pkgInfo?.packageJson?.name) { binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name); } } } } } const binaryMapJson = Object.fromEntries( Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)]) ); this.emitFile({ type: "asset", name: "binary-map.json", source: `${JSON.stringify(binaryMapJson, null, 2)}` }); } }; } // src/build/analyze/bundleExternals.ts function prepareEntryFileName(name, rootDir) { return chunk3T7FP546_cjs.rollupSafeName(name, rootDir); } function createVirtualDependencies(depsToOptimize, { projectRoot, workspaceRoot, outputDir, bundlerOptions }) { const { isDev = false, externalsPreset = false } = bundlerOptions || {}; const fileNameToDependencyMap = /* @__PURE__ */ new Map(); const optimizedDependencyEntries = /* @__PURE__ */ new Map(); const rootDir = workspaceRoot || projectRoot; for (const [dep, { exports: exports2 }] of depsToOptimize.entries()) { const fileName = dep.replaceAll("/", "__"); const virtualFile = []; const exportStringBuilder = []; for (const local of exports2) { 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}';`); } let entryName = prepareEntryFileName(path__namespace.join(outputDir, fileName), rootDir); fileNameToDependencyMap.set(entryName, dep); optimizedDependencyEntries.set(dep, { name: entryName, virtual: virtualFile.join("\n") }); } 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 = posix.basename(currentDepPath.name); const entryName = prepareEntryFileName(chunk3T7FP546_cjs.getCompiledDepCachePath(rootPath, fileName), rootDir); fileNameToDependencyMap.set(entryName, dep); optimizedDependencyEntries.set(dep, { ...currentDepPath, name: entryName }); } } return { optimizedDependencyEntries, fileNameToDependencyMap }; } async function getInputPlugins2(virtualDependencies, { transpilePackages, workspaceMap, bundlerOptions, rootDir, externals, platform }) { const transpilePackagesMap = /* @__PURE__ */ new Map(); for (const pkg2 of transpilePackages) { const dir = await chunkYW7AIVNG_cjs.getPackageRootPath(pkg2); if (dir) { transpilePackagesMap.set(pkg2, chunk3T7FP546_cjs.slash(dir)); } else { transpilePackagesMap.set(pkg2, workspaceMap.get(pkg2)?.location ?? pkg2); } } return [ virtual__default.default( Array.from(virtualDependencies.entries()).reduce( (acc, [dep, virtualDep]) => { acc[`#virtual-${dep}`] = virtualDep.virtual; return acc; }, {} ) ), chunkYW7AIVNG_cjs.tsConfigPaths(), chunkYW7AIVNG_cjs.protocolExternalResolver(), chunkYW7AIVNG_cjs.subpathExternalsResolver(externals), transpilePackagesMap.size ? chunkYW7AIVNG_cjs.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__namespace.isAbsolute(p)) { return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`); } else { 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); const packageRootPath = path__namespace.join(rootDir, path__namespace.dirname(path__namespace.dirname(path__namespace.dirname(info.name)))); const pkgJsonBuffer = await promises.readFile(path__namespace.join(packageRootPath, "package.json"), "utf-8"); const pkgJson = JSON.parse(pkgJsonBuffer); if (!pkgJson) { return null; } const pkgName = pkgJson.name || ""; let resolvedPath = resolve__namespace.exports(pkgJson, id.replace(pkgName, "."))?.[0]; if (!resolvedPath) { resolvedPath = pkgJson.main ?? "index.js"; } const resolved = await this.resolve(path__namespace.posix.join(packageRootPath, resolvedPath), importer, options); return resolved; } } : null, rollupPlugin.optimizeLodashImports({ include: "**/*.{js,ts,mjs,cjs}" }), commonjs__default.default({ strictRequires: "strict", transformMixedEsModules: true, ignoreTryCatch: false }), bundlerOptions.noBundling ? null : nodeResolve__default.default(chunk3T7FP546_cjs.getNodeResolveOptions(platform)), bundlerOptions.noBundling ? chunkYW7AIVNG_cjs.esmShim() : null, // hono is imported from deployer, so we need to resolve from here instead of the project root aliasHono(), json__default.default(), 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 localPkg.getPackageInfo(importer); const packageName = pkgInfo?.packageJson?.name || id; throw new error.MastraBaseError({ id: "DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD", domain: error.ErrorDomain.DEPLOYER, category: error.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}"], } })` }); } } } ].filter(Boolean); } async function buildExternalDependencies(virtualDependencies, { externals, packagesToTranspile, workspaceMap, rootDir, outputDir, bundlerOptions, platform }) { if (virtualDependencies.size === 0) { return []; } const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset; const plugins = await getInputPlugins2(virtualDependencies, { transpilePackages: packagesToTranspile, workspaceMap, bundlerOptions: { noBundling }, rootDir, externals, platform }); const bundler = await rollup.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: externals, 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) => { if (noBundling) { const importedFromPackages = /* @__PURE__ */ new Set(); for (const moduleId of chunkInfo.moduleIds) { const normalized = chunk3T7FP546_cjs.slash(moduleId); for (const [pkgName, pkgInfo] of workspaceMap.entries()) { const location = chunk3T7FP546_cjs.slash(pkgInfo.location); if (normalized.startsWith(location)) { importedFromPackages.add(pkgName); break; } } } if (importedFromPackages.size > 1) { throw new error.MastraBaseError({ id: "DEPLOYER_BUNDLE_EXTERNALS_SHARED_CHUNK", domain: error.ErrorDomain.DEPLOYER, category: error.ErrorCategory.USER, details: { chunkName: chunkInfo.name, packages: JSON.stringify(Array.from(importedFromPackages)) }, text: `Please open an issue. We found a shared chunk "${chunkInfo.name}" used by multiple workspace packages: ${Array.from(importedFromPackages).join(", ")}.` }); } if (importedFromPackages.size === 1) { const [pkgName] = importedFromPackages; const workspaceLocation = workspaceMap.get(pkgName).location; return prepareEntryFileName(chunk3T7FP546_cjs.getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir); } } return `${outputDirRelative}/[name].mjs`; }, assetFileNames: `${outputDirRelative}/[name][extname]`, hoistTransitiveImports: false }); await bundler.close(); return output; } function findExternalImporter(module, external, allOutputs) { const capturedFiles = /* @__PURE__ */ new Set(); for (const id of module.imports) { if (chunk3T7FP546_cjs.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); if (importer) { return importer; } } } return null; } async function bundleExternals(depsToOptimize, outputDir, options) { const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions = {}, platform = "node" } = options; const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {}; let externalsPreset = false; if (customExternals === true) { externalsPreset = true; } const externalsList = Array.isArray(customExternals) ? customExternals : []; const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...externalsList]; const workspacePackagesNames = Array.from(workspaceMap.keys()); const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]); const extractedExternals = /* @__PURE__ */ new Map(); if (externalsPreset) { for (const [dep, metadata] of depsToOptimize.entries()) { if (!metadata.isWorkspace) { extractedExternals.set(dep, metadata.rootPath ?? dep); depsToOptimize.delete(dep); } } } const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, { workspaceRoot, outputDir, projectRoot, bundlerOptions: { isDev, externalsPreset } }); const output = await buildExternalDependencies(optimizedDependencyEntries, { externals: allExternals, packagesToTranspile, workspaceMap, rootDir: workspaceRoot || projectRoot, outputDir, bundlerOptions: { isDev, externalsPreset }, platform }); const moduleResolveMap2 = /* @__PURE__ */ new Map(); const filteredChunks = output.filter((o) => o.type === "chunk"); for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) { for (const external of allExternals) { if (DEPS_TO_IGNORE.includes(external)) { continue; } const importer = findExternalImporter(o, external, filteredChunks); if (importer) { const fullPath = path__namespace.join(workspaceRoot || projectRoot, importer.fileName); let innerMap = moduleResolveMap2.get(fullPath); if (!innerMap) { innerMap = /* @__PURE__ */ new Map(); moduleResolveMap2.set(fullPath, innerMap); } if (importer.moduleIds.length) { innerMap.set( external, importer.moduleIds[importer.moduleIds.length - 1]?.startsWith("\0virtual:#virtual") ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1] ); } } } } const usedExternals = /* @__PURE__ */ Object.create(null); for (const [fullPath, innerMap] of moduleResolveMap2) { const innerObj = /* @__PURE__ */ Object.create(null); for (const [external, value] of innerMap) { innerObj[external] = value; } usedExternals[fullPath] = innerObj; } if (extractedExternals.size > 0) { const syntheticPath = path__namespace.join(workspaceRoot || projectRoot, "__externals__"); const externalsObj = /* @__PURE__ */ Object.create(null); for (const [dep, rootPath] of extractedExternals) { externalsObj[dep] = rootPath; } usedExternals[syntheticPath] = externalsObj; } return { output, fileNameToDependencyMap, usedExternals }; } function checkConfigExport(result) { const t2 = babel2__namespace.default.types; const mastraVars = /* @__PURE__ */ new Set(); return { visitor: { ExportNamedDeclaration(path2) { const decl = path2.node.declaration; if (t2.isVariableDeclaration(decl)) { const varDecl = decl.declarations[0]; if (t2.isIdentifier(varDecl?.id, { name: "mastra" }) && t2.isNewExpression(varDecl.init) && t2.isIdentifier(varDecl.init.callee, { name: "Mastra" })) { result.hasValidConfig = true; } } if (Array.isArray(path2.node.specifiers)) { for (const spec of path2.node.specifiers) { if (t2.isExportSpecifier(spec) && t2.isIdentifier(spec.exported, { name: "mastra" }) && t2.isIdentifier(spec.local) && mastraVars.has(spec.local.name)) { result.hasValidConfig = true; } } } }, // For cases 2-4 we need to track whether those variables are assigned to `new Mastra()` VariableDeclaration(path2) { for (const decl of path2.node.declarations) { if (t2.isIdentifier(decl.id) && t2.isNewExpression(decl.init) && t2.isIdentifier(decl.init.callee, { name: "Mastra" })) { mastraVars.add(decl.id.name); } } } } }; } function getStringValue(node) { if (!node) return null; if (babel2.types.isStringLiteral(node)) { return node.value; } if (babel2.types.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) { return node.quasis[0]?.value.cooked ?? null; } return null; } function extractTargetFromProperty(prop) { if (!babel2.types.isObjectProperty(prop)) return null; const key = prop.key; if (babel2.types.isIdentifier(key, { name: "target" }) || babel2.types.isStringLiteral(key) && key.value === "target") { return getStringValue(prop.value); } return null; } function isBindingFromPino(path2, identifierName) { const binding = path2.scope.getBinding(identifierName); if (!binding) { return identifierName === "pino"; } const bindingPath = binding.path; if (bindingPath.isImportDefaultSpecifier()) { const importDecl = bindingPath.parentPath; if (importDecl?.isImportDeclaration()) { return importDecl.node.source.value === "pino"; } } if (bindingPath.isImportNamespaceSpecifier()) { const importDecl = bindingPath.parentPath; if (importDecl?.isImportDeclaration()) { return importDecl.node.source.value === "pino"; } } if (bindingPath.isImportSpecifier()) { const importDecl = bindingPath.parentPath; if (importDecl?.isImportDeclaration() && importDecl.node.source.value === "pino") { const imported = bindingPath.node.imported; if (babel2.types.isIdentifier(imported) && imported.name === "default") return true; if (babel2.types.isStringLiteral(imported) && imported.value === "default") return true; } return false; } if (bindingPath.isVariableDeclarator()) { const init = bindingPath.node.init; if (babel2.types.isCallExpression(init) && babel2.types.isIdentifier(init.callee, { name: "require" }) && init.arguments.length === 1 && babel2.types.isStringLiteral(init.arguments[0]) && init.arguments[0].value === "pino") { return true; } } return false; } function isPinoTransportCall(path2) { const callee = path2.node.callee; if (!babel2.types.isMemberExpression(callee)) return false; if (!babel2.types.isIdentifier(callee.property, { name: "transport" })) return false; if (babel2.types.isIdentifier(callee.object)) { return isBindingFromPino(path2, callee.object.name); } if (babel2.types.isMemberExpression(callee.object) && babel2.types.isIdentifier(callee.object.object) && babel2.types.isIdentifier(callee.object.property, { name: "default" })) { return isBindingFromPino(path2, callee.object.object.name); } return false; } function extractTransportsFromArg(arg) { const targets = []; if (!babel2.types.isObjectExpression(arg)) return targets; for (const prop of arg.properties) { if (!babel2.types.isObjectProperty(prop)) continue; const key = prop.key; const keyName = babel2.types.isIdentifier(key) ? key.name : babel2.types.isStringLiteral(key) ? key.value : null; if (keyName === "target") { const value = getStringValue(prop.value); if (value) { targets.push(value); } } else if (keyName === "targets") { if (babel2.types.isArrayExpression(prop.value)) { for (const element of prop.value.elements) { if (babel2.types.isObjectExpression(element)) { for (const innerProp of element.properties) { const targetValue = extractTargetFromProperty(innerProp); if (targetValue) { targets.push(targetValue); } } } } } } } return targets; } function detectPinoTransports(transports) { return { name: "detect-pino-transports", visitor: { CallExpression(path2) { if (!isPinoTransportCall(path2)) return; const firstArg = path2.node.arguments[0]; if (firstArg && !babel2.types.isSpreadElement(firstArg)) { for (const target of extractTransportsFromArg(firstArg)) { transports.add(target); } } } } }; } // src/build/analyze.ts function throwExternalDependencyError({ errorId, moduleName, packageName, messagePrefix }) { throw new error.MastraError({ id: errorId, domain: error.ErrorDomain.DEPLOYER, category: error.ErrorCategory.USER, details: { importFile: moduleName, packageName }, text: `${messagePrefix} \`${packageName}\` to your externals. export const mastra = new Mastra({ bundler: { externals: ["${packageName}"], } })` }); } function getPackageNameFromBundledModuleName(moduleName) { if (moduleName.includes("__")) { return moduleName.replaceAll("__", "/"); } const chunks = moduleName.split("-"); if (!chunks.length) { return moduleName; } if (chunks[0]?.startsWith("@")) { return chunks.slice(0, 2).join("/"); } return chunks[0]; } function validateError(err, file, { binaryMapData, workspaceMap }) { let moduleName = null; let errorConfig = null; if (err instanceof ValidationError) { const parsedStack = parse(err.stack); if (err.type === "TypeError") { const pkgNameRegex = /.*node_modules\/([^\/]+)\//; const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file)); if (stacktraceFrame) { const match = stacktraceFrame.file.match(pkgNameRegex); moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(path.basename(file.name)); } else { moduleName = getPackageNameFromBundledModuleName(path.basename(file.name)); } errorConfig = { id: "DEPLOYER_ANALYZE_TYPE_ERROR", messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add` }; } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) { moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1]; const parentModuleName = getPackageNameFromBundledModuleName(path.basename(file.name)); errorConfig = { id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND", messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add` }; if (moduleName === parentModuleName) { return; } } } if (err.message.includes("No native build was found")) { const pkgName = getPackageNameFromBundledModuleName(path.basename(file.name)); moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName; errorConfig = { id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD", messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add" }; } if (moduleName && workspaceMap.has(moduleName)) { throw new error.MastraError({ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE", domain: error.ErrorDomain.DEPLOYER, category: error.ErrorCategory.USER, details: { // importFile: moduleName, packageName: moduleName }, text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error. Error: ${err.stack}` }); } if (errorConfig && moduleName) { throwExternalDependencyError({ errorId: errorConfig.id, moduleName, packageName: moduleName, messagePrefix: errorConfig.messagePrefix }); } } async function validateFile(root, file, { binaryMapData, moduleResolveMapLocation, logger, workspaceMap, stubbedExternals }) { try { if (!file.isDynamicEntry && file.isEntry) { await validate(path.join(root, file.fileName), { moduleResolveMapLocation, injectESMShim: false, stubbedExternals }); } } catch (err) { let errorToHandle = err; if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) { try { await validate(path.join(root, file.fileName), { moduleResolveMapLocation, injectESMShim: true, stubbedExternals }); errorToHandle = null; } catch (err2) { errorToHandle = err2; } } if (errorToHandle instanceof Error) { validateError(errorToHandle, file, { binaryMapData, workspaceMap }); } } } async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals, outputDir, projectRoot, workspaceMap, depsVersionInfo }, logger) { const result = { dependencies: /* @__PURE__ */ new Map(), externalDependencies: /* @__PURE__ */ new Map(), workspaceMap }; for (const deps of Object.values(usedExternals)) { for (const dep of Object.keys(deps)) { if (chunk3T7FP546_cjs.isExternalProtocolImport(dep)) { continue; } const pkgName = chunk3T7FP546_cjs.getPackageName(dep); if (pkgName) { const versionInfo = depsVersionInfo.get(dep) || depsVersionInfo.get(pkgName) || {}; result.externalDependencies.set(pkgName, versionInfo); } } } let binaryMapData = {}; if (fs.existsSync(path.join(outputDir, "binary-map.json"))) { const binaryMap = await promises.readFile(path.join(outputDir, "binary-map.json"), "utf-8"); binaryMapData = JSON.parse(binaryMap); } for (const file of output) { if (file.type === "asset") { continue; } logger.debug("Validating module", { fileName: file.fileName }); if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) { result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName); } await validateFile(projectRoot, file, { binaryMapData, moduleResolveMapLocation: path.join(outputDir, "module-resolve-map.json"), logger, workspaceMap, stubbedExternals: [...GLOBAL_EXTERNALS, ...DEPS_TO_IGNORE] }); } return result; } async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, platform, isDev = false, bundlerOptions }, logger) { const mastraConfig = await promises.readFile(mastraEntry, "utf-8"); const mastraConfigResult = { hasValidConfig: false }; await babel2__namespace.transformAsync(mastraConfig, { filename: mastraEntry, presets: [undefined("@babel/preset-typescript")], plugins: [checkConfigExport(mastraConfigResult)] }); if (!mastraConfigResult.hasValidConfig) { logger.warn("Invalid Mastra config", { details: "Please make sure that your entry file looks like this:\nexport const mastra = new Mastra({\n // your options\n})\n\nIf you think your configuration is valid, please open an issue." }); } const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry }); let externalsPreset = false; const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : []; const userDynamicPackages = bundlerOptions?.dynamicPackages ?? []; if (bundlerOptions?.externals === true) { externalsPreset = true; } let index = 0; const depsToOptimize = /* @__PURE__ */ new Map(); const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean); const detectedPinoTransports = /* @__PURE__ */ new Set(); logger.info("Analyzing dependencies..."); const allUsedExternals = /* @__PURE__ */ new Map(); const analyzeCache = /* @__PURE__ */ new Map(); for (const entry of entries) { const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry); const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, { logger, sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false, workspaceMap, projectRoot, shouldCheckTransitiveDependencies: isDev || externalsPreset, analyzeCache }); babel2__namespace.transformSync(analyzeResult.output.code, { filename: "pino-detection.js", plugins: [detectPinoTransports(detectedPinoTransports)], configFile: false, babelrc: false }); await promises.writeFile(path.join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code); for (const [dep, metadata] of analyzeResult.dependencies.entries()) { const isPartOfExternals = allExternals.some((external) => chunk3T7FP546_cjs.isDependencyPartOfPackage(dep, external)); if (isPartOfExternals || externalsPreset && !metadata.isWorkspace) { const pkgName = chunk3T7FP546_cjs.getPackageName(dep); if (pkgName && !allUsedExternals.has(pkgName)) { allUsedExternals.set(pkgName, { version: metadata.version }); } continue; } if (depsToOptimize.has(dep)) { const existingEntry = depsToOptimize.get(dep); depsToOptimize.set(dep, { ...existingEntry, exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...metadata.exports])] }); } else { depsToOptimize.set(dep, metadata); } } } if (isDev || externalsPreset) { for (const [dep, metadata] of depsToOptimize.entries()) { if (!metadata.isWorkspace) { depsToOptimize.delete(dep); } } } const sortedDeps = Array.from(depsToOptimize.keys()).sort(); logger.info("Optimizing dependencies..."); logger.debug("Sorted dependencies", { deps: sortedDeps }); const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, { bundlerOptions: { ...bundlerOptions, externals: bundlerOptions?.externals ?? allExternals, isDev }, projectRoot, workspaceRoot, workspaceMap, platform }); const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map( (pkgInfo) => chunk3T7FP546_cjs.slash(path.relative(workspaceRoot || projectRoot, pkgInfo.location)) ); const depsVersionInfo = /* @__PURE__ */ new Map(); for (const [dep, metadata] of depsToOptimize.entries()) { const pkgName = chunk3T7FP546_cjs.getPackageName(dep); if (pkgName && metadata.version) { depsVersionInfo.set(pkgName, { version: metadata.version }); } if (metadata.version) { depsVersionInfo.set(dep, { version: metadata.version }); } } for (const o of output) { if (o.type === "asset") { continue; } for (const i of o.imports) { if (chunk3T7FP546_cjs.isBuiltinModule(i)) { continue; } if (i.startsWith(".") || i.startsWith("/")) { continue; } if (!chunk3T7FP546_cjs.isBareModuleSpecifier(i) || chunk3T7FP546_cjs.isExternalProtocolImport(i)) { continue; } if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) { continue; } const pkgName = chunk3T7FP546_cjs.getPackageName(i); if (pkgName && !allUsedExternals.has(pkgName)) { const versionInfo = depsVersionInfo.get(i) || depsVersionInfo.get(pkgName) || {}; allUsedExternals.set(pkgName, versionInfo); } } } const result = await validateOutput( { output, reverseVirtualReferenceMap: fileNameToDependencyMap, usedExternals, outputDir, projectRoot: workspaceRoot || projectRoot, workspaceMap, depsVersionInfo }, logger ); const mergedExternalDeps = new Map(result.externalDependencies); for (const [dep, info] of allUsedExternals) { if (chunk3T7FP546_cjs.isExternalProtocolImport(dep)) { continue; } const existing = mergedExternalDeps.get(dep); if (!existing || !existing.version && info.version) { mergedExternalDeps.set(dep, info); } } for (const transport of detectedPinoTransports) { if (!mergedExternalDeps.has(transport)) { mergedExternalDeps.set(transport, {}); } } for (const pkg2 of userDynamicPackages) { if (!mergedExternalDeps.has(pkg2)) { mergedExternalDeps.set(pkg2, {}); } } return { ...result, externalDependencies: mergedExternalDeps }; } exports.aliasHono = aliasHono; exports.analyzeBundle = analyzeBundle; exports.getWorkspaceInformation = getWorkspaceInformation; //# sourceMappingURL=chunk-U5HOHRPU.cjs.map //# sourceMappingURL=chunk-U5HOHRPU.cjs.map