{"version":3,"file":"index.cjs","names":["Deployer"],"sources":["../src/routes.ts","../src/index.ts"],"sourcesContent":["type VercelRoutesOptions = {\n  studio: boolean;\n};\n\nexport function getVercelRoutes({ studio }: VercelRoutesOptions) {\n  return studio\n    ? [\n        { src: '^/$', dest: '/index.html' },\n        { src: '/api/(.*)', dest: '/' },\n        { src: '/health', dest: '/' },\n        { handle: 'filesystem' as const },\n        { src: '/(.*)', dest: '/index.html', check: true },\n      ]\n    : [{ src: '/(.*)', dest: '/' }];\n}\n","import { readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\nimport type { Config } from '@mastra/core/mastra';\nimport { Deployer } from '@mastra/deployer';\nimport { escapeStudioHtmlValue, injectStudioHtmlConfig } from '@mastra/deployer/build';\nimport { copy, move } from 'fs-extra/esm';\nimport { getVercelRoutes } from './routes';\nimport type { VcConfig, VcConfigOverrides, VercelDeployerOptions } from './types';\n\nexport class VercelDeployer extends Deployer {\n  private vcConfigOverrides: VcConfigOverrides = {};\n  private studio: boolean;\n\n  constructor(options: VercelDeployerOptions = {}) {\n    super({ name: 'VERCEL' });\n    this.outputDir = join('.vercel', 'output', 'functions', 'index.func');\n    this.studio = options.studio ?? false;\n\n    const { studio, ...overrides } = options;\n    this.vcConfigOverrides = { ...overrides };\n  }\n\n  protected async getUserBundlerOptions(\n    mastraEntryFile: string,\n    outputDirectory: string,\n  ): Promise<NonNullable<Config['bundler']>> {\n    const bundlerOptions = await super.getUserBundlerOptions(mastraEntryFile, outputDirectory);\n\n    // Always force externals: true for Vercel deployments.\n    // Vercel serverless functions resolve dependencies from node_modules,\n    // so bundling them inline serves no purpose. Bundling inline can also cause\n    // circular module evaluation deadlocks when dynamic imports produce chunks\n    // that depend back on the entry module via static imports, resulting in\n    // \"Detected unsettled top-level await\" errors (Node.js exit code 13).\n    // See: https://github.com/mastra-ai/mastra/issues/14860\n    return {\n      ...bundlerOptions,\n      externals: true,\n    };\n  }\n\n  async prepare(outputDirectory: string): Promise<void> {\n    await super.prepare(outputDirectory);\n\n    this.writeVercelJSON(join(outputDirectory, this.outputDir, '..', '..'));\n\n    if (this.studio) {\n      const __filename = fileURLToPath(import.meta.url);\n      const __dirname = dirname(__filename);\n\n      const studioSource = join(dirname(__dirname), 'dist', 'studio');\n      const staticDir = join(outputDirectory, '.vercel', 'output', 'static');\n\n      try {\n        await copy(studioSource, staticDir, { overwrite: true });\n      } catch (err) {\n        throw new Error(\n          `Failed to copy studio assets from \"${studioSource}\" to \"${staticDir}\": ${err instanceof Error ? err.message : err}`,\n        );\n      }\n\n      this.injectStudioConfig(staticDir);\n    }\n  }\n\n  private getEntry(): string {\n    return `\nimport { handle } from 'hono/vercel'\nimport { mastra } from '#mastra';\nimport { createHonoServer, getToolExports } from '#server';\nimport { tools } from '#tools';\nimport { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\nif (mastra.getStorage()) {\n  mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n}\n\nconst app = await createHonoServer(mastra, { tools: getToolExports(tools) });\n\nexport const GET = handle(app);\nexport const POST = handle(app);\nexport const PUT = handle(app);\nexport const DELETE = handle(app);\nexport const PATCH = handle(app);\nexport const OPTIONS = handle(app);\nexport const HEAD = handle(app);\n`;\n  }\n\n  private injectStudioConfig(staticDir: string) {\n    const indexPath = join(staticDir, 'index.html');\n    let html = readFileSync(indexPath, 'utf-8');\n\n    /**\n     * Use window.location expressions so the SPA constructs the correct same-origin endpoint.\n     * Port uses a ternary: window.location.port is '' for default ports (80/443), and the SPA falls back to 4111 for empty strings, so we return the default port explicitly instead.\n     */\n    html = injectStudioHtmlConfig(html, {\n      host: `window.location.hostname`,\n      port: `(window.location.port || (window.location.protocol === 'https:' ? '443' : '80'))`,\n      protocol: `window.location.protocol.replace(':', '')`,\n      apiPrefix: `'/api'`,\n      basePath: '',\n      hideCloudCta: `'true'`,\n      templates: `'false'`,\n      cloudApiEndpoint: `''`,\n      experimentalFeatures: `'false'`,\n      telemetryDisabled: `''`,\n      requestContextPresets: `''`,\n      experimentalUI: `'false'`,\n      agentSignals: process.env.MASTRA_AGENT_SIGNALS === 'false' ? `'false'` : `'true'`,\n      signalsUI: process.env.MASTRA_SIGNALS_UI === 'true' ? `'true'` : `'false'`,\n      organizationId: `'${escapeStudioHtmlValue(process.env.MASTRA_ORGANIZATION_ID || '')}'`,\n      platformProjectId: `'${escapeStudioHtmlValue(process.env.MASTRA_PLATFORM_PROJECT_ID || '')}'`,\n      platformObservabilityEndpoint: `'${escapeStudioHtmlValue(process.env.MASTRA_PLATFORM_OBSERVABILITY_ENDPOINT || '')}'`,\n    });\n\n    writeFileSync(indexPath, html);\n  }\n\n  private writeVercelJSON(outputDirectory: string) {\n    writeFileSync(\n      join(outputDirectory, 'config.json'),\n      JSON.stringify({ version: 3, routes: getVercelRoutes({ studio: this.studio }) }),\n    );\n  }\n\n  async bundle(\n    entryFile: string,\n    outputDirectory: string,\n    { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n  ): Promise<void> {\n    const result = await this._bundle(\n      this.getEntry(),\n      entryFile,\n      { outputDirectory, projectRoot },\n      toolsPaths,\n      join(outputDirectory, this.outputDir),\n    );\n\n    const nodeVersion = process.version?.split('.')?.[0]?.replace('v', '') ?? '22';\n\n    const vcConfig: VcConfig = {\n      handler: 'index.mjs',\n      launcherType: 'Nodejs',\n      runtime: `nodejs${nodeVersion}.x`,\n      shouldAddHelpers: true,\n    };\n\n    // Merge supported overrides\n    const { maxDuration, memory, regions } = this.vcConfigOverrides;\n    if (typeof maxDuration === 'number') vcConfig.maxDuration = maxDuration;\n    if (typeof memory === 'number') vcConfig.memory = memory;\n    if (Array.isArray(regions) && regions.length > 0) vcConfig.regions = regions;\n\n    writeFileSync(join(outputDirectory, this.outputDir, '.vc-config.json'), JSON.stringify(vcConfig, null, 2));\n\n    await move(join(outputDirectory, '.vercel', 'output'), join(process.cwd(), '.vercel', 'output'), {\n      overwrite: true,\n    });\n\n    return result;\n  }\n\n  async deploy(): Promise<void> {\n    this.logger?.info('Deploying to Vercel is deprecated. Please use the Vercel dashboard to deploy.');\n  }\n\n  async lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void> {\n    await super.lint(entryFile, outputDirectory, toolsPaths);\n\n    const hasLibsql = (await this.deps.checkDependencies(['@mastra/libsql'])) === `ok`;\n\n    if (hasLibsql) {\n      this.logger.error(\n        `Vercel Deployer does not support @libsql/client(which may have been installed by @mastra/libsql) as a dependency. \n\t\t\t\tUse other Mastra Storage options instead e.g @mastra/pg`,\n      );\n      process.exit(1);\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAgB,gBAAgB,EAAE,UAA+B;CAC/D,OAAO,SACH;EACE;GAAE,KAAK;GAAO,MAAM;EAAc;EAClC;GAAE,KAAK;GAAa,MAAM;EAAI;EAC9B;GAAE,KAAK;GAAW,MAAM;EAAI;EAC5B,EAAE,QAAQ,aAAsB;EAChC;GAAE,KAAK;GAAS,MAAM;GAAe,OAAO;EAAK;CACnD,IACA,CAAC;EAAE,KAAK;EAAS,MAAM;CAAI,CAAC;AAClC;;;ACHA,IAAa,iBAAb,cAAoCA,iBAAAA,SAAS;CAC3C,oBAA+C,CAAC;CAChD;CAEA,YAAY,UAAiC,CAAC,GAAG;EAC/C,MAAM,EAAE,MAAM,SAAS,CAAC;EACxB,KAAK,aAAA,GAAA,KAAA,KAAA,CAAiB,WAAW,UAAU,aAAa,YAAY;EACpE,KAAK,SAAS,QAAQ,UAAU;EAEhC,MAAM,EAAE,QAAQ,GAAG,cAAc;EACjC,KAAK,oBAAoB,EAAE,GAAG,UAAU;CAC1C;CAEA,MAAgB,sBACd,iBACA,iBACyC;EAUzC,OAAO;GACL,GAAG,MAVwB,MAAM,sBAAsB,iBAAiB,eAAe;GAWvF,WAAW;EACb;CACF;CAEA,MAAM,QAAQ,iBAAwC;EACpD,MAAM,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