@mastra/deployer 1.80.0-alpha.0 → 1.80.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/{analyze-DzJoNBCX.js → analyze-DhTwbIGn.js} +3 -3
  2. package/dist/{analyze-DzJoNBCX.js.map → analyze-DhTwbIGn.js.map} +1 -1
  3. package/dist/{analyze-B4cKPVju.cjs → analyze-jJAydlIl.cjs} +3 -3
  4. package/dist/{analyze-B4cKPVju.cjs.map → analyze-jJAydlIl.cjs.map} +1 -1
  5. package/dist/build/analyze.cjs +1 -1
  6. package/dist/build/analyze.js +1 -1
  7. package/dist/build/bundler.cjs +1 -1
  8. package/dist/build/bundler.js +1 -1
  9. package/dist/build/index.cjs +5 -5
  10. package/dist/build/index.js +5 -5
  11. package/dist/{build-DZuiBxfv.js → build-Ch38BMkf.js} +5 -5
  12. package/dist/{build-DZuiBxfv.js.map → build-Ch38BMkf.js.map} +1 -1
  13. package/dist/{build-D0odKdrs.cjs → build-ClcuWPJW.cjs} +5 -5
  14. package/dist/{build-D0odKdrs.cjs.map → build-ClcuWPJW.cjs.map} +1 -1
  15. package/dist/bundler/index.cjs +4 -4
  16. package/dist/bundler/index.js +4 -4
  17. package/dist/{bundler-Dpd5nkcu.cjs → bundler-3xwX-u2Y.cjs} +2 -2
  18. package/dist/bundler-3xwX-u2Y.cjs.map +1 -0
  19. package/dist/{bundler-BUqyRuGu.js → bundler-Xbu98oe6.js} +2 -2
  20. package/dist/bundler-Xbu98oe6.js.map +1 -0
  21. package/dist/{bundlerOptions-DHcbcD1a.cjs → bundlerOptions-DVHKdYsv.cjs} +2 -2
  22. package/dist/{bundlerOptions-DHcbcD1a.cjs.map → bundlerOptions-DVHKdYsv.cjs.map} +1 -1
  23. package/dist/{bundlerOptions-DMxva0Sp.js → bundlerOptions-lxkzE0Jg.js} +2 -2
  24. package/dist/{bundlerOptions-DMxva0Sp.js.map → bundlerOptions-lxkzE0Jg.js.map} +1 -1
  25. package/dist/docs/SKILL.md +1 -1
  26. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  27. package/dist/index.cjs +3 -3
  28. package/dist/index.js +3 -3
  29. package/dist/services/deps.d.ts.map +1 -1
  30. package/dist/services/index.cjs +1 -1
  31. package/dist/services/index.js +1 -1
  32. package/dist/{services-CzhmXlRZ.cjs → services-CCa8HFrE.cjs} +3 -7
  33. package/dist/{services-CzhmXlRZ.cjs.map → services-CCa8HFrE.cjs.map} +1 -1
  34. package/dist/{services-Imf20x6f.js → services-DahfG_xq.js} +3 -7
  35. package/dist/{services-Imf20x6f.js.map → services-DahfG_xq.js.map} +1 -1
  36. package/package.json +12 -12
  37. package/dist/bundler-BUqyRuGu.js.map +0 -1
  38. package/dist/bundler-Dpd5nkcu.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"services-Imf20x6f.js","names":[],"sources":["../src/deploy/log.ts","../src/services/deps.ts","../src/services/env.ts","../src/services/fs.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { Writable } from 'node:stream';\nimport type { IMastraLogger } from '@mastra/core/logger';\n\nexport const createPinoStream = (logger: IMastraLogger) => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n console.info(line);\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\n/**\n * Args are joined into a shell command (`shell: true` is required for package\n * manager shims on Windows), so only allow characters that appear in package\n * specifiers and CLI flags — never shell metacharacters (CodeQL\n * js/shell-command-constructed-from-input).\n */\nconst SAFE_SHELL_ARG = /^[\\w@%+=:,./^~-]*$/;\n\nexport function createChildProcessLogger({ logger, root }: { logger: IMastraLogger; root: string }) {\n const pinoStream = createPinoStream(logger);\n return async ({ cmd, args, env }: { cmd: string; args: string[]; env: Record<string, string> }) => {\n try {\n for (const arg of args) {\n if (!SAFE_SHELL_ARG.test(arg)) {\n throw new Error(`Refusing to pass unsafe argument to shell command: ${JSON.stringify(arg)}`);\n }\n }\n const subprocess = spawn(cmd, args, {\n cwd: root,\n shell: true,\n env,\n // No stdin for the child process — it doesn't need interactive input\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n subprocess.stdout?.on('data', chunk => {\n stdout += chunk.toString();\n });\n subprocess.stderr?.on('data', chunk => {\n stderr += chunk.toString();\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n // Wait for the process to complete\n return new Promise((resolve, reject) => {\n subprocess.on('close', code => {\n pinoStream.end();\n if (code === 0) {\n resolve({ success: true, stdout, stderr });\n } else {\n reject(Object.assign(new Error(`Process exited with code ${code}`), { stdout, stderr }));\n }\n });\n\n subprocess.on('error', error => {\n pinoStream.end();\n logger.error('Process failed', { error });\n reject(error);\n });\n });\n } catch (error) {\n console.error(error);\n logger.error('Process failed', { error });\n pinoStream.end();\n return { success: false, error };\n }\n };\n}\n","import fs from 'node:fs';\nimport fsPromises from 'node:fs/promises';\nimport path, { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { MastraBase } from '@mastra/core/base';\nimport type { BundlerConfig } from '@mastra/core/bundler';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { readJSON, writeJSON, ensureFile } from 'fs-extra/esm';\nimport type { PackageJson } from 'type-fest';\nimport { parse, stringify } from 'yaml';\n\nimport { createChildProcessLogger } from '../deploy/log.js';\n\ntype PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';\n\n/** Version used to pack private workspace packages whose package.json has no `version`. */\nexport const WORKSPACE_PLACEHOLDER_VERSION = '0.0.0';\n\n// Write via temp file + rename so an interrupted write never leaves a truncated manifest.\nasync function writeManifestAtomically(manifestPath: string, contents: string, inFlight?: Set<string>) {\n const tmpPath = `${manifestPath}.${process.pid}.${Date.now()}.tmp`;\n inFlight?.add(tmpPath);\n try {\n const { mode } = await fsPromises.stat(manifestPath);\n await fsPromises.writeFile(tmpPath, contents, { mode });\n await fsPromises.chmod(tmpPath, mode);\n await fsPromises.rename(tmpPath, manifestPath);\n } catch (error) {\n await fsPromises.rm(tmpPath, { force: true });\n throw error;\n } finally {\n inFlight?.delete(tmpPath);\n }\n}\n\n/**\n * Package managers refuse to pack a manifest without a version, and pnpm/bun also\n * resolve `workspace:` ranges from the dependency's manifest. So every versionless\n * package in `dirs` gets the placeholder version for the whole of `operation`, and\n * the original manifests are restored afterwards — also on SIGINT/SIGTERM.\n */\nexport async function withPlaceholderVersions<T>(dirs: string[], operation: () => Promise<T>): Promise<T> {\n const acquired: string[] = [];\n try {\n for (const dir of new Set(dirs.map(dir => path.resolve(dir)))) {\n const manifestPath = path.join(dir, 'package.json');\n let lease = placeholderLeases.get(manifestPath);\n // A lease whose last owner is restoring it can't be joined; wait and start a fresh one.\n while (lease?.releasing) {\n await lease.releasing.catch(() => {});\n lease = placeholderLeases.get(manifestPath);\n }\n if (lease) {\n lease.refs++;\n } else {\n lease = { refs: 1, injected: false, ready: Promise.resolve() };\n lease.ready = injectPlaceholderVersion(manifestPath, lease);\n placeholderLeases.set(manifestPath, lease);\n installSignalHandlers();\n }\n acquired.push(manifestPath);\n await lease.ready;\n }\n return await operation();\n } finally {\n try {\n for (const manifestPath of acquired) {\n await releasePlaceholderVersion(manifestPath);\n }\n } finally {\n if (placeholderLeases.size === 0) {\n removeSignalHandlers();\n }\n }\n }\n}\n\ninterface PlaceholderLease {\n refs: number;\n original?: string;\n injected: boolean;\n ready: Promise<void>;\n releasing?: Promise<void>;\n}\n\n// Shared across calls so one bundle can't restore a manifest another is still packing.\nconst placeholderLeases = new Map<string, PlaceholderLease>();\nconst inFlightTmpPaths = new Set<string>();\n\nasync function injectPlaceholderVersion(manifestPath: string, lease: PlaceholderLease) {\n const original = await fsPromises.readFile(manifestPath, 'utf-8').catch(() => undefined);\n if (original === undefined) return;\n let manifest: PackageJson;\n try {\n manifest = JSON.parse(original) as PackageJson;\n } catch (error) {\n throw new Error(`Failed to parse ${manifestPath}: ${(error as Error).message}`, { cause: error });\n }\n if (manifest.version) return;\n lease.original = original;\n // Mark before writing so a signal mid-write still restores this manifest.\n lease.injected = true;\n await writeManifestAtomically(\n manifestPath,\n JSON.stringify({ ...manifest, version: WORKSPACE_PLACEHOLDER_VERSION }, null, 2) + '\\n',\n inFlightTmpPaths,\n );\n}\n\nasync function releasePlaceholderVersion(manifestPath: string) {\n const lease = placeholderLeases.get(manifestPath)!;\n if (--lease.refs > 0) return;\n lease.releasing = (async () => {\n await lease.ready.catch(() => {});\n try {\n if (lease.injected) {\n await writeManifestAtomically(manifestPath, lease.original!, inFlightTmpPaths);\n lease.injected = false;\n }\n } finally {\n placeholderLeases.delete(manifestPath);\n }\n })();\n await lease.releasing;\n}\n\nfunction restorePlaceholderVersionsSync() {\n // Removing in-flight temp files keeps them out of later tarballs and makes any\n // pending rename fail instead of overwriting the restored manifest.\n for (const tmpPath of inFlightTmpPaths) {\n fs.rmSync(tmpPath, { force: true });\n }\n inFlightTmpPaths.clear();\n for (const [manifestPath, lease] of placeholderLeases) {\n if (lease.injected) {\n fs.writeFileSync(manifestPath, lease.original!);\n lease.injected = false;\n }\n }\n}\n\nfunction onPlaceholderSignal(signal: NodeJS.Signals) {\n restorePlaceholderVersionsSync();\n removeSignalHandlers();\n process.kill(process.pid, signal);\n}\n\nfunction installSignalHandlers() {\n if (process.listeners('SIGINT').includes(onPlaceholderSignal)) return;\n process.once('SIGINT', onPlaceholderSignal);\n process.once('SIGTERM', onPlaceholderSignal);\n}\n\nfunction removeSignalHandlers() {\n process.off('SIGINT', onPlaceholderSignal);\n process.off('SIGTERM', onPlaceholderSignal);\n}\n\ninterface LockFileInfo {\n path: string;\n filename: string;\n packageManager: PackageManager;\n}\n\ninterface ArchitectureOptions {\n os?: string[];\n cpu?: string[];\n libc?: string[];\n}\n\ninterface InstallOptions extends ArchitectureOptions {\n pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'];\n pnpmOverrides?: Record<string, string>;\n pnpmNodeLinker?: 'hoisted';\n /** Patch key -> path relative to the output directory. */\n patchedDependencies?: Record<string, string>;\n}\n\nconst PNPM_PATCHES_DIR = 'pnpm-patches';\nconst BUN_PATCHES_DIR = 'bun-patches';\n\nconst PNPM_CONFIG_KEYS_TO_COPY = new Set([\n 'allowBuilds',\n 'onlyBuiltDependencies',\n 'ignoredBuiltDependencies',\n 'neverBuiltDependencies',\n 'minimumReleaseAge',\n 'minimumReleaseAgeExclude',\n 'trustPolicy',\n 'trustPolicyExclude',\n 'trustPolicyIgnoreAfter',\n 'supportedArchitectures',\n]);\n\n// supportedArchitectures is generated from deployer architecture targets, so it can't be set explicitly.\n// neverBuiltDependencies switches pnpm 10 into deny-list mode, which runs every build script it doesn't name.\nconst PNPM_EXPLICIT_SETTING_KEYS = new Set(\n [...PNPM_CONFIG_KEYS_TO_COPY, 'blockExoticSubdeps'].filter(\n key => key !== 'supportedArchitectures' && key !== 'neverBuiltDependencies',\n ),\n);\n\nfunction serializePnpmWorkspaceSettings(settings: BundlerConfig['pnpmWorkspaceSettings']) {\n // Untyped JS configs can pass undefined; treat it as omitted so the copied source setting survives.\n const definedSettings = Object.entries(settings ?? {}).filter(([, value]) => value !== undefined);\n return definedSettings.map(([key, value]) => {\n if (!PNPM_EXPLICIT_SETTING_KEYS.has(key)) {\n throw new MastraError({\n id: 'DEPLOYER_INVALID_PNPM_WORKSPACE_SETTING',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n text: `pnpm workspace setting ${JSON.stringify(key)} isn't supported in bundler.pnpmWorkspaceSettings. Supported settings: ${[...PNPM_EXPLICIT_SETTING_KEYS].join(', ')}.`,\n });\n }\n const block = stringify({ [key]: value }).trimEnd();\n validatePnpmBuildApprovals(key, block);\n return block;\n });\n}\n\nfunction getTopLevelYamlKey(line: string) {\n const match = /^(?!\\s)([\\w-]+):/.exec(line);\n return match?.[1];\n}\n\nconst PNPM_IGNORED_BUILDS_ERROR = 'ERR_PNPM_IGNORED_BUILDS';\n\nexport function getPnpmIgnoredBuildPackages(output: string): string[] {\n const match = new RegExp(`\\\\[?${PNPM_IGNORED_BUILDS_ERROR}\\\\]?[^\\\\n]*Ignored build scripts:\\\\s*([^\\\\n]+)`).exec(\n output,\n );\n if (!match?.[1]) return [];\n\n return match[1]\n .split(',')\n .map(specifier => specifier.trim())\n .filter(Boolean)\n .map(specifier => {\n if (specifier.startsWith('@')) {\n const versionSeparator = specifier.indexOf('@', 1);\n return versionSeparator === -1 ? specifier : specifier.slice(0, versionSeparator);\n }\n return specifier.split('@', 1)[0]!;\n });\n}\n\nfunction validatePnpmBuildApprovals(key: string, block: string): void {\n if (key !== 'allowBuilds' && key !== 'onlyBuiltDependencies') return;\n\n let value: unknown;\n try {\n value = (parse(block) as Record<string, unknown>)[key];\n } catch (error) {\n throw new MastraError(\n {\n id: 'DEPLOYER_INVALID_PNPM_BUILD_APPROVAL_CONFIG',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { key },\n text: `Invalid pnpm ${key} configuration`,\n },\n error,\n );\n }\n\n const invalidEntries =\n key === 'allowBuilds'\n ? value && typeof value === 'object' && !Array.isArray(value)\n ? Object.entries(value).filter(\n ([dependency, approval]) => dependency.trim().length === 0 || typeof approval !== 'boolean',\n )\n : [[key, value]]\n : Array.isArray(value) &&\n value.every(dependency => typeof dependency === 'string' && dependency.trim().length > 0)\n ? []\n : [[key, value]];\n\n if (invalidEntries.length === 0) return;\n const invalidEntryNames = invalidEntries.map(([entry]) => entry).join(', ');\n\n throw new MastraError({\n id: 'DEPLOYER_INVALID_PNPM_BUILD_APPROVAL_CONFIG',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { key, invalidEntries: invalidEntryNames },\n text: `Invalid pnpm ${key} entries: ${invalidEntryNames}`,\n });\n}\n\n/**\n * Reads the `patchedDependencies` map from a pnpm workspace file. Paths are returned as declared,\n * i.e. relative to the workspace root. Returns an empty map for absent or unusable declarations.\n */\nexport function parsePnpmPatchedDependencies(source: string): Record<string, string> {\n let parsed: unknown;\n try {\n parsed = parse(source);\n } catch {\n return {};\n }\n\n const patched = (parsed as { patchedDependencies?: unknown } | null)?.patchedDependencies;\n if (!patched || typeof patched !== 'object' || Array.isArray(patched)) {\n return {};\n }\n\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(patched as Record<string, unknown>)) {\n if (typeof value === 'string' && value.trim() && key.trim()) {\n result[key] = value.trim();\n }\n }\n\n return result;\n}\n\nexport function copyPnpmWorkspaceSettings(source: string, options: InstallOptions = {}) {\n const hasArchitecture = Boolean(options.os?.length || options.cpu?.length || options.libc?.length);\n const lines = source.split(/\\r?\\n/);\n const customBlocks = serializePnpmWorkspaceSettings(options.pnpmWorkspaceSettings);\n const blocks: string[] = [];\n\n for (let index = 0; index < lines.length;) {\n const key = getTopLevelYamlKey(lines[index] ?? '');\n if (!key) {\n index += 1;\n continue;\n }\n\n const start = index;\n index += 1;\n while (index < lines.length && !getTopLevelYamlKey(lines[index] ?? '')) {\n index += 1;\n }\n\n if (\n !PNPM_CONFIG_KEYS_TO_COPY.has(key) ||\n options.pnpmWorkspaceSettings?.[key] !== undefined ||\n (key === 'supportedArchitectures' && hasArchitecture)\n ) {\n continue;\n }\n\n const block = lines.slice(start, index).join('\\n').trimEnd();\n if (block) {\n validatePnpmBuildApprovals(key, block);\n blocks.push(block);\n }\n }\n\n if (hasArchitecture) {\n const architectureBlock = ['supportedArchitectures:'];\n if (options.os?.length) {\n architectureBlock.push(` os: ${JSON.stringify(options.os)}`);\n }\n if (options.cpu?.length) {\n architectureBlock.push(` cpu: ${JSON.stringify(options.cpu)}`);\n }\n if (options.libc?.length) {\n architectureBlock.push(` libc: ${JSON.stringify(options.libc)}`);\n }\n blocks.push(architectureBlock.join('\\n'));\n }\n\n if (options.pnpmOverrides && Object.keys(options.pnpmOverrides).length > 0) {\n blocks.push(\n [\n 'overrides:',\n ...Object.entries(options.pnpmOverrides).map(\n ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join('\\n'),\n );\n }\n\n if (options.patchedDependencies && Object.keys(options.patchedDependencies).length > 0) {\n blocks.push(\n [\n 'patchedDependencies:',\n ...Object.entries(options.patchedDependencies).map(\n ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join('\\n'),\n );\n // The bundled output only installs runtime dependencies, so patches declared for\n // dev-only or bundled-away packages are legitimately unused here.\n blocks.push('allowUnusedPatches: true');\n }\n\n if (options.pnpmNodeLinker) {\n blocks.push(`nodeLinker: ${options.pnpmNodeLinker}`);\n }\n\n return [\"packages:\\n - '.'\", ...blocks, ...customBlocks].join('\\n\\n') + '\\n';\n}\n\n// Semver characters only; versions are interpolated into a shell command.\nconst SAFE_PACKAGE_VERSION = /^[0-9A-Za-z.+-]+$/;\n\n/**\n * Yarn classic writes `# yarn lockfile v1` within the first two lines; Berry lockfiles never contain it.\n * Only the head of the file is read so large monorepo lockfiles are never loaded into memory.\n */\nasync function isYarnClassicLockfile(lockfilePath: string): Promise<boolean> {\n const handle = await fsPromises.open(lockfilePath, 'r');\n try {\n const buffer = Buffer.alloc(512);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n return /^# yarn lockfile v1\\r?$/m.test(buffer.toString('utf-8', 0, bytesRead));\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Removes overridden packages from every importer of a copied pnpm lockfile. When the Mastra app is the\n * workspace root, the root importer still resolves its workspace dependencies to `link:` versions. pnpm\n * keeps those versions although the output overrides them with packed tarballs, so the tarball is never\n * installed and the dependency symlink dangles. Without the entries, pnpm resolves them from the overrides.\n */\nasync function dropPnpmImporterDependencies(lockfilePath: string, packageNames: string[]): Promise<void> {\n const lockfile = parse(await fsPromises.readFile(lockfilePath, 'utf-8')) as {\n importers?: Record<string, Record<string, Record<string, unknown> | undefined> | undefined>;\n } | null;\n let changed = false;\n for (const importer of Object.values(lockfile?.importers ?? {})) {\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {\n const dependencies = importer?.[field];\n for (const name of packageNames) {\n if (dependencies && name in dependencies) {\n delete dependencies[name];\n changed = true;\n }\n }\n }\n }\n if (changed) {\n await fsPromises.writeFile(lockfilePath, stringify(lockfile, { lineWidth: 0 }));\n }\n}\n\nexport class Deps extends MastraBase {\n private packageManager: PackageManager;\n private rootDir: string;\n private lockFile: LockFileInfo | null;\n\n constructor(rootDir = process.cwd()) {\n super({ component: 'DEPLOYER', name: 'DEPS' });\n\n this.rootDir = rootDir;\n this.lockFile = this.findLockFile(rootDir);\n this.packageManager = this.lockFile?.packageManager ?? 'npm';\n }\n\n private findLockFile(dir: string): LockFileInfo | null {\n const lockFiles: Array<{ filename: string; packageManager: PackageManager }> = [\n { filename: 'pnpm-lock.yaml', packageManager: 'pnpm' },\n { filename: 'package-lock.json', packageManager: 'npm' },\n { filename: 'yarn.lock', packageManager: 'yarn' },\n { filename: 'bun.lock', packageManager: 'bun' },\n ];\n for (const lockFile of lockFiles) {\n const lockFilePath = path.join(dir, lockFile.filename);\n if (fs.existsSync(lockFilePath)) {\n return { ...lockFile, path: lockFilePath };\n }\n }\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findLockFile(parentDir);\n }\n return null;\n }\n\n public getWorkspaceDependencyPath({ pkgName, version }: { pkgName: string; version: string }) {\n return `file:./workspace-module/${pkgName}-${version}.tgz`;\n }\n\n public async pack({\n dir,\n destination,\n sanitizedName,\n version,\n }: {\n dir: string;\n destination: string;\n sanitizedName: string;\n version: string;\n }) {\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: dir,\n });\n\n let packCmd = 'pack';\n let destinationFlag = `--pack-destination ${destination}`;\n if (this.packageManager === 'yarn') {\n if (this.lockFile && (await isYarnClassicLockfile(this.lockFile.path))) {\n if (!SAFE_PACKAGE_VERSION.test(version)) {\n throw new MastraError({\n id: 'DEPLOYER_INVALID_WORKSPACE_PACKAGE_VERSION',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { dir, version: String(version) },\n text: `Invalid version ${JSON.stringify(version)} in workspace package at ${dir}`,\n });\n }\n // Yarn classic has no --out/%v; --filename takes the full output path.\n destinationFlag = `--filename ${destination}/${sanitizedName}-${version}.tgz`;\n } else {\n // %s includes an '@' at the start of packages names with an '@'\n // so we need to use our sanitizedName instead.\n destinationFlag = `--out ${destination}/${sanitizedName}-%v.tgz`;\n }\n }\n if (this.packageManager === 'bun') {\n // bun uses `pm pack` instead of `pack`\n packCmd = 'pm pack';\n // bun uses --destination instead of --pack-destination\n destinationFlag = `--destination ${destination}`;\n }\n\n return cpLogger({\n cmd: `${this.packageManager} ${packCmd} ${destinationFlag}`,\n args: [],\n env: {\n PATH: process.env.PATH!,\n },\n });\n }\n\n private findPnpmWorkspaceFile(dir: string): string | null {\n const workspaceYamlPath = path.join(dir, 'pnpm-workspace.yaml');\n if (fs.existsSync(workspaceYamlPath)) {\n return workspaceYamlPath;\n }\n\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findPnpmWorkspaceFile(parentDir);\n }\n\n return null;\n }\n\n private async writePnpmConfig(dir: string, options: InstallOptions = {}) {\n const sourceWorkspaceYamlPath = this.findPnpmWorkspaceFile(this.rootDir);\n const sourceWorkspaceYaml = sourceWorkspaceYamlPath\n ? await fsPromises.readFile(sourceWorkspaceYamlPath, 'utf-8')\n : '';\n\n const patchedDependencies = sourceWorkspaceYamlPath\n ? await this.copyPnpmPatches(sourceWorkspaceYaml, path.dirname(sourceWorkspaceYamlPath), dir)\n : undefined;\n\n await fsPromises.writeFile(\n path.join(dir, 'pnpm-workspace.yaml'),\n copyPnpmWorkspaceSettings(sourceWorkspaceYaml, { ...options, patchedDependencies }),\n 'utf-8',\n );\n }\n\n /**\n * Resolves a declared patch path against the source workspace and verifies that, once symlinks\n * are followed, it still resolves inside the workspace. Returns the real path to copy from, or\n * `undefined` when the patch escapes the workspace or its file cannot be resolved.\n */\n private async resolvePatchSource(\n resolvedWorkspaceRoot: string,\n declaredPath: string,\n { key, label }: { key: string; label: string },\n ): Promise<string | undefined> {\n const sourcePath = path.resolve(resolvedWorkspaceRoot, declaredPath);\n if (!sourcePath.startsWith(`${resolvedWorkspaceRoot}${path.sep}`)) {\n this.logger.warn(`Skipping ${label} patch for \"${key}\": patch file is outside the workspace at ${sourcePath}`);\n return undefined;\n }\n\n // A patch path can stay lexically under the workspace while traversing a symlink whose target\n // lives outside it. copyFile follows symlinks, so compare the resolved real paths before copying.\n let realWorkspaceRoot: string;\n let realSourcePath: string;\n try {\n [realWorkspaceRoot, realSourcePath] = await Promise.all([\n fsPromises.realpath(resolvedWorkspaceRoot),\n fsPromises.realpath(sourcePath),\n ]);\n } catch {\n this.logger.warn(`Skipping ${label} patch for \"${key}\": patch file not found at ${sourcePath}`);\n return undefined;\n }\n\n if (!realSourcePath.startsWith(`${realWorkspaceRoot}${path.sep}`)) {\n this.logger.warn(\n `Skipping ${label} patch for \"${key}\": patch file is outside the workspace at ${realSourcePath}`,\n );\n return undefined;\n }\n\n return realSourcePath;\n }\n\n /**\n * Copies the patch files declared by the source workspace into the output directory and returns\n * the patch map rewritten to output-relative paths, so the patches survive the output install.\n */\n private async copyPnpmPatches(\n sourceWorkspaceYaml: string,\n sourceWorkspaceRoot: string,\n dir: string,\n ): Promise<Record<string, string>> {\n const declared = parsePnpmPatchedDependencies(sourceWorkspaceYaml);\n const rewritten: Record<string, string> = {};\n const usedFileNames = new Set<string>();\n const resolvedWorkspaceRoot = path.resolve(sourceWorkspaceRoot);\n\n for (const [key, declaredPath] of Object.entries(declared)) {\n const sourcePath = await this.resolvePatchSource(resolvedWorkspaceRoot, declaredPath, {\n key,\n label: 'pnpm',\n });\n if (!sourcePath) continue;\n\n let fileName = path.basename(sourcePath);\n if (usedFileNames.has(fileName)) {\n fileName = `${key.replace(/[^a-zA-Z0-9._-]/g, '_')}-${fileName}`;\n }\n usedFileNames.add(fileName);\n\n await fsPromises.mkdir(path.join(dir, PNPM_PATCHES_DIR), { recursive: true });\n await fsPromises.copyFile(sourcePath, path.join(dir, PNPM_PATCHES_DIR, fileName));\n rewritten[key] = `${PNPM_PATCHES_DIR}/${fileName}`;\n }\n\n return rewritten;\n }\n\n /**\n * Writes the `.yarnrc.yml` for the bundled output, recording the supported architectures so the\n * output install only resolves optional native binaries that match the deployment target.\n */\n private async writeYarnConfig(dir: string, options: ArchitectureOptions) {\n const yarnrcPath = path.join(dir, '.yarnrc.yml');\n const config = {\n supportedArchitectures: {\n cpu: options.cpu || [],\n os: options.os || [],\n libc: options.libc || [],\n },\n };\n\n await fsPromises.writeFile(\n yarnrcPath,\n `supportedArchitectures:\\n${Object.entries(config.supportedArchitectures)\n .map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)\n .join('\\n')}`,\n );\n }\n\n /**\n * Copies the source workspace's `.yarn/patches/` directory (Yarn Berry) into the output\n * directory so patches survive the output install. Yarn auto-discovers patches from this\n * directory and applies them per the lockfile references.\n */\n private async copyYarnPatches(dir: string): Promise<void> {\n const sourcePatchesDir = path.join(this.rootDir, '.yarn', 'patches');\n if (!fs.existsSync(sourcePatchesDir)) return;\n\n const outputPatchesDir = path.join(dir, '.yarn', 'patches');\n await fsPromises.cp(sourcePatchesDir, outputPatchesDir, { recursive: true, errorOnExist: false });\n }\n\n /**\n * Copies the patch files referenced by the source workspace's `patchedDependencies` in\n * package.json into the output directory and returns the map rewritten to output-relative\n * paths, so bun patches survive the output install.\n */\n private async copyBunPatches(\n declared: Record<string, string>,\n sourceRoot: string,\n dir: string,\n ): Promise<Record<string, string>> {\n const rewritten: Record<string, string> = {};\n const usedFileNames = new Set<string>();\n const resolvedRoot = path.resolve(sourceRoot);\n\n for (const [key, declaredPath] of Object.entries(declared)) {\n const sourcePath = await this.resolvePatchSource(resolvedRoot, declaredPath, {\n key,\n label: 'bun',\n });\n if (!sourcePath) continue;\n\n let fileName = path.basename(sourcePath);\n if (usedFileNames.has(fileName)) {\n fileName = `${key.replace(/[^a-zA-Z0-9._-]/g, '_')}-${fileName}`;\n }\n usedFileNames.add(fileName);\n\n await fsPromises.mkdir(path.join(dir, BUN_PATCHES_DIR), { recursive: true });\n await fsPromises.copyFile(sourcePath, path.join(dir, BUN_PATCHES_DIR, fileName));\n rewritten[key] = `${BUN_PATCHES_DIR}/${fileName}`;\n }\n\n return rewritten;\n }\n\n /**\n * Reads `patchedDependencies` from the source package.json, copies the referenced patch\n * files into the output directory, and writes the output-relative patch map into the\n * output's package.json so `bun install` preserves patches in the bundled output.\n */\n private async copyBunPatchesToOutput(dir: string): Promise<void> {\n const sourcePackageJsonPath = path.join(this.rootDir, 'package.json');\n if (!fs.existsSync(sourcePackageJsonPath)) return;\n\n const sourcePkg = await readJSON(sourcePackageJsonPath);\n const patchedDeps = sourcePkg.patchedDependencies as Record<string, string> | undefined;\n if (!patchedDeps || Object.keys(patchedDeps).length === 0) return;\n\n const rewritten = await this.copyBunPatches(patchedDeps, this.rootDir, dir);\n if (Object.keys(rewritten).length === 0) return;\n\n const outputPackageJsonPath = path.join(dir, 'package.json');\n let outputPkg: Record<string, unknown>;\n try {\n outputPkg = (await readJSON(outputPackageJsonPath)) as Record<string, unknown>;\n } catch {\n outputPkg = {};\n }\n outputPkg.patchedDependencies = rewritten;\n await writeJSON(outputPackageJsonPath, outputPkg, { spaces: 2 });\n }\n\n private getNpmArgs(options: ArchitectureOptions): string[] {\n const args: string[] = [];\n if (options.cpu) args.push(`--cpu=${options.cpu.join(',')}`);\n if (options.os) args.push(`--os=${options.os.join(',')}`);\n if (options.libc) args.push(`--libc=${options.libc.join(',')}`);\n return args;\n }\n\n /**\n * Depending on whether we want to install or add a package, this function returns the appropriate commands.\n * All package managers support both commands (e.g. npm install has an alias on \"add\")\n */\n private getPackageManagerCommand(\n pm: PackageManager,\n type: 'install' | 'add',\n { yarnClassic = false }: { yarnClassic?: boolean } = {},\n ): string {\n const cmd = type === 'install' ? 'install' : 'add';\n\n switch (pm) {\n case 'npm':\n return `${cmd} --audit=false --fund=false --loglevel=error --progress=false --update-notifier=false`;\n case 'yarn':\n return type === 'install' && !yarnClassic ? `${cmd} --no-immutable` : cmd;\n case 'pnpm':\n return type === 'install' ? `${cmd} --no-frozen-lockfile --loglevel=error` : `${cmd} --loglevel=error`;\n default:\n return cmd;\n }\n }\n\n public async install({\n dir = this.rootDir,\n architecture,\n pnpmOverrides,\n pnpmNodeLinker,\n pnpmWorkspaceSettings,\n }: {\n dir?: string;\n architecture?: ArchitectureOptions;\n pnpmOverrides?: Record<string, string>;\n pnpmNodeLinker?: 'hoisted';\n pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'];\n } = {}) {\n const pm = this.packageManager;\n let yarnClassic = false;\n if (this.lockFile) {\n const destination = path.join(dir, this.lockFile.filename);\n if (path.resolve(this.lockFile.path) !== path.resolve(destination)) {\n const packedBunWorkspaces =\n pm === 'bun' &&\n fs.existsSync(path.join(dir, 'package.json')) &&\n Object.values(\n ((await readJSON(path.join(dir, 'package.json'))) as { resolutions?: Record<string, string> })\n .resolutions ?? {},\n ).some(spec => spec.startsWith('file:./workspace-module/'));\n\n if (packedBunWorkspaces) {\n // Bun cannot reuse the source workspace lockfile with packed tarballs; removing its workspace entries\n // makes Bun ignore it and regenerate the lockfile anyway. Start with a clean lockfile instead.\n await fsPromises.rm(destination, { force: true });\n } else {\n await fsPromises.copyFile(this.lockFile.path, destination);\n if (pm === 'pnpm' && pnpmOverrides && Object.keys(pnpmOverrides).length > 0) {\n await dropPnpmImporterDependencies(destination, Object.keys(pnpmOverrides));\n }\n }\n }\n\n if (pm === 'yarn') {\n yarnClassic = await isYarnClassicLockfile(destination);\n }\n }\n\n const installCommand = this.getPackageManagerCommand(pm, 'install', { yarnClassic });\n let args: string[] = [];\n\n switch (pm) {\n case 'pnpm':\n await this.writePnpmConfig(dir, { ...architecture, pnpmOverrides, pnpmNodeLinker, pnpmWorkspaceSettings });\n break;\n case 'yarn':\n // similar to --ignore-workspace but for yarn\n await ensureFile(path.join(dir, 'yarn.lock'));\n if (architecture) {\n await this.writeYarnConfig(dir, architecture);\n }\n await this.copyYarnPatches(dir);\n break;\n case 'bun':\n await this.copyBunPatchesToOutput(dir);\n break;\n case 'npm':\n if (architecture) {\n args = this.getNpmArgs(architecture);\n }\n break;\n default:\n // Do nothing\n }\n\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: dir,\n });\n\n try {\n return await cpLogger({\n cmd: `${pm} ${installCommand}`,\n args,\n env: process.env as Record<string, string>,\n });\n } catch (error) {\n if (pm !== 'pnpm') throw error;\n\n const processOutput =\n error && typeof error === 'object'\n ? `${'stdout' in error ? String(error.stdout) : ''}\\n${'stderr' in error ? String(error.stderr) : ''}`\n : '';\n const ignoredPackages = getPnpmIgnoredBuildPackages(processOutput);\n if (ignoredPackages.length === 0) throw error;\n\n throw new MastraError(\n {\n id: 'DEPLOYER_PNPM_IGNORED_BUILDS',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { packageNames: ignoredPackages.join(', ') },\n text: `pnpm blocked build scripts for: ${ignoredPackages.join(', ')}. Add these packages to allowBuilds in pnpm-workspace.yaml and retry the build.`,\n },\n error,\n );\n }\n }\n\n public async installPackages(packages: string[]) {\n const pm = this.packageManager;\n const installCommand = this.getPackageManagerCommand(pm, 'add');\n\n const env: Record<string, string> = {\n PATH: process.env.PATH!,\n };\n\n if (process.env.npm_config_registry) {\n env.npm_config_registry = process.env.npm_config_registry;\n }\n\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: '',\n });\n\n return cpLogger({\n cmd: `${pm} ${installCommand}`,\n args: packages,\n env,\n });\n }\n\n public async checkDependencies(dependencies: string[]): Promise<string> {\n try {\n const packageJsonPath = path.join(this.rootDir, 'package.json');\n\n try {\n await fsPromises.access(packageJsonPath);\n } catch {\n return 'No package.json file found in the current directory';\n }\n\n const packageJson = await readJSON(packageJsonPath);\n for (const dependency of dependencies) {\n if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {\n return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;\n }\n }\n\n return 'ok';\n } catch (err) {\n console.error(err);\n return 'Could not check dependencies';\n }\n }\n\n public async getProjectName() {\n try {\n const packageJsonPath = path.join(this.rootDir, 'package.json');\n const pkg = await readJSON(packageJsonPath);\n return pkg.name;\n } catch (err) {\n throw err;\n }\n }\n\n public async getPackageVersion() {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkgJsonPath = path.join(__dirname, '..', '..', 'package.json');\n\n const content = (await readJSON(pkgJsonPath)) as PackageJson;\n return content.version;\n }\n\n public async addScriptsToPackageJson(scripts: Record<string, string>) {\n const packageJson = await readJSON('package.json');\n packageJson.scripts = {\n ...packageJson.scripts,\n ...scripts,\n };\n await writeJSON('package.json', packageJson, { spaces: 2 });\n }\n}\n\nexport class DepsService extends Deps {}\n","import * as fs from 'node:fs';\n\nexport abstract class EnvService {\n abstract getEnvValue(key: string): Promise<string | null>;\n abstract setEnvValue(key: string, value: string): Promise<void>;\n}\n\nexport class FileEnvService extends EnvService {\n private filePath: string;\n\n constructor(filePath: string) {\n super();\n this.filePath = filePath;\n }\n\n private readFile(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n fs.readFile(filePath, 'utf8', (err: NodeJS.ErrnoException | null, data: string) => {\n if (err) reject(err);\n else resolve(data);\n });\n });\n }\n\n private writeFile({ filePath, data }: { filePath: string; data: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n fs.writeFile(filePath, data, 'utf8', (err: NodeJS.ErrnoException | null) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n private async updateEnvData({\n key,\n value,\n filePath = this.filePath,\n data,\n }: {\n key: string;\n value: string;\n filePath?: string;\n data: string;\n }): Promise<string> {\n const regex = new RegExp(`^${key}=.*$`, 'm');\n if (data.match(regex)) {\n // Use a replacement function so `$` sequences in the value (e.g. `$&`,\n // `$$`) are written literally instead of being interpreted as\n // String.prototype.replace special patterns.\n data = data.replace(regex, () => `${key}=${value}`);\n } else {\n data += `\\n${key}=${value}`;\n }\n await this.writeFile({ filePath, data });\n console.info(`${key} set to ${value} in ENV file.`);\n return data;\n }\n\n async getEnvValue(key: string): Promise<string | null> {\n try {\n const data = await this.readFile(this.filePath);\n const regex = new RegExp(`^${key}=(.*)$`, 'm');\n const match = data.match(regex);\n return match?.[1] || null;\n } catch (err) {\n console.error(`Error reading ENV value: ${err}`);\n return null;\n }\n }\n\n async setEnvValue(key: string, value: string): Promise<void> {\n try {\n const data = await this.readFile(this.filePath);\n await this.updateEnvData({ key, value, data });\n } catch (err) {\n console.error(`Error writing ENV value: ${err}`);\n }\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport fsExtra from 'fs-extra/esm';\n\nimport { FileEnvService } from './env.js';\n\nexport class FileService {\n /**\n *\n * @param inputFile the file in the starter files directory to copy\n * @param outputFilePath the destination path\n * @param replaceIfExists flag to replace if it exists\n * @returns\n */\n public async copyStarterFile(inputFile: string, outputFilePath: string, replaceIfExists?: boolean) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n const filePath = path.resolve(__dirname, '..', 'starter-files', inputFile);\n const fileString = fs.readFileSync(filePath, 'utf8');\n\n if (fs.existsSync(outputFilePath) && !replaceIfExists) {\n console.info(`${outputFilePath} already exists`);\n return false;\n }\n\n await fsExtra.outputFile(outputFilePath, fileString);\n\n return true;\n }\n\n public async setupEnvFile({ dbUrl }: { dbUrl: string }) {\n const envPath = path.join(process.cwd(), '.env.development');\n\n await fsExtra.ensureFile(envPath);\n\n const fileEnvService = new FileEnvService(envPath);\n await fileEnvService.setEnvValue('DB_URL', dbUrl);\n }\n\n public getFirstExistingFile(files: string[]): string {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n throw new Error('Missing required file, checked the following paths: ' + files.join(', '));\n }\n\n /**\n * Returns every existing file from the provided array in the same order.\n * Callers supply files from the lowest to highest precedence so later dotenv\n * files override earlier values when the bundler loads them.\n */\n public getExistingFiles(files: string[]): string[] {\n return files.filter(file => fs.existsSync(file));\n }\n\n /**\n * Returns the first existing file from the provided array, or undefined if none exist\n * @param files array of file paths to check\n * @returns the first existing file path or undefined\n */\n public getFirstExistingFileOrUndefined(files: string[]): string | undefined {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n return undefined;\n }\n\n public replaceValuesInFile({\n filePath,\n replacements,\n }: {\n filePath: string;\n replacements: { search: string; replace: string }[];\n }) {\n let fileContent = fs.readFileSync(filePath, 'utf8');\n replacements.forEach(({ search, replace }) => {\n fileContent = fileContent.replaceAll(search, replace);\n });\n\n fs.writeFileSync(filePath, fileContent);\n }\n}\n"],"mappings":";;;;;;;;;;;AAIA,MAAa,oBAAoB,WAA0B;CACzD,OAAO,IAAI,SAAS,EAClB,MAAM,OAAO,WAAW,UAAU;EAEhC,MAAM,OAAO,MAAM,SAAS,CAAC,CAAC,KAAK;EAEnC,IAAI,MAAM;GACR,QAAQ,KAAK,IAAI;GAEjB,OAAO,KAAK,IAAI;EAClB;EAEA,SAAS;CACX,EACF,CAAC;AACH;;;;;;;AAQA,MAAM,iBAAiB;AAEvB,SAAgB,yBAAyB,EAAE,QAAQ,QAAiD;CAClG,MAAM,aAAa,iBAAiB,MAAM;CAC1C,OAAO,OAAO,EAAE,KAAK,MAAM,UAAwE;EACjG,IAAI;GACF,KAAK,MAAM,OAAO,MAChB,IAAI,CAAC,eAAe,KAAK,GAAG,GAC1B,MAAM,IAAI,MAAM,sDAAsD,KAAK,UAAU,GAAG,GAAG;GAG/F,MAAM,aAAa,MAAM,KAAK,MAAM;IAClC,KAAK;IACL,OAAO;IACP;IAEA,OAAO;KAAC;KAAU;KAAQ;IAAM;G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AAU,MAAM;EAEnD,IAAI,GAAG,WAAW,cAAc,KAAK,CAAC,iBAAiB;GACrD,QAAQ,KAAK,GAAG,eAAe,gBAAgB;GAC/C,OAAO;EACT;EAEA,MAAM,QAAQ,WAAW,gBAAgB,UAAU;EAEnD,OAAO;CACT;CAEA,MAAa,aAAa,EAAE,SAA4B;EACtD,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI,GAAG,kBAAkB;EAE3D,MAAM,QAAQ,WAAW,OAAO;EAGhC,MAAM,IADqB,eAAe,OACvB,CAAC,CAAC,YAAY,UAAU,KAAK;CAClD;CAEA,qBAA4B,OAAyB;EACnD,KAAK,MAAM,KAAK,OACd,IAAI,GAAG,WAAW,CAAC,GACjB,OAAO;EAIX,MAAM,IAAI,MAAM,yDAAyD,MAAM,KAAK,IAAI,CAAC;CAC3F;;;;;;CAOA,iBAAwB,OAA2B;EACjD,OAAO,MAAM,QAAO,SAAQ,GAAG,WAAW,IAAI,CAAC;CACjD;;;;;;CAOA,gCAAuC,OAAqC;EAC1E,KAAK,MAAM,KAAK,OACd,IAAI,GAAG,WAAW,CAAC,GACjB,OAAO;CAKb;CAEA,oBAA2B,EACzB,UACA,gBAIC;EACD,IAAI,cAAc,GAAG,aAAa,UAAU,MAAM;EAClD,aAAa,SAAS,EAAE,QAAQ,cAAc;GAC5C,cAAc,YAAY,WAAW,QAAQ,OAAO;EACtD,CAAC;EAED,GAAG,cAAc,UAAU,WAAW;CACxC;AACF"}
