{"version":3,"sources":["../src/bundler/index.ts"],"names":["MastraBundler","emptyDir","ensureDir","join","writeFile","createBundler","getBundlerOptions","analyzeBundle","DepsService","fsExtra","execSync","rm","stat","copy","existsSync","MastraError","ErrorDomain","ErrorCategory","getWorkspaceInformation","pkg","dirname","getInputOptions","virtual","slash","posix","glob","path","FileService","error","isBareModuleSpecifier"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBO,IAAM,UAAA,0BAAoB,YAAY;AAEtC,IAAe,OAAA,GAAf,cAA+BA,qBAAA,CAAc;AAAA,EACxC,gBAAA,GAAmB,QAAA;AAAA,EACnB,SAAA,GAAY,QAAA;AAAA,EACZ,QAAA,GAA4B,MAAA;AAAA,EAEtC,WAAA,CAAY,IAAA,EAAc,SAAA,GAAoC,SAAA,EAAW;AACvE,IAAA,KAAA,CAAM,EAAE,IAAA,EAAM,SAAA,EAAW,CAAA;AAAA,EAC3B;AAAA,EAEA,MAAM,QAAQ,eAAA,EAAwC;AAEpD,IAAA,MAAMC,iBAAS,eAAe,CAAA;AAE9B,IAAA,MAAMC,iBAAA,CAAUC,SAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,gBAAgB,CAAC,CAAA;AAC5D,IAAA,MAAMD,iBAAA,CAAUC,SAAA,CAAK,eAAA,EAAiB,IAAA,CAAK,SAAS,CAAC,CAAA;AAAA,EACvD;AAAA,EAEA,MAAM,gBAAA,CACJ,eAAA,EACA,YAAA,EACA,WAAA,EACA;AACA,IAAA,IAAA,CAAK,MAAA,CAAO,MAAM,gCAAgC,CAAA;AAElD,IAAA,MAAMD,kBAAU,eAAe,CAAA;AAC/B,IAAA,MAAM,OAAA,GAAUC,SAAA,CAAK,eAAA,EAAiB,cAAc,CAAA;AAEpD,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAAI;AAChC,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,CAAA,IAAK,YAAA,CAAa,SAAQ,EAAG;AACjD,MAA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O,IAAA,CAAK,aAAA,EAAe,EAAE,KAAA,EAAO,aAAa,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"chunk-7BCMZXLF.cjs","sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, posix } from 'node:path';\nimport { MastraBundler } from '@mastra/core/bundler';\nimport { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';\nimport type { Config } from '@mastra/core/mastra';\nimport virtual from '@rollup/plugin-virtual';\nimport * as pkg from 'empathic/package';\nimport fsExtra, { copy, ensureDir, emptyDir } from 'fs-extra/esm';\nimport type { InputOptions, OutputOptions } from 'rollup';\nimport { glob } from 'tinyglobby';\nimport { analyzeBundle } from '../build/analyze';\nimport { createBundler as createBundlerUtil, getInputOptions } from '../build/bundler';\nimport { getBundlerOptions } from '../build/bundlerOptions';\nimport type { BundlerOptions, ExternalDependencyInfo } from '../build/types';\nimport type { BundlerPlatform } from '../build/utils';\nimport { isBareModuleSpecifier, slash } from '../build/utils';\nimport { DepsService } from '../services/deps';\nimport { FileService } from '../services/fs';\nimport { getWorkspaceInformation } from './workspaceDependencies';\n\nexport type { BundlerOptions } from '../build/types';\nexport type { BundlerPlatform } from '../build/utils';\n\nexport const IS_DEFAULT = Symbol('IS_DEFAULT');\n\nexport abstract class Bundler extends MastraBundler {\n  protected analyzeOutputDir = '.build';\n  protected outputDir = 'output';\n  protected platform: BundlerPlatform = 'node';\n\n  constructor(name: string, component: 'BUNDLER' | 'DEPLOYER' = 'BUNDLER') {\n    super({ name, component });\n  }\n\n  async prepare(outputDirectory: string): Promise<void> {\n    // Clean up the output directory first\n    await emptyDir(outputDirectory);\n\n    await ensureDir(join(outputDirectory, this.analyzeOutputDir));\n    await ensureDir(join(outputDirectory, this.outputDir));\n  }\n\n  async writePackageJson(\n    outputDirectory: string,\n    dependencies: Map<string, string | ExternalDependencyInfo>,\n    resolutions?: Record<string, string>,\n  ) {\n    this.logger.debug(\"Writing project's package.json\");\n\n    await ensureDir(outputDirectory);\n    const pkgPath = join(outputDirectory, 'package.json');\n\n    const dependenciesMap = new Map();\n    for (const [key, value] of dependencies.entries()) {\n      const dependencyValue = typeof value === 'string' ? value : (value.packageSpec ?? value.version ?? 'latest');\n      if (key.startsWith('@')) {\n        // Handle scoped packages (e.g. @org/package)\n        const pkgChunks = key.split('/');\n        dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);\n      } else {\n        // For non-scoped packages, take only the first part before any slash\n        const pkgName = key.split('/')[0] || key;\n        dependenciesMap.set(pkgName, dependencyValue);\n      }\n    }\n\n    await writeFile(\n      pkgPath,\n      JSON.stringify(\n        {\n          name: 'server',\n          version: '1.0.0',\n          private: true,\n          type: 'module',\n          main: 'index.mjs',\n          scripts: {\n            start: 'node ./index.mjs',\n          },\n          dependencies: Object.fromEntries(dependenciesMap.entries()),\n          ...(Object.keys(resolutions ?? {}).length > 0 && { resolutions }),\n        },\n        null,\n        2,\n      ),\n    );\n  }\n\n  protected createBundler(inputOptions: InputOptions, outputOptions: Partial<OutputOptions> & { dir: string }) {\n    return createBundlerUtil(inputOptions, outputOptions);\n  }\n\n  protected async getUserBundlerOptions(\n    mastraEntryFile: string,\n    outputDirectory: string,\n  ): Promise<NonNullable<Config['bundler']>> {\n    const defaultBundlerOptions: Config['bundler'] = {\n      externals: [],\n      sourcemap: false,\n      transpilePackages: [],\n      [IS_DEFAULT]: true,\n    } as const;\n\n    try {\n      const bundlerOptions = await getBundlerOptions(mastraEntryFile, outputDirectory);\n\n      return bundlerOptions ?? defaultBundlerOptions;\n    } catch (error) {\n      this.logger.debug('Failed to get bundler options, sourcemap will be disabled', { error });\n    }\n\n    return defaultBundlerOptions;\n  }\n\n  protected async analyze(entry: string | string[], mastraFile: string, outputDirectory: string) {\n    return await analyzeBundle(\n      ([] as string[]).concat(entry),\n      mastraFile,\n      {\n        outputDir: join(outputDirectory, this.analyzeOutputDir),\n        projectRoot: outputDirectory,\n        platform: this.platform,\n      },\n      this.logger,\n    );\n  }\n\n  protected async installDependencies(outputDirectory: string, rootDir = process.cwd()) {\n    const deps = new DepsService(rootDir);\n    deps.__setLogger(this.logger);\n\n    await deps.install({ dir: join(outputDirectory, this.outputDir) });\n  }\n\n  /**\n   * Generate a package-lock.json for the output directory so that deploy targets\n   * can use `npm ci` instead of `npm install`, skipping version resolution entirely.\n   * This is a lockfile-only operation — no packages are downloaded.\n   *\n   * Temporarily moves node_modules out of the way because pnpm's symlink-based\n   * layout confuses npm's arborist, then restores it afterwards so that\n   * `mastra start` (or wrangler) can still resolve dependencies at runtime.\n   */\n  private async generateNpmLockfile(outputDir: string): Promise<void> {\n    const nodeModules = join(outputDir, 'node_modules');\n    const nodeModulesTmp = join(outputDir, 'node_modules.__tmp');\n    let movedNodeModules = false;\n    try {\n      // Move node_modules aside — pnpm's symlink layout confuses npm's arborist\n      if (await fsExtra.pathExists(nodeModules)) {\n        await fsExtra.move(nodeModules, nodeModulesTmp, { overwrite: true });\n        movedNodeModules = true;\n      }\n      execSync('npm install --package-lock-only --force', {\n        cwd: outputDir,\n        stdio: 'pipe',\n        timeout: 60_000,\n      });\n    } catch {\n      this.logger.warn('Failed to generate package-lock.json — deploy will fall back to npm install');\n    } finally {\n      // Restore node_modules so runtime resolution works\n      if (movedNodeModules) {\n        await rm(nodeModules, { recursive: true, force: true });\n        await fsExtra.move(nodeModulesTmp, nodeModules, { overwrite: true });\n      }\n    }\n  }\n\n  protected async copyPublic(mastraDir: string, outputDirectory: string) {\n    const publicDir = join(mastraDir, 'public');\n\n    try {\n      await stat(publicDir);\n    } catch {\n      return;\n    }\n\n    await copy(publicDir, join(outputDirectory, this.outputDir));\n  }\n\n  protected async copyDOTNPMRC({\n    rootDir = process.cwd(),\n    outputDirectory,\n  }: {\n    rootDir?: string;\n    outputDirectory: string;\n  }) {\n    const sourceDotNpmRcPath = join(rootDir, '.npmrc');\n    const targetDotNpmRcPath = join(outputDirectory, this.outputDir, '.npmrc');\n\n    try {\n      await stat(sourceDotNpmRcPath);\n      await copy(sourceDotNpmRcPath, targetDotNpmRcPath);\n    } catch {\n      return;\n    }\n  }\n\n  /**\n   * Writes the `mastra-project.json` deployment marker for Software Factory\n   * projects after public assets have been copied. Verifies that the Factory\n   * SPA (`factory/index.html`) exists in the output before emitting the marker.\n   */\n  protected async writeFactoryMarker(outputDirectory: string): Promise<void> {\n    const outputDir = join(outputDirectory, this.outputDir);\n    const factoryIndex = join(outputDir, 'factory', 'index.html');\n    if (!existsSync(factoryIndex)) {\n      throw new MastraError({\n        id: 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING',\n        text: 'Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.',\n        domain: ErrorDomain.DEPLOYER,\n        category: ErrorCategory.SYSTEM,\n      });\n    }\n    await writeFile(\n      join(outputDir, 'mastra-project.json'),\n      JSON.stringify({ schemaVersion: 1, projectType: 'factory', assets: { ui: 'factory' } }, null, 2),\n    );\n    this.logger.info('Wrote mastra-project.json for Software Factory project');\n  }\n\n  protected async getBundlerOptions(\n    serverFile: string,\n    mastraEntryFile: string,\n    analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n    toolsPaths: (string | string[])[],\n    { enableSourcemap, enableEsmShim, externals }: BundlerOptions,\n  ) {\n    const { workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile });\n    const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });\n    const projectRoot = closestPkgJson ? dirname(closestPkgJson) : process.cwd();\n\n    const inputOptions: InputOptions = await getInputOptions(\n      mastraEntryFile,\n      analyzedBundleInfo,\n      this.platform,\n      {\n        'process.env.NODE_ENV': JSON.stringify('production'),\n      },\n      { sourcemap: enableSourcemap, workspaceRoot, projectRoot, enableEsmShim, externalsPreset: externals === true },\n    );\n    const isVirtual = serverFile.includes('\\n') || !existsSync(serverFile);\n    const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n\n    if (isVirtual) {\n      inputOptions.input = { index: '#entry', ...toolsInputOptions };\n\n      if (Array.isArray(inputOptions.plugins)) {\n        inputOptions.plugins.unshift(virtual({ '#entry': serverFile }));\n      } else {\n        inputOptions.plugins = [virtual({ '#entry': serverFile })];\n      }\n    } else {\n      inputOptions.input = { index: serverFile, ...toolsInputOptions };\n    }\n\n    return inputOptions;\n  }\n\n  getAllToolPaths(mastraDir: string, toolsPaths: (string | string[])[] = []): (string | string[])[] {\n    // Normalize Windows paths to forward slashes for consistent handling\n    const normalizedMastraDir = slash(mastraDir);\n\n    // Prepare default tools paths with glob patterns\n    const defaultToolsPath = posix.join(normalizedMastraDir, 'tools/**/*.{js,ts}');\n    const defaultToolsIgnorePaths = [\n      `!${posix.join(normalizedMastraDir, 'tools/**/*.{test,spec}.{js,ts}')}`,\n      `!${posix.join(normalizedMastraDir, 'tools/**/__tests__/**')}`,\n    ];\n\n    // Combine default path with ignore patterns\n    const defaultPaths = [defaultToolsPath, ...defaultToolsIgnorePaths];\n\n    // If no tools paths provided, use only the default paths\n    if (toolsPaths.length === 0) {\n      return [defaultPaths];\n    }\n\n    // If tools paths are provided, add the default paths to ensure standard tools are always included\n    return [...toolsPaths, defaultPaths];\n  }\n\n  async listToolsInputOptions(toolsPaths: (string | string[])[]) {\n    const inputs: Record<string, string> = {};\n\n    for (const toolPath of toolsPaths) {\n      const expandedPaths = await glob(toolPath, {\n        absolute: true,\n        expandDirectories: false,\n      });\n\n      for (const path of expandedPaths) {\n        if (await fsExtra.pathExists(path)) {\n          const fileService = new FileService();\n          const entryFile = fileService.getFirstExistingFile([\n            join(path, 'index.ts'),\n            join(path, 'index.js'),\n            path, // if path itself is a file\n          ]);\n\n          // if it doesn't exist or is a dir skip it. using a dir as a tool will crash the process\n          if (!entryFile || (await stat(entryFile)).isDirectory()) {\n            this.logger.warn('No entry file found, skipping', { path });\n            continue;\n          }\n\n          const uniqueToolID = crypto.randomUUID();\n          // Normalize Windows paths to forward slashes for consistent handling\n          const normalizedEntryFile = entryFile.replaceAll('\\\\', '/');\n          inputs[`tools/${uniqueToolID}`] = normalizedEntryFile;\n        } else {\n          this.logger.warn('Tool path does not exist, skipping', { path });\n        }\n      }\n    }\n\n    return inputs;\n  }\n\n  protected async _bundle(\n    serverFile: string,\n    mastraEntryFile: string,\n    {\n      projectRoot,\n      outputDirectory,\n      enableEsmShim = true,\n    }: {\n      projectRoot: string;\n      outputDirectory: string;\n      enableEsmShim?: boolean;\n    },\n    toolsPaths: (string | string[])[] = [],\n    bundleLocation: string = join(outputDirectory, this.outputDir),\n  ): Promise<void> {\n    const analyzeDir = join(outputDirectory, this.analyzeOutputDir);\n\n    const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n    const internalBundlerOptions: BundlerOptions = {\n      enableSourcemap: !!bundlerOptions.sourcemap,\n      externals: bundlerOptions.externals ?? [],\n      enableEsmShim,\n      dynamicPackages: bundlerOptions.dynamicPackages,\n    };\n\n    let analyzedBundleInfo;\n    try {\n      const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths);\n      analyzedBundleInfo = await analyzeBundle(\n        [serverFile, ...Object.values(resolvedToolsPaths)],\n        mastraEntryFile,\n        {\n          outputDir: analyzeDir,\n          projectRoot,\n          platform: this.platform,\n          bundlerOptions: internalBundlerOptions,\n        },\n        this.logger,\n      );\n    } catch (error) {\n      const message = error instanceof Error ? error.message : String(error);\n\n      if (error instanceof MastraError) {\n        throw error;\n      }\n\n      throw new MastraError(\n        {\n          id: 'DEPLOYER_BUNDLER_ANALYZE_FAILED',\n          text: `Failed to analyze Mastra application: ${message}`,\n          domain: ErrorDomain.DEPLOYER,\n          category: ErrorCategory.SYSTEM,\n        },\n        error,\n      );\n    }\n\n    const dependenciesToInstall = new Map<string, ExternalDependencyInfo>();\n    for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {\n      if (analyzedBundleInfo.workspaceMap.has(dep) || !isBareModuleSpecifier(dep)) {\n        continue;\n      }\n\n      dependenciesToInstall.set(dep, depInfo);\n    }\n\n    try {\n      await this.writePackageJson(join(outputDirectory, this.outputDir), dependenciesToInstall);\n\n      this.logger.info('Bundling Mastra application');\n\n      const inputOptions: InputOptions = await this.getBundlerOptions(\n        serverFile,\n        mastraEntryFile,\n        analyzedBundleInfo,\n        toolsPaths,\n        internalBundlerOptions,\n      );\n\n      const bundler = await this.createBundler(\n        {\n          ...inputOptions,\n          logLevel: inputOptions.logLevel === 'silent' ? 'warn' : inputOptions.logLevel,\n          onwarn: warning => {\n            if (warning.code === 'CIRCULAR_DEPENDENCY') {\n              if (warning.ids?.[0]?.includes('node_modules')) {\n                return;\n              }\n\n              this.logger.warn('Circular dependency found', {\n                dependency: warning.message.replace('Circular dependency: ', ''),\n              });\n            }\n          },\n        },\n        {\n          dir: bundleLocation,\n          manualChunks: {\n            mastra: ['#mastra'],\n          },\n          sourcemap: internalBundlerOptions.enableSourcemap,\n        },\n      );\n\n      await bundler.write();\n      const toolImports: string[] = [];\n      const toolsExports: string[] = [];\n      Array.from(Object.keys(inputOptions.input || {}))\n        .filter(key => key.startsWith('tools/'))\n        .forEach((key, index) => {\n          const toolExport = `tool${index}`;\n          toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);\n          toolsExports.push(toolExport);\n        });\n\n      await writeFile(\n        join(bundleLocation, 'tools.mjs'),\n        `${toolImports.join('\\n')}\n\nexport const tools = [${toolsExports.join(', ')}]`,\n      );\n      this.logger.info('Bundling Mastra done');\n\n      this.logger.info('Copying public files');\n      await this.copyPublic(dirname(mastraEntryFile), outputDirectory);\n      this.logger.info('Done copying public files');\n\n      // For Software Factory projects, write a deterministic deployment marker\n      // after public assets (including the SPA) have been copied.\n      if (analyzedBundleInfo.projectType === 'factory') {\n        await this.writeFactoryMarker(outputDirectory);\n      }\n\n      this.logger.info('Copying .npmrc file');\n      await this.copyDOTNPMRC({ outputDirectory, rootDir: projectRoot });\n\n      this.logger.info('Done copying .npmrc file');\n\n      this.logger.info('Installing dependencies');\n      await this.installDependencies(outputDirectory, projectRoot);\n      this.logger.info('Done installing dependencies');\n\n      this.logger.info('Generating package-lock.json for deploy');\n      await this.generateNpmLockfile(join(outputDirectory, this.outputDir));\n      this.logger.info('Done generating package-lock.json');\n    } catch (error) {\n      if (error instanceof MastraError && error.id === 'DEPLOYER_BUNDLER_FACTORY_UI_MISSING') {\n        throw error;\n      }\n\n      const message = error instanceof Error ? error.message : String(error);\n      throw new MastraError(\n        {\n          id: 'DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED',\n          text: `Failed during bundler bundle stage: ${message}`,\n          domain: ErrorDomain.DEPLOYER,\n          category: ErrorCategory.SYSTEM,\n        },\n        error,\n      );\n    }\n  }\n\n  async lint(_entryFile: string, _outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n    const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);\n    const toolsLength = Object.keys(toolsInputOptions).length;\n    if (toolsLength > 0) {\n      this.logger.info('Found tools', { count: toolsLength });\n    }\n  }\n}\n"]}