{"version":3,"file":"index.cjs","names":["Deployer"],"sources":["../src/routes.ts","../src/index.ts"],"sourcesContent":["type VercelRoutesOptions = {\n  studio: boolean;\n  /** Studio's top-level route segments, read from the Studio build's routes-manifest.json. */\n  studioRouteRoots?: string[];\n};\n\nconst escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nexport function getVercelRoutes({ studio, studioRouteRoots = [] }: VercelRoutesOptions) {\n  if (!studio) {\n    return [{ src: '/(.*)', dest: '/' }];\n  }\n\n  // Studio owns a known set of SPA paths; everything else belongs to the server function.\n  // The function has to be the catch-all because custom `registerApiRoute()` paths are mounted\n  // at the root of the server (never under `apiPrefix`), so the CDN cannot tell them apart from\n  // an unknown path — an SPA catch-all would swallow every one of them.\n  const spaRoots = studioRouteRoots.map(escapeRegExp).join('|');\n\n  return [\n    { src: '^/$', dest: '/index.html' },\n    ...(spaRoots ? [{ src: `^/(?:${spaRoots})(?:/.*)?$`, dest: '/index.html' }] : []),\n    { handle: 'filesystem' as const },\n    { src: '/(.*)', dest: '/' },\n  ];\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    const __filename = fileURLToPath(import.meta.url);\n    const __dirname = dirname(__filename);\n\n    const studioSource = join(dirname(__dirname), 'dist', 'studio');\n\n    this.writeVercelJSON(\n      join(outputDirectory, this.outputDir, '..', '..'),\n      this.studio ? this.readStudioRouteRoots(studioSource) : [],\n    );\n\n    if (this.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  /**\n   * Studio's top-level route segments, emitted by the Studio build alongside index.html.\n   * The Vercel route table needs them explicitly: custom `registerApiRoute()` paths are mounted\n   * at the root of the server, so the function has to own every path Studio doesn't claim.\n   */\n  private readStudioRouteRoots(studioSource: string): string[] {\n    const manifestPath = join(studioSource, 'routes-manifest.json');\n\n    try {\n      const roots = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n      if (!Array.isArray(roots) || roots.some(root => typeof root !== 'string')) {\n        throw new Error('expected an array of route segments');\n      }\n      return roots;\n    } catch (err) {\n      throw new Error(\n        `Failed to read studio routes manifest at \"${manifestPath}\": ${err instanceof Error ? err.message : err}`,\n      );\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, studioRouteRoots: string[]) {\n    writeFileSync(\n      join(outputDirectory, 'config.json'),\n      JSON.stringify({ version: 3, routes: getVercelRoutes({ studio: this.studio, studioRouteRoots }) }),\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      );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