1
+ {"version":3,"file":"services-DahfG_xq.js","names":[],"sources":["../src/deploy/log.ts","../src/services/deps.ts","../src/services/env.ts","../src/services/fs.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { Writable } from 'node:stream';\nimport type { IMastraLogger } from '@mastra/core/logger';\n\nexport const createPinoStream = (logger: IMastraLogger) => {\n return new Writable({\n write(chunk, _encoding, callback) {\n // Convert Buffer/string to string and trim whitespace\n const line = chunk.toString().trim();\n\n if (line) {\n console.info(line);\n // Log each line through Pino\n logger.info(line);\n }\n\n callback();\n },\n });\n};\n\n/**\n * Args are joined into a shell command (`shell: true` is required for package\n * manager shims on Windows), so only allow characters that appear in package\n * specifiers and CLI flags — never shell metacharacters (CodeQL\n * js/shell-command-constructed-from-input).\n */\nconst SAFE_SHELL_ARG = /^[\\w@%+=:,./^~-]*$/;\n\nexport function createChildProcessLogger({ logger, root }: { logger: IMastraLogger; root: string }) {\n const pinoStream = createPinoStream(logger);\n return async ({ cmd, args, env }: { cmd: string; args: string[]; env: Record<string, string> }) => {\n try {\n for (const arg of args) {\n if (!SAFE_SHELL_ARG.test(arg)) {\n throw new Error(`Refusing to pass unsafe argument to shell command: ${JSON.stringify(arg)}`);\n }\n }\n const subprocess = spawn(cmd, args, {\n cwd: root,\n shell: true,\n env,\n // No stdin for the child process — it doesn't need interactive input\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n subprocess.stdout?.on('data', chunk => {\n stdout += chunk.toString();\n });\n subprocess.stderr?.on('data', chunk => {\n stderr += chunk.toString();\n });\n\n // Pipe stdout and stderr through the logging stream.\n // { end: false } prevents the first stream to close from ending pinoStream\n // while the other may still be writing.\n subprocess.stdout?.pipe(pinoStream, { end: false });\n subprocess.stderr?.pipe(pinoStream, { end: false });\n\n // Wait for the process to complete\n return new Promise((resolve, reject) => {\n subprocess.on('close', code => {\n pinoStream.end();\n if (code === 0) {\n resolve({ success: true, stdout, stderr });\n } else {\n reject(Object.assign(new Error(`Process exited with code ${code}`), { stdout, stderr }));\n }\n });\n\n subprocess.on('error', error => {\n pinoStream.end();\n logger.error('Process failed', { error });\n reject(error);\n });\n });\n } catch (error) {\n console.error(error);\n logger.error('Process failed', { error });\n pinoStream.end();\n return { success: false, error };\n }\n };\n}\n","import fs from 'node:fs';\nimport fsPromises from 'node:fs/promises';\nimport path, { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { MastraBase } from '@mastra/core/base';\nimport type { BundlerConfig } from '@mastra/core/bundler';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { readJSON, writeJSON, ensureFile } from 'fs-extra/esm';\nimport type { PackageJson } from 'type-fest';\nimport { parse, stringify } from 'yaml';\n\nimport { createChildProcessLogger } from '../deploy/log.js';\n\ntype PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';\n\n/** Version used to pack private workspace packages whose package.json has no `version`. */\nexport const WORKSPACE_PLACEHOLDER_VERSION = '0.0.0';\n\n// Write via temp file + rename so an interrupted write never leaves a truncated manifest.\nasync function writeManifestAtomically(manifestPath: string, contents: string, inFlight?: Set<string>) {\n const tmpPath = `${manifestPath}.${process.pid}.${Date.now()}.tmp`;\n inFlight?.add(tmpPath);\n try {\n const { mode } = await fsPromises.stat(manifestPath);\n await fsPromises.writeFile(tmpPath, contents, { mode });\n await fsPromises.chmod(tmpPath, mode);\n await fsPromises.rename(tmpPath, manifestPath);\n } catch (error) {\n await fsPromises.rm(tmpPath, { force: true });\n throw error;\n } finally {\n inFlight?.delete(tmpPath);\n }\n}\n\n/**\n * Package managers refuse to pack a manifest without a version, and pnpm/bun also\n * resolve `workspace:` ranges from the dependency's manifest. So every versionless\n * package in `dirs` gets the placeholder version for the whole of `operation`, and\n * the original manifests are restored afterwards — also on SIGINT/SIGTERM.\n */\nexport async function withPlaceholderVersions<T>(dirs: string[], operation: () => Promise<T>): Promise<T> {\n const acquired: string[] = [];\n try {\n for (const dir of new Set(dirs.map(dir => path.resolve(dir)))) {\n const manifestPath = path.join(dir, 'package.json');\n let lease = placeholderLeases.get(manifestPath);\n // A lease whose last owner is restoring it can't be joined; wait and start a fresh one.\n while (lease?.releasing) {\n await lease.releasing.catch(() => {});\n lease = placeholderLeases.get(manifestPath);\n }\n if (lease) {\n lease.refs++;\n } else {\n lease = { refs: 1, injected: false, ready: Promise.resolve() };\n lease.ready = injectPlaceholderVersion(manifestPath, lease);\n placeholderLeases.set(manifestPath, lease);\n installSignalHandlers();\n }\n acquired.push(manifestPath);\n await lease.ready;\n }\n return await operation();\n } finally {\n try {\n for (const manifestPath of acquired) {\n await releasePlaceholderVersion(manifestPath);\n }\n } finally {\n if (placeholderLeases.size === 0) {\n removeSignalHandlers();\n }\n }\n }\n}\n\ninterface PlaceholderLease {\n refs: number;\n original?: string;\n injected: boolean;\n ready: Promise<void>;\n releasing?: Promise<void>;\n}\n\n// Shared across calls so one bundle can't restore a manifest another is still packing.\nconst placeholderLeases = new Map<string, PlaceholderLease>();\nconst inFlightTmpPaths = new Set<string>();\n\nasync function injectPlaceholderVersion(manifestPath: string, lease: PlaceholderLease) {\n const original = await fsPromises.readFile(manifestPath, 'utf-8').catch(() => undefined);\n if (original === undefined) return;\n let manifest: PackageJson;\n try {\n manifest = JSON.parse(original) as PackageJson;\n } catch (error) {\n throw new Error(`Failed to parse ${manifestPath}: ${(error as Error).message}`, { cause: error });\n }\n if (manifest.version) return;\n lease.original = original;\n // Mark before writing so a signal mid-write still restores this manifest.\n lease.injected = true;\n await writeManifestAtomically(\n manifestPath,\n JSON.stringify({ ...manifest, version: WORKSPACE_PLACEHOLDER_VERSION }, null, 2) + '\\n',\n inFlightTmpPaths,\n );\n}\n\nasync function releasePlaceholderVersion(manifestPath: string) {\n const lease = placeholderLeases.get(manifestPath)!;\n if (--lease.refs > 0) return;\n lease.releasing = (async () => {\n await lease.ready.catch(() => {});\n try {\n if (lease.injected) {\n await writeManifestAtomically(manifestPath, lease.original!, inFlightTmpPaths);\n lease.injected = false;\n }\n } finally {\n placeholderLeases.delete(manifestPath);\n }\n })();\n await lease.releasing;\n}\n\nfunction restorePlaceholderVersionsSync() {\n // Removing in-flight temp files keeps them out of later tarballs and makes any\n // pending rename fail instead of overwriting the restored manifest.\n for (const tmpPath of inFlightTmpPaths) {\n fs.rmSync(tmpPath, { force: true });\n }\n inFlightTmpPaths.clear();\n for (const [manifestPath, lease] of placeholderLeases) {\n if (lease.injected) {\n fs.writeFileSync(manifestPath, lease.original!);\n lease.injected = false;\n }\n }\n}\n\nfunction onPlaceholderSignal(signal: NodeJS.Signals) {\n restorePlaceholderVersionsSync();\n removeSignalHandlers();\n process.kill(process.pid, signal);\n}\n\nfunction installSignalHandlers() {\n if (process.listeners('SIGINT').includes(onPlaceholderSignal)) return;\n process.once('SIGINT', onPlaceholderSignal);\n process.once('SIGTERM', onPlaceholderSignal);\n}\n\nfunction removeSignalHandlers() {\n process.off('SIGINT', onPlaceholderSignal);\n process.off('SIGTERM', onPlaceholderSignal);\n}\n\ninterface LockFileInfo {\n path: string;\n filename: string;\n packageManager: PackageManager;\n}\n\ninterface ArchitectureOptions {\n os?: string[];\n cpu?: string[];\n libc?: string[];\n}\n\ninterface InstallOptions extends ArchitectureOptions {\n pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'];\n pnpmOverrides?: Record<string, string>;\n pnpmNodeLinker?: 'hoisted';\n /** Patch key -> path relative to the output directory. */\n patchedDependencies?: Record<string, string>;\n}\n\nconst PNPM_PATCHES_DIR = 'pnpm-patches';\nconst BUN_PATCHES_DIR = 'bun-patches';\n\nconst PNPM_CONFIG_KEYS_TO_COPY = new Set([\n 'allowBuilds',\n 'onlyBuiltDependencies',\n 'ignoredBuiltDependencies',\n 'neverBuiltDependencies',\n 'minimumReleaseAge',\n 'minimumReleaseAgeExclude',\n 'trustPolicy',\n 'trustPolicyExclude',\n 'trustPolicyIgnoreAfter',\n 'supportedArchitectures',\n]);\n\n// supportedArchitectures is generated from deployer architecture targets, so it can't be set explicitly.\n// neverBuiltDependencies switches pnpm 10 into deny-list mode, which runs every build script it doesn't name.\nconst PNPM_EXPLICIT_SETTING_KEYS = new Set(\n [...PNPM_CONFIG_KEYS_TO_COPY, 'blockExoticSubdeps'].filter(\n key => key !== 'supportedArchitectures' && key !== 'neverBuiltDependencies',\n ),\n);\n\nfunction serializePnpmWorkspaceSettings(settings: BundlerConfig['pnpmWorkspaceSettings']) {\n // Untyped JS configs can pass undefined; treat it as omitted so the copied source setting survives.\n const definedSettings = Object.entries(settings ?? {}).filter(([, value]) => value !== undefined);\n return definedSettings.map(([key, value]) => {\n if (!PNPM_EXPLICIT_SETTING_KEYS.has(key)) {\n throw new MastraError({\n id: 'DEPLOYER_INVALID_PNPM_WORKSPACE_SETTING',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n text: `pnpm workspace setting ${JSON.stringify(key)} isn't supported in bundler.pnpmWorkspaceSettings. Supported settings: ${[...PNPM_EXPLICIT_SETTING_KEYS].join(', ')}.`,\n });\n }\n const block = stringify({ [key]: value }).trimEnd();\n validatePnpmBuildApprovals(key, block);\n return block;\n });\n}\n\nfunction getTopLevelYamlKey(line: string) {\n const match = /^(?!\\s)([\\w-]+):/.exec(line);\n return match?.[1];\n}\n\nconst PNPM_IGNORED_BUILDS_ERROR = 'ERR_PNPM_IGNORED_BUILDS';\n\nexport function getPnpmIgnoredBuildPackages(output: string): string[] {\n const match = new RegExp(`\\\\[?${PNPM_IGNORED_BUILDS_ERROR}\\\\]?[^\\\\n]*Ignored build scripts:\\\\s*([^\\\\n]+)`).exec(\n output,\n );\n if (!match?.[1]) return [];\n\n return match[1]\n .split(',')\n .map(specifier => specifier.trim())\n .filter(Boolean)\n .map(specifier => {\n if (specifier.startsWith('@')) {\n const versionSeparator = specifier.indexOf('@', 1);\n return versionSeparator === -1 ? specifier : specifier.slice(0, versionSeparator);\n }\n return specifier.split('@', 1)[0]!;\n });\n}\n\nfunction validatePnpmBuildApprovals(key: string, block: string): void {\n if (key !== 'allowBuilds' && key !== 'onlyBuiltDependencies') return;\n\n let value: unknown;\n try {\n value = (parse(block) as Record<string, unknown>)[key];\n } catch (error) {\n throw new MastraError(\n {\n id: 'DEPLOYER_INVALID_PNPM_BUILD_APPROVAL_CONFIG',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { key },\n text: `Invalid pnpm ${key} configuration`,\n },\n error,\n );\n }\n\n const invalidEntries =\n key === 'allowBuilds'\n ? value && typeof value === 'object' && !Array.isArray(value)\n ? Object.entries(value).filter(\n ([dependency, approval]) => dependency.trim().length === 0 || typeof approval !== 'boolean',\n )\n : [[key, value]]\n : Array.isArray(value) &&\n value.every(dependency => typeof dependency === 'string' && dependency.trim().length > 0)\n ? []\n : [[key, value]];\n\n if (invalidEntries.length === 0) return;\n const invalidEntryNames = invalidEntries.map(([entry]) => entry).join(', ');\n\n throw new MastraError({\n id: 'DEPLOYER_INVALID_PNPM_BUILD_APPROVAL_CONFIG',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { key, invalidEntries: invalidEntryNames },\n text: `Invalid pnpm ${key} entries: ${invalidEntryNames}`,\n });\n}\n\n/**\n * Reads the `patchedDependencies` map from a pnpm workspace file. Paths are returned as declared,\n * i.e. relative to the workspace root. Returns an empty map for absent or unusable declarations.\n */\nexport function parsePnpmPatchedDependencies(source: string): Record<string, string> {\n let parsed: unknown;\n try {\n parsed = parse(source);\n } catch {\n return {};\n }\n\n const patched = (parsed as { patchedDependencies?: unknown } | null)?.patchedDependencies;\n if (!patched || typeof patched !== 'object' || Array.isArray(patched)) {\n return {};\n }\n\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(patched as Record<string, unknown>)) {\n if (typeof value === 'string' && value.trim() && key.trim()) {\n result[key] = value.trim();\n }\n }\n\n return result;\n}\n\nexport function copyPnpmWorkspaceSettings(source: string, options: InstallOptions = {}) {\n const hasArchitecture = Boolean(options.os?.length || options.cpu?.length || options.libc?.length);\n const lines = source.split(/\\r?\\n/);\n const customBlocks = serializePnpmWorkspaceSettings(options.pnpmWorkspaceSettings);\n const blocks: string[] = [];\n\n for (let index = 0; index < lines.length;) {\n const key = getTopLevelYamlKey(lines[index] ?? '');\n if (!key) {\n index += 1;\n continue;\n }\n\n const start = index;\n index += 1;\n while (index < lines.length && !getTopLevelYamlKey(lines[index] ?? '')) {\n index += 1;\n }\n\n if (\n !PNPM_CONFIG_KEYS_TO_COPY.has(key) ||\n options.pnpmWorkspaceSettings?.[key] !== undefined ||\n (key === 'supportedArchitectures' && hasArchitecture)\n ) {\n continue;\n }\n\n const block = lines.slice(start, index).join('\\n').trimEnd();\n if (block) {\n validatePnpmBuildApprovals(key, block);\n blocks.push(block);\n }\n }\n\n if (hasArchitecture) {\n const architectureBlock = ['supportedArchitectures:'];\n if (options.os?.length) {\n architectureBlock.push(` os: ${JSON.stringify(options.os)}`);\n }\n if (options.cpu?.length) {\n architectureBlock.push(` cpu: ${JSON.stringify(options.cpu)}`);\n }\n if (options.libc?.length) {\n architectureBlock.push(` libc: ${JSON.stringify(options.libc)}`);\n }\n blocks.push(architectureBlock.join('\\n'));\n }\n\n if (options.pnpmOverrides && Object.keys(options.pnpmOverrides).length > 0) {\n blocks.push(\n [\n 'overrides:',\n ...Object.entries(options.pnpmOverrides).map(\n ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join('\\n'),\n );\n }\n\n if (options.patchedDependencies && Object.keys(options.patchedDependencies).length > 0) {\n blocks.push(\n [\n 'patchedDependencies:',\n ...Object.entries(options.patchedDependencies).map(\n ([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`,\n ),\n ].join('\\n'),\n );\n // The bundled output only installs runtime dependencies, so patches declared for\n // dev-only or bundled-away packages are legitimately unused here.\n blocks.push('allowUnusedPatches: true');\n }\n\n if (options.pnpmNodeLinker) {\n blocks.push(`nodeLinker: ${options.pnpmNodeLinker}`);\n }\n\n return [\"packages:\\n - '.'\", ...blocks, ...customBlocks].join('\\n\\n') + '\\n';\n}\n\n// Semver characters only; versions are interpolated into a shell command.\nconst SAFE_PACKAGE_VERSION = /^[0-9A-Za-z.+-]+$/;\n\n/**\n * Yarn classic writes `# yarn lockfile v1` within the first two lines; Berry lockfiles never contain it.\n * Only the head of the file is read so large monorepo lockfiles are never loaded into memory.\n */\nasync function isYarnClassicLockfile(lockfilePath: string): Promise<boolean> {\n const handle = await fsPromises.open(lockfilePath, 'r');\n try {\n const buffer = Buffer.alloc(512);\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n return /^# yarn lockfile v1\\r?$/m.test(buffer.toString('utf-8', 0, bytesRead));\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Removes overridden packages from every importer of a copied pnpm lockfile. When the Mastra app is the\n * workspace root, the root importer still resolves its workspace dependencies to `link:` versions. pnpm\n * keeps those versions although the output overrides them with packed tarballs, so the tarball is never\n * installed and the dependency symlink dangles. Without the entries, pnpm resolves them from the overrides.\n */\nasync function dropPnpmImporterDependencies(lockfilePath: string, packageNames: string[]): Promise<void> {\n const lockfile = parse(await fsPromises.readFile(lockfilePath, 'utf-8')) as {\n importers?: Record<string, Record<string, Record<string, unknown> | undefined> | undefined>;\n } | null;\n let changed = false;\n for (const importer of Object.values(lockfile?.importers ?? {})) {\n for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) {\n const dependencies = importer?.[field];\n for (const name of packageNames) {\n if (dependencies && name in dependencies) {\n delete dependencies[name];\n changed = true;\n }\n }\n }\n }\n if (changed) {\n await fsPromises.writeFile(lockfilePath, stringify(lockfile, { lineWidth: 0 }));\n }\n}\n\nexport class Deps extends MastraBase {\n private packageManager: PackageManager;\n private rootDir: string;\n private lockFile: LockFileInfo | null;\n\n constructor(rootDir = process.cwd()) {\n super({ component: 'DEPLOYER', name: 'DEPS' });\n\n this.rootDir = rootDir;\n this.lockFile = this.findLockFile(rootDir);\n this.packageManager = this.lockFile?.packageManager ?? 'npm';\n }\n\n private findLockFile(dir: string): LockFileInfo | null {\n const lockFiles: Array<{ filename: string; packageManager: PackageManager }> = [\n { filename: 'pnpm-lock.yaml', packageManager: 'pnpm' },\n { filename: 'package-lock.json', packageManager: 'npm' },\n { filename: 'yarn.lock', packageManager: 'yarn' },\n { filename: 'bun.lock', packageManager: 'bun' },\n ];\n for (const lockFile of lockFiles) {\n const lockFilePath = path.join(dir, lockFile.filename);\n if (fs.existsSync(lockFilePath)) {\n return { ...lockFile, path: lockFilePath };\n }\n }\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findLockFile(parentDir);\n }\n return null;\n }\n\n public getWorkspaceDependencyPath({ pkgName, version }: { pkgName: string; version: string }) {\n return `file:./workspace-module/${pkgName}-${version}.tgz`;\n }\n\n public async pack({\n dir,\n destination,\n sanitizedName,\n version,\n }: {\n dir: string;\n destination: string;\n sanitizedName: string;\n version: string;\n }) {\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: dir,\n });\n\n let packCmd = 'pack';\n let destinationFlag = `--pack-destination ${destination}`;\n if (this.packageManager === 'yarn') {\n if (this.lockFile && (await isYarnClassicLockfile(this.lockFile.path))) {\n if (!SAFE_PACKAGE_VERSION.test(version)) {\n throw new MastraError({\n id: 'DEPLOYER_INVALID_WORKSPACE_PACKAGE_VERSION',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { dir, version: String(version) },\n text: `Invalid version ${JSON.stringify(version)} in workspace package at ${dir}`,\n });\n }\n // Yarn classic has no --out/%v; --filename takes the full output path.\n destinationFlag = `--filename ${destination}/${sanitizedName}-${version}.tgz`;\n } else {\n // %s includes an '@' at the start of packages names with an '@'\n // so we need to use our sanitizedName instead.\n destinationFlag = `--out ${destination}/${sanitizedName}-%v.tgz`;\n }\n }\n if (this.packageManager === 'bun') {\n // bun uses `pm pack` instead of `pack`\n packCmd = 'pm pack';\n // bun uses --destination instead of --pack-destination\n destinationFlag = `--destination ${destination}`;\n }\n\n return cpLogger({\n cmd: `${this.packageManager} ${packCmd} ${destinationFlag}`,\n args: [],\n env: {\n PATH: process.env.PATH!,\n },\n });\n }\n\n private findPnpmWorkspaceFile(dir: string): string | null {\n const workspaceYamlPath = path.join(dir, 'pnpm-workspace.yaml');\n if (fs.existsSync(workspaceYamlPath)) {\n return workspaceYamlPath;\n }\n\n const parentDir = path.resolve(dir, '..');\n if (parentDir !== dir) {\n return this.findPnpmWorkspaceFile(parentDir);\n }\n\n return null;\n }\n\n private async writePnpmConfig(dir: string, options: InstallOptions = {}) {\n const sourceWorkspaceYamlPath = this.findPnpmWorkspaceFile(this.rootDir);\n const sourceWorkspaceYaml = sourceWorkspaceYamlPath\n ? await fsPromises.readFile(sourceWorkspaceYamlPath, 'utf-8')\n : '';\n\n const patchedDependencies = sourceWorkspaceYamlPath\n ? await this.copyPnpmPatches(sourceWorkspaceYaml, path.dirname(sourceWorkspaceYamlPath), dir)\n : undefined;\n\n await fsPromises.writeFile(\n path.join(dir, 'pnpm-workspace.yaml'),\n copyPnpmWorkspaceSettings(sourceWorkspaceYaml, { ...options, patchedDependencies }),\n 'utf-8',\n );\n }\n\n /**\n * Resolves a declared patch path against the source workspace and verifies that, once symlinks\n * are followed, it still resolves inside the workspace. Returns the real path to copy from, or\n * `undefined` when the patch escapes the workspace or its file cannot be resolved.\n */\n private async resolvePatchSource(\n resolvedWorkspaceRoot: string,\n declaredPath: string,\n { key, label }: { key: string; label: string },\n ): Promise<string | undefined> {\n const sourcePath = path.resolve(resolvedWorkspaceRoot, declaredPath);\n if (!sourcePath.startsWith(`${resolvedWorkspaceRoot}${path.sep}`)) {\n this.logger.warn(`Skipping ${label} patch for \"${key}\": patch file is outside the workspace at ${sourcePath}`);\n return undefined;\n }\n\n // A patch path can stay lexically under the workspace while traversing a symlink whose target\n // lives outside it. copyFile follows symlinks, so compare the resolved real paths before copying.\n let realWorkspaceRoot: string;\n let realSourcePath: string;\n try {\n [realWorkspaceRoot, realSourcePath] = await Promise.all([\n fsPromises.realpath(resolvedWorkspaceRoot),\n fsPromises.realpath(sourcePath),\n ]);\n } catch {\n this.logger.warn(`Skipping ${label} patch for \"${key}\": patch file not found at ${sourcePath}`);\n return undefined;\n }\n\n if (!realSourcePath.startsWith(`${realWorkspaceRoot}${path.sep}`)) {\n this.logger.warn(\n `Skipping ${label} patch for \"${key}\": patch file is outside the workspace at ${realSourcePath}`,\n );\n return undefined;\n }\n\n return realSourcePath;\n }\n\n /**\n * Copies the patch files declared by the source workspace into the output directory and returns\n * the patch map rewritten to output-relative paths, so the patches survive the output install.\n */\n private async copyPnpmPatches(\n sourceWorkspaceYaml: string,\n sourceWorkspaceRoot: string,\n dir: string,\n ): Promise<Record<string, string>> {\n const declared = parsePnpmPatchedDependencies(sourceWorkspaceYaml);\n const rewritten: Record<string, string> = {};\n const usedFileNames = new Set<string>();\n const resolvedWorkspaceRoot = path.resolve(sourceWorkspaceRoot);\n\n for (const [key, declaredPath] of Object.entries(declared)) {\n const sourcePath = await this.resolvePatchSource(resolvedWorkspaceRoot, declaredPath, {\n key,\n label: 'pnpm',\n });\n if (!sourcePath) continue;\n\n let fileName = path.basename(sourcePath);\n if (usedFileNames.has(fileName)) {\n fileName = `${key.replace(/[^a-zA-Z0-9._-]/g, '_')}-${fileName}`;\n }\n usedFileNames.add(fileName);\n\n await fsPromises.mkdir(path.join(dir, PNPM_PATCHES_DIR), { recursive: true });\n await fsPromises.copyFile(sourcePath, path.join(dir, PNPM_PATCHES_DIR, fileName));\n rewritten[key] = `${PNPM_PATCHES_DIR}/${fileName}`;\n }\n\n return rewritten;\n }\n\n /**\n * Writes the `.yarnrc.yml` for the bundled output, recording the supported architectures so the\n * output install only resolves optional native binaries that match the deployment target.\n */\n private async writeYarnConfig(dir: string, options: ArchitectureOptions) {\n const yarnrcPath = path.join(dir, '.yarnrc.yml');\n const config = {\n supportedArchitectures: {\n cpu: options.cpu || [],\n os: options.os || [],\n libc: options.libc || [],\n },\n };\n\n await fsPromises.writeFile(\n yarnrcPath,\n `supportedArchitectures:\\n${Object.entries(config.supportedArchitectures)\n .map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)\n .join('\\n')}`,\n );\n }\n\n /**\n * Copies the source workspace's `.yarn/patches/` directory (Yarn Berry) into the output\n * directory so patches survive the output install. Yarn auto-discovers patches from this\n * directory and applies them per the lockfile references.\n */\n private async copyYarnPatches(dir: string): Promise<void> {\n const sourcePatchesDir = path.join(this.rootDir, '.yarn', 'patches');\n if (!fs.existsSync(sourcePatchesDir)) return;\n\n const outputPatchesDir = path.join(dir, '.yarn', 'patches');\n await fsPromises.cp(sourcePatchesDir, outputPatchesDir, { recursive: true, errorOnExist: false });\n }\n\n /**\n * Copies the patch files referenced by the source workspace's `patchedDependencies` in\n * package.json into the output directory and returns the map rewritten to output-relative\n * paths, so bun patches survive the output install.\n */\n private async copyBunPatches(\n declared: Record<string, string>,\n sourceRoot: string,\n dir: string,\n ): Promise<Record<string, string>> {\n const rewritten: Record<string, string> = {};\n const usedFileNames = new Set<string>();\n const resolvedRoot = path.resolve(sourceRoot);\n\n for (const [key, declaredPath] of Object.entries(declared)) {\n const sourcePath = await this.resolvePatchSource(resolvedRoot, declaredPath, {\n key,\n label: 'bun',\n });\n if (!sourcePath) continue;\n\n let fileName = path.basename(sourcePath);\n if (usedFileNames.has(fileName)) {\n fileName = `${key.replace(/[^a-zA-Z0-9._-]/g, '_')}-${fileName}`;\n }\n usedFileNames.add(fileName);\n\n await fsPromises.mkdir(path.join(dir, BUN_PATCHES_DIR), { recursive: true });\n await fsPromises.copyFile(sourcePath, path.join(dir, BUN_PATCHES_DIR, fileName));\n rewritten[key] = `${BUN_PATCHES_DIR}/${fileName}`;\n }\n\n return rewritten;\n }\n\n /**\n * Reads `patchedDependencies` from the source package.json, copies the referenced patch\n * files into the output directory, and writes the output-relative patch map into the\n * output's package.json so `bun install` preserves patches in the bundled output.\n */\n private async copyBunPatchesToOutput(dir: string): Promise<void> {\n const sourcePackageJsonPath = path.join(this.rootDir, 'package.json');\n if (!fs.existsSync(sourcePackageJsonPath)) return;\n\n const sourcePkg = await readJSON(sourcePackageJsonPath);\n const patchedDeps = sourcePkg.patchedDependencies as Record<string, string> | undefined;\n if (!patchedDeps || Object.keys(patchedDeps).length === 0) return;\n\n const rewritten = await this.copyBunPatches(patchedDeps, this.rootDir, dir);\n if (Object.keys(rewritten).length === 0) return;\n\n const outputPackageJsonPath = path.join(dir, 'package.json');\n let outputPkg: Record<string, unknown>;\n try {\n outputPkg = (await readJSON(outputPackageJsonPath)) as Record<string, unknown>;\n } catch {\n outputPkg = {};\n }\n outputPkg.patchedDependencies = rewritten;\n await writeJSON(outputPackageJsonPath, outputPkg, { spaces: 2 });\n }\n\n private getNpmArgs(options: ArchitectureOptions): string[] {\n const args: string[] = [];\n if (options.cpu) args.push(`--cpu=${options.cpu.join(',')}`);\n if (options.os) args.push(`--os=${options.os.join(',')}`);\n if (options.libc) args.push(`--libc=${options.libc.join(',')}`);\n return args;\n }\n\n /**\n * Depending on whether we want to install or add a package, this function returns the appropriate commands.\n * All package managers support both commands (e.g. npm install has an alias on \"add\")\n */\n private getPackageManagerCommand(\n pm: PackageManager,\n type: 'install' | 'add',\n { yarnClassic = false }: { yarnClassic?: boolean } = {},\n ): string {\n const cmd = type === 'install' ? 'install' : 'add';\n\n switch (pm) {\n case 'npm':\n return `${cmd} --audit=false --fund=false --loglevel=error --progress=false --update-notifier=false`;\n case 'yarn':\n return type === 'install' && !yarnClassic ? `${cmd} --no-immutable` : cmd;\n case 'pnpm':\n return type === 'install' ? `${cmd} --no-frozen-lockfile --loglevel=error` : `${cmd} --loglevel=error`;\n default:\n return cmd;\n }\n }\n\n public async install({\n dir = this.rootDir,\n architecture,\n pnpmOverrides,\n pnpmNodeLinker,\n pnpmWorkspaceSettings,\n }: {\n dir?: string;\n architecture?: ArchitectureOptions;\n pnpmOverrides?: Record<string, string>;\n pnpmNodeLinker?: 'hoisted';\n pnpmWorkspaceSettings?: BundlerConfig['pnpmWorkspaceSettings'];\n } = {}) {\n const pm = this.packageManager;\n let yarnClassic = false;\n if (this.lockFile) {\n const destination = path.join(dir, this.lockFile.filename);\n if (path.resolve(this.lockFile.path) !== path.resolve(destination)) {\n const packedBunWorkspaces =\n pm === 'bun' &&\n fs.existsSync(path.join(dir, 'package.json')) &&\n Object.values(\n ((await readJSON(path.join(dir, 'package.json'))) as { resolutions?: Record<string, string> })\n .resolutions ?? {},\n ).some(spec => spec.startsWith('file:./workspace-module/'));\n\n if (packedBunWorkspaces) {\n // Bun cannot reuse the source workspace lockfile with packed tarballs; removing its workspace entries\n // makes Bun ignore it and regenerate the lockfile anyway. Start with a clean lockfile instead.\n await fsPromises.rm(destination, { force: true });\n } else {\n await fsPromises.copyFile(this.lockFile.path, destination);\n if (pm === 'pnpm' && pnpmOverrides && Object.keys(pnpmOverrides).length > 0) {\n await dropPnpmImporterDependencies(destination, Object.keys(pnpmOverrides));\n }\n }\n }\n\n if (pm === 'yarn') {\n yarnClassic = await isYarnClassicLockfile(destination);\n }\n }\n\n const installCommand = this.getPackageManagerCommand(pm, 'install', { yarnClassic });\n let args: string[] = [];\n\n switch (pm) {\n case 'pnpm':\n await this.writePnpmConfig(dir, { ...architecture, pnpmOverrides, pnpmNodeLinker, pnpmWorkspaceSettings });\n break;\n case 'yarn':\n // similar to --ignore-workspace but for yarn\n await ensureFile(path.join(dir, 'yarn.lock'));\n if (architecture) {\n await this.writeYarnConfig(dir, architecture);\n }\n await this.copyYarnPatches(dir);\n break;\n case 'bun':\n await this.copyBunPatchesToOutput(dir);\n break;\n case 'npm':\n if (architecture) {\n args = this.getNpmArgs(architecture);\n }\n break;\n default:\n // Do nothing\n }\n\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: dir,\n });\n\n try {\n return await cpLogger({\n cmd: `${pm} ${installCommand}`,\n args,\n env: process.env as Record<string, string>,\n });\n } catch (error) {\n if (pm !== 'pnpm') throw error;\n\n const processOutput =\n error && typeof error === 'object'\n ? `${'stdout' in error ? String(error.stdout) : ''}\\n${'stderr' in error ? String(error.stderr) : ''}`\n : '';\n const ignoredPackages = getPnpmIgnoredBuildPackages(processOutput);\n if (ignoredPackages.length === 0) throw error;\n\n throw new MastraError(\n {\n id: 'DEPLOYER_PNPM_IGNORED_BUILDS',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: { packageNames: ignoredPackages.join(', ') },\n text: `pnpm blocked build scripts for: ${ignoredPackages.join(', ')}. Add these packages to allowBuilds in pnpm-workspace.yaml and retry the build.`,\n },\n error,\n );\n }\n }\n\n public async installPackages(packages: string[]) {\n const pm = this.packageManager;\n const installCommand = this.getPackageManagerCommand(pm, 'add');\n\n const env: Record<string, string> = {\n PATH: process.env.PATH!,\n };\n\n if (process.env.npm_config_registry) {\n env.npm_config_registry = process.env.npm_config_registry;\n }\n\n const cpLogger = createChildProcessLogger({\n logger: this.logger,\n root: '',\n });\n\n return cpLogger({\n cmd: `${pm} ${installCommand}`,\n args: packages,\n env,\n });\n }\n\n public async checkDependencies(dependencies: string[]): Promise<string> {\n try {\n const packageJsonPath = path.join(this.rootDir, 'package.json');\n\n try {\n await fsPromises.access(packageJsonPath);\n } catch {\n return 'No package.json file found in the current directory';\n }\n\n const packageJson = await readJSON(packageJsonPath);\n for (const dependency of dependencies) {\n if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {\n return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;\n }\n }\n\n return 'ok';\n } catch (err) {\n console.error(err);\n return 'Could not check dependencies';\n }\n }\n\n public async getProjectName() {\n const packageJsonPath = path.join(this.rootDir, 'package.json');\n const pkg = await readJSON(packageJsonPath);\n return pkg.name;\n }\n\n public async getPackageVersion() {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkgJsonPath = path.join(__dirname, '..', '..', 'package.json');\n\n const content = (await readJSON(pkgJsonPath)) as PackageJson;\n return content.version;\n }\n\n public async addScriptsToPackageJson(scripts: Record<string, string>) {\n const packageJson = await readJSON('package.json');\n packageJson.scripts = {\n ...packageJson.scripts,\n ...scripts,\n };\n await writeJSON('package.json', packageJson, { spaces: 2 });\n }\n}\n\nexport class DepsService extends Deps {}\n","import * as fs from 'node:fs';\n\nexport abstract class EnvService {\n abstract getEnvValue(key: string): Promise<string | null>;\n abstract setEnvValue(key: string, value: string): Promise<void>;\n}\n\nexport class FileEnvService extends EnvService {\n private filePath: string;\n\n constructor(filePath: string) {\n super();\n this.filePath = filePath;\n }\n\n private readFile(filePath: string): Promise<string> {\n return new Promise((resolve, reject) => {\n fs.readFile(filePath, 'utf8', (err: NodeJS.ErrnoException | null, data: string) => {\n if (err) reject(err);\n else resolve(data);\n });\n });\n }\n\n private writeFile({ filePath, data }: { filePath: string; data: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n fs.writeFile(filePath, data, 'utf8', (err: NodeJS.ErrnoException | null) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n private async updateEnvData({\n key,\n value,\n filePath = this.filePath,\n data,\n }: {\n key: string;\n value: string;\n filePath?: string;\n data: string;\n }): Promise<string> {\n const regex = new RegExp(`^${key}=.*$`, 'm');\n if (data.match(regex)) {\n // Use a replacement function so `$` sequences in the value (e.g. `$&`,\n // `$$`) are written literally instead of being interpreted as\n // String.prototype.replace special patterns.\n data = data.replace(regex, () => `${key}=${value}`);\n } else {\n data += `\\n${key}=${value}`;\n }\n await this.writeFile({ filePath, data });\n console.info(`${key} set to ${value} in ENV file.`);\n return data;\n }\n\n async getEnvValue(key: string): Promise<string | null> {\n try {\n const data = await this.readFile(this.filePath);\n const regex = new RegExp(`^${key}=(.*)$`, 'm');\n const match = data.match(regex);\n return match?.[1] || null;\n } catch (err) {\n console.error(`Error reading ENV value: ${err}`);\n return null;\n }\n }\n\n async setEnvValue(key: string, value: string): Promise<void> {\n try {\n const data = await this.readFile(this.filePath);\n await this.updateEnvData({ key, value, data });\n } catch (err) {\n console.error(`Error writing ENV value: ${err}`);\n }\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport fsExtra from 'fs-extra/esm';\n\nimport { FileEnvService } from './env.js';\n\nexport class FileService {\n /**\n *\n * @param inputFile the file in the starter files directory to copy\n * @param outputFilePath the destination path\n * @param replaceIfExists flag to replace if it exists\n * @returns\n */\n public async copyStarterFile(inputFile: string, outputFilePath: string, replaceIfExists?: boolean) {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n const filePath = path.resolve(__dirname, '..', 'starter-files', inputFile);\n const fileString = fs.readFileSync(filePath, 'utf8');\n\n if (fs.existsSync(outputFilePath) && !replaceIfExists) {\n console.info(`${outputFilePath} already exists`);\n return false;\n }\n\n await fsExtra.outputFile(outputFilePath, fileString);\n\n return true;\n }\n\n public async setupEnvFile({ dbUrl }: { dbUrl: string }) {\n const envPath = path.join(process.cwd(), '.env.development');\n\n await fsExtra.ensureFile(envPath);\n\n const fileEnvService = new FileEnvService(envPath);\n await fileEnvService.setEnvValue('DB_URL', dbUrl);\n }\n\n public getFirstExistingFile(files: string[]): string {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n throw new Error('Missing required file, checked the following paths: ' + files.join(', '));\n }\n\n /**\n * Returns every existing file from the provided array in the same order.\n * Callers supply files from the lowest to highest precedence so later dotenv\n * files override earlier values when the bundler loads them.\n */\n public getExistingFiles(files: string[]): string[] {\n return files.filter(file => fs.existsSync(file));\n }\n\n /**\n * Returns the first existing file from the provided array, or undefined if none exist\n * @param files array of file paths to check\n * @returns the first existing file path or undefined\n */\n public getFirstExistingFileOrUndefined(files: string[]): string | undefined {\n for (const f of files) {\n if (fs.existsSync(f)) {\n return f;\n }\n }\n\n return undefined;\n }\n\n public replaceValuesInFile({\n filePath,\n replacements,\n }: {\n filePath: string;\n replacements: { search: string; replace: string }[];\n }) {\n let fileContent = fs.readFileSync(filePath, 'utf8');\n replacements.forEach(({ search, replace }) => {\n fileContent = fileContent.replaceAll(search, replace);\n });\n\n fs.writeFileSync(filePath, fileContent);\n }\n}\n"],"mappings":";;;;;;;;;;;AAIA,MAAa,oBAAoB,WAA0B;CACzD,OAAO,IAAI,SAAS,EAClB,MAAM,OAAO,WAAW,UAAU;EAEhC,MAAM,OAAO,MAAM,SAAS,CAAC,CAAC,KAAK;EAEnC,IAAI,MAAM;GACR,QAAQ,KAAK,IAAI;GAEjB,OAAO,KAAK,IAAI;EAClB;EAEA,SAAS;CACX,EACF,CAAC;AACH;;;;;;;AAQA,MAAM,iBAAiB;AA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1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/deployer",
3
- "version": "1.80.0-alpha.0",
3
+ "version": "1.80.0-alpha.2",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [
@@ -110,7 +110,7 @@
110
110
  "tinyglobby": "^0.2.17",
111
111
  "ws": "^8.21.3",
112
112
  "yaml": "^2.9.0",
113
- "@mastra/server": "1.80.0-alpha.0"
113
+ "@mastra/server": "1.80.0-alpha.2"
114
114
  },
115
115
  "devDependencies": {
116
116
  "@hono/node-server": "^2.0.0",
@@ -118,8 +118,8 @@
118
118
  "@hono/swagger-ui": "^0.5.3",
119
119
  "@types/fs-extra": "^11.0.4",
120
120
  "@types/node": "22.20.5",
121
- "@vitest/coverage-v8": "4.1.11",
122
- "@vitest/ui": "4.1.11",
121
+ "@vitest/coverage-v8": "4.1.12",
122
+ "@vitest/ui": "4.1.12",
123
123
  "fetch-to-node": "^2.1.0",
124
124
  "hono-openapi": "^1.3.1",
125
125
  "stacktrace-parser": "^0.1.11",
@@ -127,17 +127,17 @@
127
127
  "tsx": "^4.23.1",
128
128
  "type-fest": "^5.4.4",
129
129
  "typescript": "^6.0.3",
130
- "vitest": "4.1.11",
130
+ "vitest": "4.1.12",
131
131
  "zod": "^4.6.7",
132
- "@internal/core": "0.1.3",
133
- "@internal/lint": "0.0.145",
132
+ "@internal/types-builder": "0.0.120",
134
133
  "@internal/find-workspaces": "0.0.0",
134
+ "@internal/core": "0.1.3",
135
135
  "@mastra/agent-browser": "0.5.4",
136
- "@internal/types-builder": "0.0.120",
137
- "@mastra/core": "1.80.0-alpha.0",
138
- "@mastra/hono": "1.7.22-alpha.0",
139
- "@mastra/server": "1.80.0-alpha.0",
140
- "@mastra/mcp": "^2.6.0-alpha.0"
136
+ "@mastra/core": "1.80.0-alpha.2",
137
+ "@mastra/hono": "1.7.22-alpha.2",
138
+ "@mastra/mcp": "^2.6.0-alpha.0",
139
+ "@mastra/server": "1.80.0-alpha.2",
140
+ "@internal/lint": "0.0.145"
141
141
  },
142
142
  "peerDependencies": {
143
143
  "@mastra/core": ">=1.58.0-0 <2.0.0-0"
@@ -1 +0,0 @@
1
- {"version":3,"file":"bundler-BUqyRuGu.js","names":["getPackageInfo","getOriginalPackageInfo","getPackageInfo","removeDeployer","t","removeDeployerBabelPlugin","minify","esbuildMinify"],"sources":["../src/build/plugins/esbuild.ts","../src/build/plugins/esm-shim.ts","../src/build/plugins/local-storage-detector.ts","../src/build/package-info.ts","../src/build/plugins/module-alias.ts","../src/build/plugins/node-modules-extension-resolver.ts","../src/build/plugins/protocol-external-resolver.ts","../src/build/babel/remove-deployer.ts","../src/build/plugins/remove-deployer.ts","../src/build/plugins/subpath-externals-resolver.ts","../src/build/plugins/tsconfig-paths.ts","../src/build/bundler.ts"],"sourcesContent":["import originalEsbuild from 'rollup-plugin-esbuild';\n\nexport function esbuild(options: Parameters<typeof originalEsbuild>[0] = {}) {\n return originalEsbuild({\n target: 'node20',\n platform: 'node',\n minify: false,\n ...options,\n });\n}\n","import originalEsmShim from '@rollup/plugin-esm-shim';\nimport type { Plugin } from 'rollup';\n\n// Regex to detect DECLARATIONS of __filename, __dirname\n// Using non-capturing group (?:) for slightly better performance\nconst FilenameDeclarationRegex = /(?:const|let|var)\\s+__filename/;\nconst DirnameDeclarationRegex = /(?:const|let|var)\\s+__dirname/;\n\n/**\n * Custom ESM shim plugin wrapper that respects user-declared __filename/__dirname variables.\n *\n * The original @rollup/plugin-esm-shim would inject shims even when users had already declared\n * their own __filename/__dirname, causing \"Identifier '__filename' has already been declared\" errors.\n *\n * This wrapper checks if the user has already declared these variables and skips the shim injection\n * if so. If either variable is declared, we skip the shim entirely since the original plugin injects\n * both together and we assume users who declare one will also handle the other if needed.\n */\nexport function esmShim(): Plugin {\n const original = originalEsmShim();\n\n return {\n name: 'esm-shim',\n renderChunk(code, chunk, opts, meta) {\n // Fast path: use includes() first to avoid regex if identifiers aren't present\n const hasFilename = code.includes('__filename');\n const hasDirname = code.includes('__dirname');\n\n // If user declared either __filename or __dirname, skip shim injection entirely\n // since the original plugin injects both together\n const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);\n const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);\n\n if (userDeclaredFilename || userDeclaredDirname) {\n return null;\n }\n\n // Otherwise, delegate to the original plugin\n if (typeof original.renderChunk === 'function') {\n return original.renderChunk.call(this, code, chunk, opts, meta);\n }\n\n return null;\n },\n };\n}\n\nexport default esmShim;\n","import type { Plugin } from 'rollup';\n\n/**\n * Connection-string-shaped patterns that resolve to the build host and will\n * never work inside the deploy container.\n */\nconst LOCAL_HOST_PATTERNS: Array<{ pattern: RegExp; hint: string }> = [\n {\n pattern: /\\bfile:\\.{1,2}\\/[^\\s'\"`]+\\.(?:db|sqlite)\\b/gi,\n hint: 'LibSQL/SQLite file path relative to the build host',\n },\n {\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb|redis|libsql):\\/\\/[^/\\s'\"`]*localhost\\b/gi,\n hint: 'localhost in a connection string',\n },\n {\n pattern: /\\b(?:postgres(?:ql)?|mysql|mongodb|redis|libsql):\\/\\/[^/\\s'\"`]*127\\.0\\.0\\.1\\b/g,\n hint: '127.0.0.1 in a connection string',\n },\n];\n\nexport interface LocalStorageDetection {\n value: string;\n hint: string;\n module: string;\n /**\n * Name of the env var that guards this literal at runtime, when the\n * literal is the fallback arm of a `process.env.X || literal` (or `??`)\n * expression. The CLI preflight uses this to suppress or soften the\n * error when the guarding var is present in the deploy env.\n */\n guardedBy?: string;\n}\n\n/**\n * Unified preflight metadata emitted as `preflight-metadata.json`.\n * Superset of the legacy `preflight-local-paths.json` (which stays emitted\n * for one release so older CLIs keep working with newer deployers).\n */\nexport interface PreflightMetadata {\n version: 1;\n localPaths: LocalStorageDetection[];\n userEnvRefs: string[];\n}\n\n/**\n * Everything under `.mastra/.build/` is deployer-generated pre-bundled\n * dependency code (`@mastra__*.mjs` shims and their shared `chunk-*.mjs`\n * files), never user-authored. These preserve JSDoc examples from the\n * original library source (e.g. `LibSQLStore({ url: 'file:./data.db' })`)\n * which would otherwise trip the host-local detector, and their env var\n * reads are library refs that must not count as user references.\n */\nconst MASTRA_BUILD_DIR = /[\\\\/]\\.mastra[\\\\/]\\.build[\\\\/]/;\n\nconst PROCESS_ENV_DOT = /\\bprocess\\.env\\.([A-Z_][A-Z0-9_]*)\\b/g;\nconst PROCESS_ENV_BRACKET = /\\bprocess\\.env\\[['\"]([A-Z_][A-Z0-9_]*)['\"]\\]/g;\n\n/** Names of the metadata assets emitted into the output dir. */\n// TODO(preflight-metadata): stop emitting the legacy file in the next minor\n// after @mastra/deployer 1.50 — every CLI released alongside 1.50+ reads\n// preflight-metadata.json. Also remove the legacy fallback in the CLI's\n// deploy-preflight.ts at the same time.\nconst LEGACY_LOCAL_PATHS_FILE = 'preflight-local-paths.json';\nconst PREFLIGHT_METADATA_FILE = 'preflight-metadata.json';\nconst WORKERS_CONFIG_FILE = 'workers.json';\n\ninterface ModuleMatch {\n value: string;\n hint: string;\n guardedBy?: string;\n}\n\nfunction collectEnvRefs(code: string): Set<string> {\n const refs = new Set<string>();\n for (const m of code.matchAll(PROCESS_ENV_DOT)) refs.add(m[1]!);\n for (const m of code.matchAll(PROCESS_ENV_BRACKET)) refs.add(m[1]!);\n return refs;\n}\n\n/* ------------------------------------------------------------------ */\n/* AST guard analysis */\n/* ------------------------------------------------------------------ */\n\ninterface AstNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isAstNode(v: unknown): v is AstNode {\n return typeof v === 'object' && v !== null && typeof (v as AstNode).type === 'string';\n}\n\nfunction walkAst(node: AstNode, visit: (node: AstNode) => void): void {\n visit(node);\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isAstNode(item)) walkAst(item, visit);\n }\n } else if (isAstNode(value)) {\n walkAst(value, visit);\n }\n }\n}\n\nfunction propertyName(node: AstNode): string | undefined {\n const key = node.key as AstNode | undefined;\n if (key?.type === 'Identifier' && !node.computed) return key.name as string;\n if (key?.type === 'Literal' && typeof key.value === 'string') return key.value;\n return undefined;\n}\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype WorkerConfig = { enabled: boolean; [key: string]: JsonValue };\n\ntype WorkersConfig = {\n version: 1;\n orchestration: WorkerConfig;\n scheduler: WorkerConfig;\n backgroundTasks: WorkerConfig;\n custom: string[];\n};\n\nfunction staticJsonValue(node: AstNode): JsonValue | undefined {\n if (node.type === 'Literal') {\n const value = node.value;\n if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value;\n }\n return undefined;\n }\n\n if (node.type === 'UnaryExpression' && node.operator === '-') {\n const argument = node.argument as AstNode | undefined;\n const value = argument ? staticJsonValue(argument) : undefined;\n return typeof value === 'number' ? -value : undefined;\n }\n\n if (node.type === 'TemplateLiteral') {\n const expressions = (node.expressions as AstNode[] | undefined) ?? [];\n const quasis = (node.quasis as Array<{ value?: { cooked?: string } }> | undefined) ?? [];\n if (expressions.length === 0) return quasis[0]?.value?.cooked ?? '';\n return undefined;\n }\n\n if (node.type === 'ArrayExpression') {\n const result: JsonValue[] = [];\n for (const element of (node.elements as Array<AstNode | null> | undefined) ?? []) {\n if (!element) return undefined;\n const value = staticJsonValue(element);\n if (value === undefined) return undefined;\n result.push(value);\n }\n return result;\n }\n\n if (node.type === 'ObjectExpression') {\n const result: Record<string, JsonValue> = {};\n for (const property of (node.properties as AstNode[] | undefined) ?? []) {\n if (property.type !== 'Property' || property.kind !== 'init') return undefined;\n const name = propertyName(property);\n const valueNode = property.value as AstNode | undefined;\n if (!name || !valueNode) return undefined;\n const value = staticJsonValue(valueNode);\n if (value === undefined) {\n delete result[name];\n } else {\n result[name] = value;\n }\n }\n return result;\n }\n\n return undefined;\n}\n\nfunction staticObjectValue(node: AstNode | undefined): Record<string, JsonValue> {\n if (!node) return {};\n const value = staticJsonValue(node);\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};\n}\n\nfunction isConfigured(node: AstNode | undefined): boolean {\n if (!node) return false;\n if (node.type === 'Literal') return node.value !== null && node.value !== false;\n return node.type !== 'Identifier' || node.name !== 'undefined';\n}\n\nfunction unwrapAwait(node: AstNode | undefined): AstNode | undefined {\n return node?.type === 'AwaitExpression' ? (node.argument as AstNode | undefined) : node;\n}\n\nfunction findPreparedConfigSources(ast: AstNode): Map<string, AstNode> {\n const factoryConfigs = new Map<string, AstNode>();\n const preparedConfigs = new Map<string, AstNode>();\n\n walkAst(ast, node => {\n if (node.type !== 'VariableDeclarator') return;\n const id = node.id as AstNode | undefined;\n const init = node.init as AstNode | undefined;\n const callee = init?.type === 'NewExpression' ? (init.callee as AstNode | undefined) : undefined;\n const config = (init?.arguments as AstNode[] | undefined)?.[0];\n if (\n id?.type === 'Identifier' &&\n callee?.type === 'Identifier' &&\n callee.name === 'MastraFactory' &&\n config?.type === 'ObjectExpression'\n ) {\n factoryConfigs.set(id.name as string, config);\n }\n });\n\n walkAst(ast, node => {\n if (node.type !== 'VariableDeclarator') return;\n const id = node.id as AstNode | undefined;\n const init = unwrapAwait(node.init as AstNode | undefined);\n const callee = init?.type === 'CallExpression' ? (init.callee as AstNode | undefined) : undefined;\n const object = callee?.type === 'MemberExpression' ? (callee.object as AstNode | undefined) : undefined;\n const property = callee?.type === 'MemberExpression' ? (callee.property as AstNode | undefined) : undefined;\n const isPrepareCall =\n (property?.type === 'Identifier' && property.name === 'prepare') ||\n (property?.type === 'Literal' && property.value === 'prepare');\n if (id?.type !== 'Identifier' || object?.type !== 'Identifier' || !isPrepareCall) return;\n\n const factoryConfig = factoryConfigs.get(object.name as string);\n if (factoryConfig) preparedConfigs.set(id.name as string, factoryConfig);\n });\n\n return preparedConfigs;\n}\n\nfunction resolvedObjectProperty(\n config: AstNode,\n name: string,\n preparedConfigs: Map<string, AstNode>,\n seen = new Set<AstNode>(),\n): AstNode | undefined {\n if (config.type !== 'ObjectExpression' || seen.has(config)) return undefined;\n seen.add(config);\n\n let value: AstNode | undefined;\n for (const property of (config.properties as AstNode[] | undefined) ?? []) {\n if (property.type === 'Property' && propertyName(property) === name) {\n value = property.value as AstNode | undefined;\n continue;\n }\n if (property.type !== 'SpreadElement') continue;\n\n const argument = property.argument as AstNode | undefined;\n const spreadConfig = argument?.type === 'Identifier' ? preparedConfigs.get(argument.name as string) : undefined;\n if (!spreadConfig) continue;\n const spreadValue = resolvedObjectProperty(spreadConfig, name, preparedConfigs, seen);\n if (spreadValue) value = spreadValue;\n }\n\n return value;\n}\n\n/**\n * Best-effort static extraction of the worker topology configured on a\n * `new Mastra(...)` instance, including `MastraFactory.prepare()` results spread\n * into its constructor. A worker service is only useful when the instance\n * explicitly provides both storage and pubsub so its processes can coordinate.\n * Dynamic values and callbacks are omitted from the display-only manifest.\n */\nfunction findStaticCustomWorkerNames(ast: AstNode, workers: AstNode | undefined): string[] {\n const variableInitializers = new Map<string, AstNode>();\n const classWorkerNames = new Map<string, string>();\n\n walkAst(ast, node => {\n if (node.type === 'VariableDeclarator') {\n const id = node.id as AstNode | undefined;\n const init = node.init as AstNode | undefined;\n if (id?.type === 'Identifier' && init) variableInitializers.set(id.name as string, init);\n return;\n }\n\n if (node.type !== 'ClassDeclaration' && node.type !== 'ClassExpression') return;\n const id = node.id as AstNode | undefined;\n const body = node.body as AstNode | undefined;\n if (id?.type !== 'Identifier' || body?.type !== 'ClassBody') return;\n\n for (const member of (body.body as AstNode[] | undefined) ?? []) {\n if (member.type !== 'PropertyDefinition' || propertyName(member) !== 'name') continue;\n const value = member.value as AstNode | undefined;\n const name = value ? staticJsonValue(value) : undefined;\n if (typeof name === 'string') classWorkerNames.set(id.name as string, name);\n }\n });\n\n const names = new Set<string>();\n const seen = new Set<AstNode>();\n const visit = (node: AstNode | undefined): void => {\n if (!node || seen.has(node)) return;\n seen.add(node);\n\n if (node.type === 'Identifier') {\n visit(variableInitializers.get(node.name as string));\n return;\n }\n if (node.type === 'ArrayExpression') {\n for (const element of (node.elements as Array<AstNode | null> | undefined) ?? []) {\n if (element?.type === 'SpreadElement') {\n visit(element.argument as AstNode | undefined);\n } else {\n visit(element ?? undefined);\n }\n }\n return;\n }\n if (node.type === 'NewExpression') {\n const callee = node.callee as AstNode | undefined;\n const name = callee?.type === 'Identifier' ? classWorkerNames.get(callee.name as string) : undefined;\n if (name) names.add(name);\n return;\n }\n if (node.type === 'ObjectExpression') {\n const name = staticObjectValue(node).name;\n if (typeof name === 'string') names.add(name);\n }\n };\n\n visit(workers);\n for (const builtIn of ['orchestration', 'scheduler', 'backgroundTasks']) names.delete(builtIn);\n return [...names].sort();\n}\n\nfunction findWorkersConfig(ast: AstNode): WorkersConfig | undefined {\n const preparedConfigs = findPreparedConfigSources(ast);\n let workersConfig: WorkersConfig | undefined;\n walkAst(ast, node => {\n if (workersConfig || node.type !== 'NewExpression') return;\n const callee = node.callee as AstNode | undefined;\n if (callee?.type !== 'Identifier' || callee.name !== 'Mastra') return;\n const config = (node.arguments as AstNode[] | undefined)?.[0];\n if (config?.type !== 'ObjectExpression') return;\n\n const storage = resolvedObjectProperty(config, 'storage', preparedConfigs);\n const pubsub = resolvedObjectProperty(config, 'pubsub', preparedConfigs);\n const workers = resolvedObjectProperty(config, 'workers', preparedConfigs);\n if (!isConfigured(storage) || !isConfigured(pubsub) || (workers?.type === 'Literal' && workers.value === false)) {\n return;\n }\n\n const scheduler = staticObjectValue(resolvedObjectProperty(config, 'scheduler', preparedConfigs));\n const backgroundTasks = staticObjectValue(resolvedObjectProperty(config, 'backgroundTasks', preparedConfigs));\n\n workersConfig = {\n version: 1,\n orchestration: { enabled: true },\n scheduler: { ...scheduler, enabled: scheduler.enabled !== false },\n backgroundTasks: { ...backgroundTasks, enabled: backgroundTasks.enabled === true },\n custom: findStaticCustomWorkerNames(ast, workers),\n };\n });\n return workersConfig;\n}\n\n/** Find the first `process.env.X` / `process.env['X']` read inside an expression. */\nfunction findFirstEnvRef(node: AstNode): string | undefined {\n let found: string | undefined;\n walkAst(node, n => {\n if (found !== undefined) return;\n if (n.type !== 'MemberExpression') return;\n const object = n.object as AstNode | undefined;\n if (\n !object ||\n object.type !== 'MemberExpression' ||\n (object.object as AstNode | undefined)?.type !== 'Identifier' ||\n ((object.object as AstNode).name as string) !== 'process' ||\n (object.property as AstNode | undefined)?.type !== 'Identifier' ||\n ((object.property as AstNode).name as string) !== 'env'\n ) {\n return;\n }\n const property = n.property as AstNode | undefined;\n if (property?.type === 'Identifier' && !n.computed) {\n found = property.name as string;\n } else if (property?.type === 'Literal' && typeof property.value === 'string') {\n found = property.value;\n }\n });\n return found;\n}\n\n/**\n * Parse a module and figure out, for each detected local-path value, whether\n * every string literal containing it is the fallback arm of a\n * `process.env.X || <literal>` / `??` expression. Returns a map from\n * detected value to guarding env var name. Values with any unguarded\n * occurrence (or inconsistent guards) are absent — the CLI then errors as\n * before, which is the safe default.\n */\nfunction findGuardedValues(ast: AstNode, values: Set<string>): Map<string, string> {\n const stringLiterals: AstNode[] = [];\n const guardedLiterals = new Map<AstNode, string>();\n\n walkAst(ast, node => {\n if (node.type === 'Literal' && typeof node.value === 'string') {\n stringLiterals.push(node);\n return;\n }\n if (node.type === 'LogicalExpression' && (node.operator === '||' || node.operator === '??')) {\n const right = node.right as AstNode | undefined;\n if (right?.type === 'Literal' && typeof right.value === 'string') {\n const envName = findFirstEnvRef(node.left as AstNode);\n if (envName) guardedLiterals.set(right, envName);\n }\n }\n });\n\n const result = new Map<string, string>();\n for (const value of values) {\n const containing = stringLiterals.filter(lit => (lit.value as string).includes(value));\n if (containing.length === 0) continue;\n const guards = containing.map(lit => guardedLiterals.get(lit));\n const first = guards[0];\n if (first !== undefined && guards.every(g => g === first)) {\n result.set(value, first);\n }\n }\n return result;\n}\n\n/**\n * Rollup plugin that detects host-local storage URLs (e.g. `file:./mastra.db`,\n * `postgres://localhost`) in **user source modules** during bundling, and\n * collects the env vars user code reads via `process.env.X`.\n *\n * Only modules outside `node_modules` (and the deployer's own\n * `.mastra/.build/` pre-bundled files) are inspected, so library code\n * (like Agent Builder prompt templates or JSDoc examples in `@mastra/core`)\n * is naturally excluded. When `rootDir` is given, modules outside it are\n * also excluded — symlinked dependencies (pnpm `link:`/`file:`) resolve to\n * real paths that never contain `node_modules`. Tree-shaken modules are\n * excluded via\n * `generateBundle` — only modules that actually contribute rendered code to\n * the output are reported.\n *\n * When a detected literal is the fallback arm of a `process.env.X || literal`\n * expression, `guardedBy: \"X\"` is recorded so the CLI preflight can apply\n * deploy-time env context instead of hard-erroring on a dead fallback.\n *\n * Three assets are emitted into the output directory:\n * - `preflight-metadata.json` — unified metadata (local paths + user env refs)\n * - `workers.json` — statically extracted worker topology, or `null`\n * - `preflight-local-paths.json` — legacy shape, kept for one release so an\n * older globally-installed CLI paired with a newer project-local deployer\n * doesn't lose the LOCAL_STORAGE_PATH check.\n */\nexport function localStorageDetector(rootDir?: string): Plugin {\n const userModuleMatches = new Map<string, ModuleMatch[]>();\n const userModuleEnvRefs = new Map<string, Set<string>>();\n const userModuleWorkersConfigs = new Map<string, WorkersConfig>();\n let normalizedRoot: string | undefined;\n if (rootDir) {\n let root = rootDir.replace(/\\\\/g, '/');\n while (root.endsWith('/')) root = root.slice(0, -1);\n normalizedRoot = root + '/';\n }\n\n return {\n name: 'mastra-local-storage-detector',\n\n transform(_code, id) {\n if (id.includes('node_modules')) return null;\n if (MASTRA_BUILD_DIR.test(id)) return null;\n // Modules outside the project/workspace root are dependencies resolved\n // through symlinks (pnpm `link:`, `file:`, monorepo dev setups) whose\n // real path escapes `node_modules` — library code, not user code.\n if (normalizedRoot && !id.replace(/\\\\/g, '/').startsWith(normalizedRoot)) return null;\n\n const refs = collectEnvRefs(_code);\n if (refs.size > 0) {\n userModuleEnvRefs.set(id, refs);\n }\n\n const matches: ModuleMatch[] = [];\n for (const { pattern, hint } of LOCAL_HOST_PATTERNS) {\n const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');\n for (const m of _code.matchAll(re)) {\n matches.push({ value: m[0], hint });\n }\n }\n\n // Best-effort structural pass: only parse modules that may contain\n // Mastra worker config or need guard analysis for a detected local path.\n // Existing local-path matches remain unguarded on parse failure.\n if (_code.includes('Mastra') || matches.length > 0) {\n try {\n const ast = this.parse(_code) as unknown as AstNode;\n const workersConfig = findWorkersConfig(ast);\n if (workersConfig) {\n userModuleWorkersConfigs.set(id, workersConfig);\n }\n if (matches.length > 0) {\n const guarded = findGuardedValues(ast, new Set(matches.map(m => m.value)));\n for (const match of matches) {\n const guardedBy = guarded.get(match.value);\n if (guardedBy) match.guardedBy = guardedBy;\n }\n }\n } catch {\n // ignore — optional static metadata is best-effort\n }\n }\n\n if (matches.length > 0) {\n userModuleMatches.set(id, matches);\n }\n\n return null;\n },\n\n generateBundle(_, bundle) {\n const detections: LocalStorageDetection[] = [];\n const seen = new Set<string>();\n const userEnvRefs = new Set<string>();\n let workersConfig: WorkersConfig | undefined;\n\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'chunk') continue;\n\n for (const [moduleId, moduleInfo] of Object.entries(chunk.modules)) {\n if (moduleInfo.renderedLength === 0) continue;\n\n for (const ref of userModuleEnvRefs.get(moduleId) ?? []) {\n userEnvRefs.add(ref);\n }\n workersConfig ??= userModuleWorkersConfigs.get(moduleId);\n\n const matches = userModuleMatches.get(moduleId);\n if (!matches) continue;\n\n for (const { value, hint, guardedBy } of matches) {\n const key = `${hint}::${value}`;\n if (seen.has(key)) continue;\n seen.add(key);\n\n detections.push({ value, hint, module: moduleId, ...(guardedBy ? { guardedBy } : {}) });\n }\n }\n }\n\n const metadata: PreflightMetadata = {\n version: 1,\n localPaths: detections,\n userEnvRefs: [...userEnvRefs].sort(),\n };\n\n this.emitFile({\n type: 'asset',\n fileName: PREFLIGHT_METADATA_FILE,\n source: JSON.stringify(metadata),\n });\n\n this.emitFile({\n type: 'asset',\n fileName: WORKERS_CONFIG_FILE,\n source: JSON.stringify(workersConfig ?? null),\n });\n\n // Legacy asset — shape unchanged (no `guardedBy`) for older CLIs.\n this.emitFile({\n type: 'asset',\n fileName: LEGACY_LOCAL_PATHS_FILE,\n source: JSON.stringify(detections.map(({ value, hint, module }) => ({ value, hint, module }))),\n });\n },\n };\n}\n","/**\n * Note: This function depends on local-pkg and should only be used at build-time.\n * It is in a separate file to avoid including local-pkg in runtime code.\n */\n\nimport { statSync } from 'node:fs';\nimport { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { findUp } from 'find-up-simple';\nimport { readJson, readJSON } from 'fs-extra/esm';\nimport { getPackageInfo as getOriginalPackageInfo } from 'local-pkg';\nimport { getPackageName } from './utils';\n\nexport async function getPackageInfo(\n packageName: string,\n options?: { paths?: string[] },\n): Promise<ReturnType<typeof getOriginalPackageInfo>> {\n const pkgInfo = await getOriginalPackageInfo(packageName, options);\n\n // A manifest without a version is still the package root when it is named after the requested package. When a\n // file path is requested there is no package name to compare against, so a named manifest is the root unless an\n // ancestor manifest carries the same name (e.g. engine.io-client/build/esm/package.json inside engine.io-client).\n async function isPackageRoot(pkgJson: { name?: string; version?: string } | undefined, manifestDir: string) {\n if (pkgJson?.version) {\n return true;\n }\n if (!isAbsolute(packageName)) {\n return pkgJson?.name === getPackageName(packageName);\n }\n const name = pkgJson?.name;\n return name ? !(await hasAncestorNamed(name, dirname(manifestDir))) : false;\n }\n\n async function hasAncestorNamed(name: string, dir: string): Promise<boolean> {\n const path = await findUp('package.json', { cwd: dir });\n if (!path) {\n return false;\n }\n const parentDir = dirname(path);\n if ((await readJson(path)).name === name) {\n return true;\n }\n return parentDir !== dirname(parentDir) && hasAncestorNamed(name, dirname(parentDir));\n }\n\n async function searchUpForPackageJson(rootPath: string) {\n const path = await findUp('package.json', {\n cwd: rootPath,\n });\n\n if (!path) {\n return undefined;\n }\n\n const pkgJson = await readJson(path);\n\n if (!(await isPackageRoot(pkgJson, dirname(path)))) {\n return searchUpForPackageJson(dirname(rootPath));\n }\n\n return {\n name: pkgJson.name,\n version: pkgJson.version,\n rootPath: dirname(path),\n packageJsonPath: path,\n packageJson: pkgJson,\n };\n }\n\n // A nested manifest (e.g. dist/esm/package.json with only \"type\") is not the package root, so search up for it.\n if (pkgInfo?.rootPath && !(await isPackageRoot(pkgInfo.packageJson, pkgInfo.rootPath))) {\n return searchUpForPackageJson(dirname(pkgInfo.rootPath));\n }\n\n return pkgInfo;\n}\n\n/**\n * Normalize a resolution base path to a directory path.\n *\n * Callers often pass a module file path (e.g. a rollup module id like\n * `node_modules/@mastra/core/dist/chunk-XYZ.js`) as the parent path. mlly (used by local-pkg)\n * also treats each resolution base as a directory candidate (`<base>/_index.js`), which makes it\n * try to read `<file>/package.json`. That fails with ENOTDIR, which mlly does not tolerate\n * (only ENOENT) and local-pkg then logs the raw error to the console. Using the file's directory\n * as the base avoids this while resolving identically.\n */\nfunction toParentDirectoryUrl(parentPath: string): string {\n let fsPath = resolve(parentPath.startsWith('file://') ? fileURLToPath(parentPath) : parentPath);\n\n try {\n if (statSync(fsPath).isFile()) {\n fsPath = dirname(fsPath);\n }\n } catch {\n // non-existent paths are used as-is\n }\n\n // Keep the trailing separator. Without it, URL resolution treats the directory name as a file\n // and starts package lookup from its parent directory.\n return pathToFileURL(`${fsPath}${sep}`).href;\n}\n\n/**\n * Get package root path\n */\nexport async function getPackageRootPath(packageName: string, parentPath?: string): Promise<string | null> {\n let rootPath: string | null;\n\n try {\n let options: { paths?: string[] } | undefined = undefined;\n if (parentPath) {\n options = {\n paths: [toParentDirectoryUrl(parentPath)],\n };\n }\n\n const pkg = await getPackageInfo(packageName, options);\n rootPath = pkg?.rootPath ?? null;\n } catch {\n rootPath = null;\n }\n\n return rootPath;\n}\n\nasync function readPackageMetadata(\n rootPath: string,\n requestedPackageName: string | null,\n): Promise<{ rootPath: string; version?: string; packageSpec?: string }> {\n try {\n const pkgJson = await readJSON(`${rootPath}/package.json`);\n const version = pkgJson.version;\n const actualPackageName = pkgJson.name;\n const packageSpec =\n version && actualPackageName && requestedPackageName && requestedPackageName !== actualPackageName\n ? `npm:${actualPackageName}@${version}`\n : undefined;\n\n return { rootPath, version, packageSpec };\n } catch {\n return { rootPath };\n }\n}\n\nexport async function getPackageMetadata(\n packageName: string,\n parentPath?: string,\n): Promise<{ rootPath: string | null; version?: string; packageSpec?: string }> {\n const requestedPackageName = getPackageName(packageName);\n const packageNames = [...new Set([packageName, requestedPackageName].filter(Boolean) as string[])];\n let firstRootPath: string | null = null;\n\n for (const name of packageNames) {\n const rootPath = await getPackageRootPath(name, parentPath);\n firstRootPath ??= rootPath;\n if (!rootPath) {\n continue;\n }\n\n const metadata = await readPackageMetadata(rootPath, requestedPackageName ?? null);\n if (metadata.version || metadata.packageSpec) {\n return metadata;\n }\n }\n\n return { rootPath: firstRootPath };\n}\n","import { dirname, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport rollupAlias from '@rollup/plugin-alias';\nimport { resolveModule } from 'local-pkg';\nimport * as resolveExports from 'resolve.exports';\nimport type { Plugin, ResolveIdHook } from 'rollup';\nimport { getPackageInfo } from '../package-info';\nimport { getNodeResolveOptions, getPackageName, isBareModuleSpecifier } from '../utils';\nimport type { BundlerPlatform } from '../utils';\n\nfunction exactMatch(specifier: string) {\n return new RegExp(`^${specifier.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}$`);\n}\n\nasync function resolveBareTarget(id: string, resolveFrom: string, platform: BundlerPlatform) {\n const packageName = getPackageName(id);\n if (!packageName) return undefined;\n\n const resolutionBase = pathToFileURL(`${dirname(resolveFrom)}${sep}`).href;\n const packageInfo = await getPackageInfo(packageName, { paths: [resolutionBase] });\n if (packageInfo?.packageJson.exports) {\n const nodeResolveOptions = getNodeResolveOptions(platform);\n try {\n const [entry] =\n resolveExports.exports(packageInfo.packageJson, id, {\n browser: nodeResolveOptions.browser === true,\n conditions: nodeResolveOptions.exportConditions,\n }) ?? [];\n if (entry) return resolve(packageInfo.rootPath, entry);\n } catch {\n return undefined;\n }\n }\n\n return resolveModule(id, { paths: [resolutionBase] });\n}\n\nexport function moduleAlias(\n alias: Record<string, string>,\n resolveFrom: string,\n platform: BundlerPlatform = 'node',\n): Plugin | null {\n const entries = Object.entries(alias);\n if (entries.length === 0) {\n return null;\n }\n\n const plugin = rollupAlias({\n entries: entries.map(([specifier, target]) => ({\n find: exactMatch(specifier),\n replacement: target,\n customResolver: async function (id, importer, options) {\n const resolveImporter = importer && !importer.startsWith('\\0') ? importer : resolveFrom;\n const resolvedBareTarget = isBareModuleSpecifier(id)\n ? await resolveBareTarget(id, resolveImporter, platform)\n : undefined;\n const resolved = resolvedBareTarget ? undefined : await this.resolve(id, resolveImporter, options);\n\n if (!resolvedBareTarget && !resolved) {\n throw new MastraError({\n id: 'DEPLOYER_ALIAS_TARGET_NOT_FOUND',\n domain: ErrorDomain.DEPLOYER,\n category: ErrorCategory.USER,\n details: {\n alias: specifier,\n target,\n },\n text: `Could not resolve deployer alias \\`${specifier}\\` to \\`${target}\\`.`,\n });\n }\n\n return resolvedBareTarget ?? resolved;\n },\n })),\n });\n\n return {\n ...plugin,\n name: 'module-alias',\n resolveId: {\n order: 'pre',\n handler: plugin.resolveId as ResolveIdHook,\n },\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { join, isAbsolute } from 'node:path';\nimport nodeResolve from '@rollup/plugin-node-resolve';\nimport type { Plugin } from 'rollup';\nimport type { PackageJson } from 'type-fest';\nimport { getPackageRootPath } from '../package-info';\nimport { getPackageName, isExternalProtocolImport, isBareModuleSpecifier } from '../utils';\n\n/**\n * Check if a package has an exports field in its package.json.\n * Results are cached to avoid repeated filesystem reads.\n */\nasync function getPackageJSON(pkgName: string, importer: string): Promise<PackageJson> {\n const pkgRoot = await getPackageRootPath(pkgName, importer);\n if (!pkgRoot) {\n throw new Error(`Package ${pkgName} not found`);\n }\n\n const pkgJSON = JSON.parse(await readFile(join(pkgRoot, 'package.json'), 'utf-8')) as PackageJson;\n return pkgJSON;\n}\n\n/**\n * Rollup plugin that resolves module extensions for external dependencies.\n *\n * This plugin handles ESM compatibility for external imports when node-resolve is not used:\n * - Packages WITH exports field (e.g., hono, date-fns): Keep imports as-is or strip redundant extensions\n * - Packages WITHOUT exports field (e.g., lodash): Add .js extension for direct file imports\n */\nexport function nodeModulesExtensionResolver(): Plugin {\n // Create a single instance of node-resolve to reuse\n const nodeResolvePlugin = nodeResolve();\n\n return {\n name: 'node-modules-extension-resolver',\n async resolveId(id, importer, options) {\n // Only bare package imports are relevant here.\n // Virtual modules (e.g. `\\0virtual:#entry`) are not real filesystem paths, so they can't be\n // used as a resolution base for package lookups.\n if (\n !importer ||\n importer.startsWith('\\0') ||\n !isBareModuleSpecifier(id) ||\n isExternalProtocolImport(id) ||\n isAbsolute(id)\n ) {\n return null;\n }\n\n // Skip direct package imports (e.g., 'lodash', '@mastra/core')\n const parts = id.split('/');\n const isScoped = id.startsWith('@');\n if ((isScoped && parts.length === 2) || (!isScoped && parts.length === 1)) {\n return null;\n }\n\n const pkgName = getPackageName(id);\n if (!pkgName) {\n return null;\n }\n\n try {\n const packageJSON = await getPackageJSON(pkgName, importer);\n // if it has exports, node should be able to rsolve it, if not the exports map is wrong.\n if (!!packageJSON.exports) {\n return null;\n }\n\n const packageRoot = await getPackageRootPath(pkgName, importer);\n // @ts-expect-error - handle is part of resolveId signature\n const nodeResolved = await nodeResolvePlugin.resolveId?.handler?.call(this, id, importer, options);\n // if we cannot resolve it, it's not a valid import so we let node handle it\n if (!nodeResolved?.id) {\n return null;\n }\n\n let filePath = nodeResolved.id;\n if (nodeResolved.resolvedBy === 'commonjs--resolver') {\n filePath = filePath.substring(1).split('?')[0];\n }\n\n const resolvedImportPath = filePath.replace(packageRoot, pkgName);\n\n return {\n id: resolvedImportPath,\n external: true,\n };\n } catch {\n return null;\n }\n },\n };\n}\n","import type { Plugin } from 'rollup';\nimport { isExternalProtocolImport } from '../utils';\n\nexport function protocolExternalResolver({ exclude = ['node:'] }: { exclude?: readonly string[] } = {}): Plugin {\n return {\n name: 'protocol-external-resolver',\n resolveId(id) {\n if (!isExternalProtocolImport(id, exclude)) {\n return null;\n }\n\n return {\n id,\n external: true,\n };\n },\n } satisfies Plugin;\n}\n","import { types as t } from '@babel/core';\nimport type { NodePath, PluginObject, PluginPass } from '@babel/core';\n\ninterface RemoveDeployerState extends PluginPass {\n hasReplaced?: boolean;\n}\n\nexport function removeDeployer(): PluginObject<RemoveDeployerState> {\n // Helper to remove deployer property from an object and clean up its binding\n function removeDeployerFromObject(\n objectExpr: t.ObjectExpression,\n scope: { getBinding: (name: string) => { path?: NodePath } | undefined },\n ): t.ObjectProperty | undefined {\n const deployerProp = objectExpr.properties.find(\n prop => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === 'deployer',\n ) as t.ObjectProperty | undefined;\n\n if (deployerProp) {\n objectExpr.properties = objectExpr.properties.filter(prop => prop !== deployerProp);\n\n // Clean up the deployer binding if it's a reference\n if (t.isIdentifier(deployerProp.value)) {\n const deployerBinding = scope.getBinding(deployerProp.value.name);\n if (deployerBinding) {\n deployerBinding.path?.parentPath?.remove();\n }\n }\n }\n\n return deployerProp;\n }\n\n return {\n name: 'remove-deployer',\n visitor: {\n NewExpression(path, state: RemoveDeployerState) {\n // is a variable declaration\n const varDeclaratorPath = path.findParent(path => t.isVariableDeclarator(path.node));\n if (!varDeclaratorPath) {\n return;\n }\n\n const parentNode = path.parentPath.node;\n // check if it's a const of mastra\n if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== 'mastra') {\n return;\n }\n\n if (!state.hasReplaced) {\n state.hasReplaced = true;\n const newMastraObj = t.cloneNode(path.node);\n if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.length) {\n const objectArg = newMastraObj.arguments[0];\n let foundDeployer = false;\n\n // First, check for direct deployer property\n const directDeployer = removeDeployerFromObject(objectArg, state.file.scope);\n if (directDeployer) {\n foundDeployer = true;\n }\n\n // Then, check spread elements for deployer properties\n for (const prop of objectArg.properties) {\n if (t.isSpreadElement(prop) && t.isIdentifier(prop.argument)) {\n const spreadBinding = state.file.scope.getBinding(prop.argument.name);\n if (spreadBinding?.path && t.isVariableDeclarator(spreadBinding.path.node)) {\n const init = spreadBinding.path.node.init;\n if (t.isObjectExpression(init)) {\n const spreadDeployer = removeDeployerFromObject(init, state.file.scope);\n if (spreadDeployer) {\n foundDeployer = true;\n }\n }\n }\n }\n }\n\n if (foundDeployer) {\n path.replaceWith(newMastraObj);\n }\n }\n }\n },\n },\n } as PluginObject<RemoveDeployerState>;\n}\n","import { transformAsync } from '@babel/core';\nimport type { Plugin, SourceMapInput } from 'rollup';\n\nimport { removeDeployer as removeDeployerBabelPlugin } from '../babel/remove-deployer';\n\nexport function removeDeployer(mastraEntry: string, options?: { sourcemap?: boolean }): Plugin {\n return {\n name: 'remove-deployer',\n transform(code, id) {\n if (id !== mastraEntry) {\n return;\n }\n\n return transformAsync(code, {\n babelrc: false,\n configFile: false,\n filename: id,\n plugins: [removeDeployerBabelPlugin],\n sourceMaps: options?.sourcemap,\n }).then(result => ({\n code: result!.code!,\n map: result!.map! as SourceMapInput,\n }));\n },\n } satisfies Plugin;\n}\n","import * as resolve from 'resolve.exports';\nimport type { Plugin } from 'rollup';\nimport type { WorkspacePackageInfo } from '../../bundler/workspaceDependencies';\nimport { getPackageName, isDependencyPartOfPackage } from '../utils';\n\nexport function subpathExternalsResolver(\n externals: string[],\n workspaceMap: Map<string, WorkspacePackageInfo> = new Map(),\n): Plugin {\n return {\n name: 'subpath-externals-resolver',\n resolveId(id) {\n if (id.startsWith('.') || id.startsWith('/')) {\n return null;\n }\n\n const isPartOfExternals = externals.some(external => isDependencyPartOfPackage(id, external));\n if (!isPartOfExternals) {\n return null;\n }\n\n const packageName = getPackageName(id);\n const workspacePackage = packageName ? workspaceMap.get(packageName) : undefined;\n if (packageName && workspacePackage?.exports !== undefined && id !== packageName) {\n const subpath = `.${id.slice(packageName.length)}`;\n try {\n resolve.exports({ name: packageName, exports: workspacePackage.exports }, subpath);\n } catch {\n this.error(`Could not resolve workspace package subpath \"${id}\".`);\n }\n }\n\n return {\n id,\n external: true,\n };\n },\n } satisfies Plugin;\n}\n","import fs from 'node:fs';\nimport { builtinModules } from 'node:module';\nimport path from 'node:path';\nimport { createPathsMatcher, parseTsconfig } from 'get-tsconfig';\nimport type { PathsMatcher } from 'get-tsconfig';\nimport type { Plugin } from 'rollup';\n\nconst PLUGIN_NAME = 'tsconfig-paths';\nconst JS_IMPORT_SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\nconst CORE_MODULES = new Set([...builtinModules, ...builtinModules.map(moduleName => `node:${moduleName}`)]);\n\nexport type PluginOptions = {\n tsConfigPath?: string;\n respectCoreModule?: boolean;\n localResolve?: boolean;\n cwd?: string;\n};\n\n/**\n * Check if a tsconfig file has path mappings configured.\n * Exported for testing purposes.\n *\n * @param tsConfigPath - Path to the tsconfig.json file\n * @returns true if the tsconfig has paths configured or extends another config, false otherwise\n */\nexport function hasPaths(tsConfigPath: string): boolean {\n try {\n const paths = parseTsconfig(tsConfigPath).compilerOptions?.paths;\n return !!paths && Object.keys(paths).length > 0;\n } catch {\n return false;\n }\n}\n\nexport function tsConfigPaths({\n tsConfigPath,\n respectCoreModule = true,\n localResolve,\n cwd,\n}: PluginOptions = {}): Plugin {\n const matcherCache = new Map<string, { matcher: PathsMatcher | null; patterns: string[] } | null>();\n\n function resolveImportToSourceFile(moduleName: string): string {\n if (fs.existsSync(moduleName) && fs.statSync(moduleName).isFile()) {\n return moduleName;\n }\n\n const parsed = path.parse(moduleName);\n const candidates =\n parsed.ext === '.js'\n ? JS_IMPORT_SOURCE_EXTENSIONS.map(extension => path.join(parsed.dir, `${parsed.name}${extension}`))\n : parsed.ext\n ? []\n : [\n ...JS_IMPORT_SOURCE_EXTENSIONS.map(extension => `${moduleName}${extension}`),\n ...JS_IMPORT_SOURCE_EXTENSIONS.map(extension => path.join(moduleName, `index${extension}`)),\n ];\n\n return candidates.find(candidate => fs.existsSync(candidate)) ?? moduleName;\n }\n\n // Find tsconfig.json file starting from a directory and walking up\n function findTsConfigForFile(filePath: string): string | null {\n let currentDir = path.dirname(filePath);\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const tsConfigPath = path.join(currentDir, 'tsconfig.json');\n\n if (fs.existsSync(tsConfigPath)) {\n // Check if this tsconfig has path mappings\n if (hasPaths(tsConfigPath)) {\n return tsConfigPath;\n }\n }\n\n // Also check for tsconfig.base.json (common in NX)\n const tsConfigBasePath = path.join(currentDir, 'tsconfig.base.json');\n if (fs.existsSync(tsConfigBasePath)) {\n if (hasPaths(tsConfigBasePath)) {\n return tsConfigBasePath;\n }\n }\n\n currentDir = path.dirname(currentDir);\n }\n\n return null;\n }\n\n function getMatcherForFile(filePath: string): { matcher: PathsMatcher | null; patterns: string[] } | null {\n const configPath = tsConfigPath ?? findTsConfigForFile(filePath);\n if (!configPath) {\n return null;\n }\n\n if (!matcherCache.has(configPath)) {\n const config = parseTsconfig(configPath);\n const patterns = Object.keys(config.compilerOptions?.paths ?? {});\n let matcher: PathsMatcher | null;\n\n try {\n matcher = createPathsMatcher({ path: configPath, config });\n } catch {\n const configWithBaseUrl = {\n ...config,\n compilerOptions: { ...config.compilerOptions, baseUrl: path.dirname(configPath) },\n };\n matcher = createPathsMatcher({ path: configPath, config: configWithBaseUrl });\n }\n\n matcherCache.set(configPath, { matcher, patterns });\n }\n\n return matcherCache.get(configPath) ?? null;\n }\n\n function resolveAliases(request: string, importer: string): string[] {\n if (respectCoreModule && CORE_MODULES.has(request)) {\n return [];\n }\n\n const matchedConfig = getMatcherForFile(importer);\n if (\n !matchedConfig?.patterns.some(pattern => {\n const wildcardIndex = pattern.indexOf('*');\n return wildcardIndex === -1\n ? request === pattern\n : request.startsWith(pattern.slice(0, wildcardIndex)) && request.endsWith(pattern.slice(wildcardIndex + 1));\n })\n ) {\n return [];\n }\n\n return matchedConfig.matcher?.(request) ?? [];\n }\n\n return {\n name: PLUGIN_NAME,\n resolveId: {\n order: 'pre',\n async handler(request, importer, options) {\n if (!importer || request.startsWith('\\0') || importer.charCodeAt(0) === 0) {\n return null;\n }\n\n // Convert relative paths to absolute to ensure proper tsconfig path resolution\n // This allows path aliases to work regardless of how the importer path is provided\n if (!path.isAbsolute(importer)) {\n importer = path.resolve(cwd ?? process.cwd(), importer);\n }\n\n const moduleNames = resolveAliases(request, importer);\n for (const moduleName of moduleNames) {\n const resolvedModuleName = resolveImportToSourceFile(moduleName);\n const resolved = await this.resolve(resolvedModuleName, importer, { skipSelf: true, ...options });\n\n if (resolved) {\n return {\n ...resolved,\n meta: {\n ...resolved.meta,\n [PLUGIN_NAME]: {\n resolved: true,\n },\n },\n };\n }\n }\n\n const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });\n if (!resolved) {\n return null;\n }\n\n // If localResolve is true, we need to check if the importer has been resolved by the tsconfig-paths plugin\n // if so, we need to resolve the request from the importer instead of the root and mark it as external\n if (localResolve) {\n const importerInfo = this.getModuleInfo(importer);\n const importerPluginMeta = importerInfo?.meta?.[PLUGIN_NAME];\n\n if (\n !path.isAbsolute(request) &&\n !request.startsWith('./') &&\n !request.startsWith('../') &&\n importerPluginMeta?.resolved\n ) {\n return {\n ...resolved,\n external: !request.startsWith('hono/') && request !== 'hono',\n };\n }\n }\n\n return {\n ...resolved,\n meta: {\n ...(resolved.meta || {}),\n },\n };\n },\n },\n } satisfies Plugin;\n}\n","import { join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport nodeResolve from '@rollup/plugin-node-resolve';\nimport { rollup } from 'rollup';\nimport type { InputOptions, OutputOptions, Plugin } from 'rollup';\nimport { minify as esbuildMinify } from 'rollup-plugin-esbuild';\nimport type { WorkspacePackageInfo } from '../bundler/workspaceDependencies';\nimport { esbuild } from './plugins/esbuild';\nimport { esmShim } from './plugins/esm-shim';\nimport { localStorageDetector } from './plugins/local-storage-detector';\nimport { moduleAlias } from './plugins/module-alias';\nimport { nodeModulesExtensionResolver } from './plugins/node-modules-extension-resolver';\nimport { protocolExternalResolver } from './plugins/protocol-external-resolver';\nimport { removeDeployer } from './plugins/remove-deployer';\nimport { subpathExternalsResolver } from './plugins/subpath-externals-resolver';\nimport { tsConfigPaths } from './plugins/tsconfig-paths';\nimport type { ExternalDependencyInfo } from './types';\nimport { getPackageName, getNodeResolveOptions, slash } from './utils';\nimport type { BundlerPlatform } from './utils';\n\nexport function mastraInternalAliasPlugin(entryFile: string): Plugin {\n const normalizedEntryFile = slash(entryFile);\n\n return {\n name: 'mastra-internal-alias',\n resolveId: {\n order: 'pre',\n handler(id) {\n if (id === '#server') {\n return slash(fileURLToPath(import.meta.resolve('@mastra/deployer/server')));\n }\n\n if (id.startsWith('@mastra/server/')) {\n return fileURLToPath(import.meta.resolve(id));\n }\n\n if (id === '#mastra') {\n return normalizedEntryFile;\n }\n },\n },\n } satisfies Plugin;\n}\n\nexport function mastraToolsAliasPlugin(): Plugin {\n return {\n name: 'tools-rewriter',\n resolveId(id: string) {\n if (id === '#tools') {\n return {\n id: './tools.mjs',\n external: true,\n };\n }\n },\n };\n}\n\nexport async function getInputOptions(\n entryFile: string,\n analyzedBundleInfo: {\n dependencies: Map<string, string>;\n externalDependencies: Map<string, ExternalDependencyInfo>;\n workspaceMap: Map<string, WorkspacePackageInfo>;\n projectType?: string;\n },\n platform: BundlerPlatform,\n env: Record<string, string> = { 'process.env.NODE_ENV': JSON.stringify('production') },\n {\n sourcemap = false,\n minify = false,\n isDev = false,\n projectRoot,\n workspaceRoot = undefined,\n enableEsmShim = true,\n externalsPreset = false,\n explicitExternals = [],\n alias = {},\n }: {\n sourcemap?: boolean;\n minify?: boolean;\n isDev?: boolean;\n workspaceRoot?: string;\n projectRoot: string;\n enableEsmShim?: boolean;\n externalsPreset?: boolean;\n explicitExternals?: string[];\n alias?: Record<string, string>;\n },\n): Promise<InputOptions> {\n const nodeResolvePlugin = nodeResolve({\n ...getNodeResolveOptions(platform),\n rootDir: projectRoot,\n modulePaths: workspaceRoot ? [join(workspaceRoot, 'node_modules')] : [],\n });\n\n const externalsCopy = new Set<string>(analyzedBundleInfo.externalDependencies.keys());\n const externals = externalsPreset ? explicitExternals : Array.from(externalsCopy);\n const aliasSources = new Set(Object.keys(alias));\n const rollupExternals = externals.filter(external => !aliasSources.has(external));\n\n return {\n logLevel: process.env.MASTRA_BUNDLER_DEBUG === 'true' ? 'debug' : 'silent',\n treeshake: 'smallest',\n preserveSymlinks: true,\n external: externalsPreset ? [] : rollupExternals,\n plugins: [\n protocolExternalResolver(),\n moduleAlias(alias, entryFile, platform),\n subpathExternalsResolver(externals, analyzedBundleInfo.workspaceMap),\n {\n name: 'alias-optimized-deps',\n resolveId(id: string) {\n if (!analyzedBundleInfo.dependencies.has(id)) {\n return null;\n }\n\n const filename = analyzedBundleInfo.dependencies.get(id)!;\n const absolutePath = join(workspaceRoot || projectRoot, filename);\n\n // During `mastra dev` we want to keep deps as external\n if (isDev) {\n return {\n id: process.platform === 'win32' ? pathToFileURL(absolutePath).href : absolutePath,\n external: true,\n };\n }\n\n // For production builds return the absolute path as-is so Rollup can handle itself\n return {\n id: absolutePath,\n external: false,\n };\n },\n } satisfies Plugin,\n mastraInternalAliasPlugin(entryFile),\n tsConfigPaths({ cwd: projectRoot }),\n mastraToolsAliasPlugin(),\n esbuild({\n platform,\n define: env,\n }),\n optimizeLodashImports({\n include: '**/*.{js,ts,mjs,cjs}',\n }),\n commonjs({\n extensions: ['.js', '.ts', '.cjs'],\n transformMixedEsModules: true,\n esmExternals(id) {\n return externals.includes(id);\n },\n }),\n enableEsmShim ? esmShim() : undefined,\n externalsPreset ? nodeModulesExtensionResolver() : nodeResolvePlugin,\n // for debugging\n // {\n // name: 'logger',\n // //@ts-expect-error\n // resolveId(id, ...args) {\n // console.log({ id, args });\n // },\n // // @ts-expect-error\n // transform(code, id) {\n // if (code.includes('class Duplexify ')) {\n // console.log({ duplex: id });\n // }\n // },\n // },\n json(),\n localStorageDetector(workspaceRoot || projectRoot),\n removeDeployer(entryFile, { sourcemap }),\n // treeshake unused imports\n esbuild({\n include: entryFile,\n platform,\n }),\n // Runs at renderChunk, so the emitted chunks are minified as a whole rather\n // than module by module. Last in the list so nothing transforms after it.\n // `sourceMap` follows the build's own setting: the plugin defaults it to true,\n // which would build a map Rollup then discards on a non-sourcemap build.\n minify ? esbuildMinify({ target: 'node20', sourceMap: sourcemap }) : null,\n ].filter(Boolean),\n } satisfies InputOptions;\n}\n\nexport async function createBundler(\n inputOptions: InputOptions,\n outputOptions: Partial<OutputOptions> & { dir: string },\n) {\n const bundler = await rollup(inputOptions);\n\n return {\n write: () => {\n return bundler.write({\n ...outputOptions,\n format: 'esm',\n entryFileNames: '[name].mjs',\n chunkFileNames: '[name].mjs',\n });\n },\n close: () => {\n return bundler.close();\n },\n };\n}\n\n/**\n * Checks whether a Rollup warning is an UNRESOLVED_IMPORT for a workspace package.\n * Returns the original import specifier if it's a workspace package that leaked\n * through, or undefined if it's not.\n */\nexport function getUnresolvedWorkspaceImport(\n warning: { code: string; source?: string; id?: string },\n workspaceMap: Map<string, WorkspacePackageInfo>,\n): string | undefined {\n if (warning.code !== 'UNRESOLVED_IMPORT') {\n return undefined;\n }\n\n const src = warning.source ?? warning.id ?? '';\n if (!src) {\n return undefined;\n }\n\n const pkgName = getPackageName(src);\n if (pkgName && workspaceMap.has(pkgName)) {\n return src;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAEA,SAAgB,QAAQ,UAAiD,CAAC,GAAG;CAC3E,OAAO,gBAAgB;EACrB,QAAQ;EACR,UAAU;EACV,QAAQ;EACR,GAAG;CACL,CAAC;AACH;;;ACJA,MAAM,2BAA2B;AACjC,MAAM,0BAA0B;;;;;;;;;;;AAYhC,SAAgB,UAAkB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