{"version":3,"sources":["../src/babel/mastra-instance-wrapper.ts","../src/plugins/mastra-instance-wrapper.ts","../src/babel/postgres-store-instance-checker.ts","../src/plugins/postgres-store-instance-checker.ts","../src/index.ts"],"names":["babel","mastraInstanceWrapper","transformSync","babel2","postgresStoreInstanceChecker","builtinModules","Deployer","writeFile","join","relative","virtual"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,qBAAA,GAAmC;AACjD,EAAA,MAAM,UAAA,GAAa,QAAA;AACnB,EAAA,MAAM,SAAA,GAAY,QAAA;AAClB,EAAA,MAAM,CAAA,GAAUA,gBAAA,CAAA,KAAA;AAEhB,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,OAAA,EAAS;AAAA,MACP,uBAAuB,IAAA,EAAM;AAC3B,QAAA,IAAI,CAAA,CAAE,qBAAA,CAAsB,IAAA,CAAK,IAAA,EAAM,WAAW,CAAA,EAAG;AACnD,UAAA,KAAA,MAAW,WAAA,IAAe,IAAA,CAAK,IAAA,CAAK,WAAA,CAAY,YAAA,EAAc;AAC5D,YAAA,IACE,CAAA,CAAE,aAAa,WAAA,EAAa,EAAA,EAAI,EAAE,IAAA,EAAM,UAAA,EAAY,CAAA,IACpD,CAAA,CAAE,eAAA,CAAgB,aAAa,IAAI,CAAA,IACnC,CAAA,CAAE,YAAA,CAAa,WAAA,CAAY,IAAA,CAAK,QAAQ,EAAE,IAAA,EAAM,SAAA,EAAW,CAAA,EAC3D;AACA,cAAA,WAAA,CAAY,OAAO,CAAA,CAAE,uBAAA,CAAwB,EAAC,EAAG,YAAY,IAAI,CAAA;AAEjE,cAAA;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA;AACF,GACF;AACF;;;AC7CO,SAASC,uBAAsB,eAAA,EAAiC;AACrE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,CAAU,MAAM,EAAA,EAAI;AAClB,MAAA,I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AA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["import type { PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\n\n/**\n * Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.\n *\n * This plugin:\n * 1. Identifies named exports of the 'mastra' variable\n * 2. Checks if the export is a new instance of the 'Mastra' class\n * 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization\n *    in the Cloudflare Workers environment\n *\n * The transformation ensures the Mastra instance is properly scoped and initialized\n * for each request in the Cloudflare Workers environment.\n *\n * @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation\n *\n * @example\n * // Before transformation:\n * export const mastra = new Mastra();\n *\n * // After transformation:\n * export const mastra = () => new Mastra();\n */\nexport function mastraInstanceWrapper(): PluginObj {\n  const exportName = 'mastra';\n  const className = 'Mastra';\n  const t = babel.types;\n\n  return {\n    name: 'wrap-mastra',\n    visitor: {\n      ExportNamedDeclaration(path) {\n        if (t.isVariableDeclaration(path.node?.declaration)) {\n          for (const declaration of path.node.declaration.declarations) {\n            if (\n              t.isIdentifier(declaration?.id, { name: exportName }) &&\n              t.isNewExpression(declaration?.init) &&\n              t.isIdentifier(declaration.init.callee, { name: className })\n            ) {\n              declaration.init = t.arrowFunctionExpression([], declaration.init);\n              // there should be only one \"mastra\" export, so we can exit the loop\n              break;\n            }\n          }\n        }\n      },\n    },\n  } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { mastraInstanceWrapper as mastraInstanceWrapperBabel } from '../babel/mastra-instance-wrapper';\n\nexport function mastraInstanceWrapper(mastraEntryFile: string): Plugin {\n  return {\n    name: 'mastra-wrapper',\n    transform(code, id) {\n      if (id !== mastraEntryFile) {\n        return null;\n      }\n\n      const result = transformSync(code, {\n        filename: id,\n        babelrc: false,\n        configFile: false,\n        plugins: [mastraInstanceWrapperBabel],\n      });\n\n      if (!result?.code) {\n        throw new Error('mastra-wrapper plugin did not return code, there is likely a bug in the plugin.');\n      }\n\n      return {\n        code: result.code,\n        map: result?.map,\n      };\n    },\n  };\n}\n","import type { NodePath, PluginObj } from '@babel/core';\nimport * as babel from '@babel/core';\nimport type { NewExpression } from '@babel/types';\n\n/**\n * Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.\n *\n * This plugin:\n * 1. Scans for all `new PostgresStore()` instantiations\n * 2. Records their file locations\n * 3. Throws an error if multiple instances are found\n *\n * Cloudflare Workers should only create one PostgresStore instance to avoid connection\n * pool exhaustion and ensure proper resource management.\n *\n * @returns {PluginObj} A Babel plugin object that validates PostgresStore usage\n *\n * @example\n * // Throws error if multiple instances found:\n * const store1 = new PostgresStore();\n * const store2 = new PostgresStore(); // Error thrown here\n */\nexport function postgresStoreInstanceChecker(): PluginObj {\n  const t = babel.types;\n  const instances: { path: NodePath<NewExpression>; location: string }[] = [];\n\n  return {\n    name: 'postgresstore-instance-checker',\n    visitor: {\n      NewExpression(path, state) {\n        if (t.isIdentifier(path.node.callee) && path.node.callee.name === 'PostgresStore') {\n          const filename = state.file?.opts?.filename || 'unknown file';\n          const location = path.node.loc\n            ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}`\n            : 'unknown location';\n\n          instances.push({\n            path,\n            location,\n          });\n        }\n      },\n    },\n    post() {\n      if (instances.length > 1) {\n        const errorMessage = [\n          `Found ${instances.length} PostgresStore instantiations:`,\n          ...instances.map((instance, i) => `  ${i + 1}. At ${instance.location}`),\n          'Only one PostgresStore instance should be created per Cloudflare Worker.',\n        ].join('\\n');\n\n        const lastInstance = instances[instances.length - 1];\n        throw lastInstance?.path.buildCodeFrameError(errorMessage);\n      }\n    },\n  } as PluginObj;\n}\n","import { transformSync } from '@babel/core';\nimport type { Plugin } from 'rollup';\nimport { postgresStoreInstanceChecker as postgresStoreInstanceCheckerBabel } from '../babel/postgres-store-instance-checker';\n\nexport function postgresStoreInstanceChecker(): Plugin {\n  return {\n    name: 'postgres-store-instance-checker',\n    transform(code, id) {\n      const result = transformSync(code, {\n        filename: id,\n        babelrc: false,\n        configFile: false,\n        plugins: [postgresStoreInstanceCheckerBabel],\n      });\n\n      // If Babel didn't transform anything or returned no code, pass through original source.\n      if (!result || typeof result.code !== 'string') {\n        return null;\n      }\n\n      return {\n        code: result.code,\n        map: result.map ?? null,\n      };\n    },\n  };\n}\n","import { writeFile } from 'node:fs/promises';\nimport { builtinModules } from 'node:module';\nimport { join, relative } from 'node:path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport type { BundlerOptions } from '@mastra/deployer/bundler';\nimport virtual from '@rollup/plugin-virtual';\nimport type { Plugin } from 'rollup';\nimport type { Unstable_RawConfig } from 'wrangler'; // Unstable_RawConfig is unstable, and no stable alternative exists. However, `wrangler` is a peerDep, allowing users to use latest properties.\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\nconst nodeBuiltins = new Set(builtinModules);\n\n/**\n * Rollup plugin that marks bare Node.js builtin imports (e.g. `process`, `path`)\n * as external. Cloudflare Workers with `nodejs_compat` provides these at runtime,\n * so they must not be resolved to npm polyfill packages during bundling.\n */\nfunction nodeBuiltinsExternal(): Plugin {\n  return {\n    name: 'node-builtins-external',\n    resolveId(id) {\n      if (nodeBuiltins.has(id)) {\n        return { id, external: true };\n      }\n      return null;\n    },\n  };\n}\n\n/** @deprecated */\ninterface D1DatabaseBinding {\n  binding: string;\n  database_name: string;\n  database_id: string;\n  preview_database_id?: string;\n}\n\n/** @deprecated */\ninterface KVNamespaceBinding {\n  binding: string;\n  id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n  readonly userConfig: Omit<Unstable_RawConfig, 'main' | '$schema'>;\n\n  constructor(\n    userConfig: Omit<Unstable_RawConfig, 'main' | '$schema'> &\n      // TODO: Remove deprecated fields in next major version, and update type to just Omit<Unstable_RawConfig, 'main' | '$schema'>.\n      {\n        /** @deprecated Use `name` instead. */\n        projectName?: string;\n        /** @deprecated This parameter is not used internally. */\n        workerNamespace?: string;\n        /** @deprecated Use `d1_databases` instead. */\n        d1Databases?: D1DatabaseBinding[];\n        /** @deprecated Use `kv_namespaces` instead. */\n        kvNamespaces?: KVNamespaceBinding[];\n      },\n  ) {\n    super({ name: 'CLOUDFLARE' });\n\n    // Use 'browser' platform for Workers-compatible module resolution.\n    // This ensures packages with conditional exports (like the Cloudflare SDK)\n    // resolve to browser/worker implementations instead of Node.js-specific code\n    // that depends on unavailable modules like 'https'.\n    this.platform = 'browser';\n\n    this.userConfig = { ...userConfig };\n\n    if (userConfig.workerNamespace) {\n      console.warn('[CloudflareDeployer]: `workerNamespace` is no longer used');\n    }\n    if (!userConfig.name && userConfig.projectName) {\n      this.userConfig.name = userConfig.projectName;\n      console.warn('[CloudflareDeployer]: `projectName` is deprecated, use `name` instead');\n    }\n    if (!userConfig.d1_databases && userConfig.d1Databases) {\n      this.userConfig.d1_databases = userConfig.d1Databases;\n      console.warn('[CloudflareDeployer]: `d1Databases` is deprecated, use `d1_databases` instead');\n    }\n    if (!userConfig.kv_namespaces && userConfig.kvNamespaces) {\n      this.userConfig.kv_namespaces = userConfig.kvNamespaces;\n      console.warn('[CloudflareDeployer]: `kvNamespaces` is deprecated, use `kv_namespaces` instead');\n    }\n  }\n\n  async writeFiles(outputDirectory: string): Promise<void> {\n    const {\n      vars: userVars,\n      alias: userAlias,\n      // Remove deprecated fields so they don't leak into wrangler.json\n      projectName: _projectName,\n      workerNamespace: _workerNamespace,\n      d1Databases: _d1Databases,\n      kvNamespaces: _kvNamespaces,\n      ...userConfig\n    } = this.userConfig as typeof this.userConfig & {\n      projectName?: string;\n      workerNamespace?: string;\n      d1Databases?: unknown;\n      kvNamespaces?: unknown;\n    };\n    const loadedEnvVars = await this.loadEnvVars();\n    const envsAsObject = Object.assign({}, userVars);\n\n    if (loadedEnvVars.size > 0) {\n      const envKeys = [...loadedEnvVars.keys()].join(', ');\n      this.logger.warn(\n        `Environment variables from .env (${envKeys}) were not written to wrangler.jsonc.\nUpload them as Cloudflare Secrets instead:\nnpx wrangler secret bulk .env`,\n      );\n    }\n\n    // Write TypeScript stub to prevent bundling the full TypeScript library (~10MB)\n    // The agent-builder package dynamically imports TypeScript for code validation,\n    // but gracefully falls back to basic validation when TypeScript is unavailable.\n    // This stub ensures the import doesn't fail while keeping the bundle small.\n    const typescriptStubPath = 'typescript-stub.mjs';\n    const typescriptStub = `// Stub for TypeScript - not available at runtime in Cloudflare Workers\n// The @mastra/agent-builder package will fall back to basic validation\nexport default {};\nexport const createSourceFile = () => null;\nexport const createProgram = () => null;\nexport const findConfigFile = () => null;\nexport const readConfigFile = () => ({ error: new Error('TypeScript not available') });\nexport const parseJsonConfigFileContent = () => ({ errors: [new Error('TypeScript not available')], fileNames: [], options: {} });\nexport const flattenDiagnosticMessageText = (message) => typeof message === 'string' ? message : message?.messageText || '';\nexport const ScriptTarget = { Latest: 99 };\nexport const ModuleKind = { ESNext: 99 };\nexport const JsxEmit = { ReactJSX: 4 };\nexport const DiagnosticCategory = { Warning: 0, Error: 1, Suggestion: 2, Message: 3 };\nexport const sys = {\n  fileExists: () => false,\n  readFile: () => undefined,\n};\n`;\n\n    await writeFile(join(outputDirectory, this.outputDir, typescriptStubPath), typescriptStub);\n\n    // Write execa stub — execa is used by @mastra/core's local sandbox process manager\n    // but is not available/needed in Cloudflare Workers\n    const execaStubPath = 'execa-stub.mjs';\n    const execaStub = `// Stub for execa - not available at runtime in Cloudflare Workers\nexport const execa = () => { throw new Error('execa is not available in Cloudflare Workers'); };\nexport const execaNode = execa;\nexport const execaSync = execa;\nexport const execaCommand = execa;\nexport const execaCommandSync = execa;\nexport const $ = execa;\n`;\n    await writeFile(join(outputDirectory, this.outputDir, execaStubPath), execaStub);\n\n    // Write readable-stream stub — redirects to native node:stream available via nodejs_compat.\n    // readable-stream is a userland copy of Node.js streams used by packages like elevenlabs.\n    // Bundling it for Workers pulls in Node.js polyfills (abort-controller, process/, string_decoder/)\n    // that are unnecessary and fail to resolve. The native node:stream is API-compatible.\n    const readableStreamStubPath = 'readable-stream-stub.mjs';\n    const readableStreamStub = `// Redirect readable-stream to native node:stream (available via nodejs_compat)\nimport stream from 'node:stream';\nexport const { Readable, Writable, Duplex, Transform, PassThrough, Stream, pipeline, finished } = stream;\nexport default stream;\n`;\n    await writeFile(join(outputDirectory, this.outputDir, readableStreamStubPath), readableStreamStub);\n\n    const wranglerConfig: Unstable_RawConfig = {\n      name: 'mastra',\n      compatibility_date: '2025-04-01',\n      compatibility_flags: ['nodejs_compat', 'nodejs_compat_populate_process_env'],\n      observability: {\n        logs: {\n          enabled: true,\n        },\n      },\n      ...userConfig,\n      main: './index.mjs',\n      vars: envsAsObject,\n      // Alias stubs to prevent wrangler from bundling unavailable libraries\n      alias: {\n        typescript: `./${typescriptStubPath}`,\n        execa: `./${execaStubPath}`,\n        'readable-stream': `./${readableStreamStubPath}`,\n        ...userAlias,\n      },\n    };\n\n    // TODO: Remove writing this file in the next major version, it should only be written to the root of the project\n    await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig, null, 2));\n\n    const projectRoot = join(outputDirectory, '../');\n    const jsoncFilePath = join(projectRoot, 'wrangler.jsonc');\n    const mainFilePath = join(outputDirectory, this.outputDir, 'index.mjs');\n    const tsStubFilePath = join(outputDirectory, this.outputDir, typescriptStubPath);\n\n    const wranglerJsoncConfig: Unstable_RawConfig & { placeholder: string } = {\n      placeholder: 'PLACEHOLDER',\n      $schema: './node_modules/wrangler/config-schema.json',\n      ...wranglerConfig,\n      main: `./${relative(projectRoot, mainFilePath)}`,\n      alias: {\n        ...wranglerConfig.alias,\n        typescript: `./${relative(projectRoot, tsStubFilePath)}`,\n      },\n    };\n\n    const jsonc = JSON.stringify(wranglerJsoncConfig, null, 2).replace(\n      /\"placeholder\": \"PLACEHOLDER\",/,\n      '/* This file was auto-generated through Mastra. Edit the CloudflareDeployer() instance directly. */',\n    );\n    await writeFile(jsoncFilePath, jsonc);\n  }\n\n  private getEntry(): string {\n    return `\n    import '#polyfills';\n    import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';\n\n    export default {\n      fetch: async (request, env, context) => {\n        const { mastra } = await import('#mastra');\n        const { tools } = await import('#tools');\n        const {createHonoServer, getToolExports} = await import('#server');\n        const _mastra = mastra();\n\n        if (_mastra.getStorage()) {\n          _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n        }\n\n        const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });\n        return app.fetch(request, env, context);\n      }\n    }\n`;\n  }\n  async prepare(outputDirectory: string): Promise<void> {\n    await super.prepare(outputDirectory);\n    await this.writeFiles(outputDirectory);\n  }\n\n  protected async getBundlerOptions(\n    serverFile: string,\n    mastraEntryFile: string,\n    analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n    toolsPaths: (string | string[])[],\n    bundlerOptions: BundlerOptions,\n  ) {\n    const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n      ...bundlerOptions,\n      enableEsmShim: false,\n    });\n\n    const hasPostgresStore = (await this.deps.checkDependencies(['@mastra/pg'])) === `ok`;\n\n    if (Array.isArray(inputOptions.plugins)) {\n      inputOptions.plugins = [\n        nodeBuiltinsExternal(),\n        virtual({\n          '#polyfills': `\nprocess.versions = process.versions || {};\nprocess.versions.node = '${process.versions.node}';\n      `,\n        }),\n        ...inputOptions.plugins,\n        mastraInstanceWrapper(mastraEntryFile),\n      ];\n\n      if (hasPostgresStore) {\n        inputOptions.plugins.push(postgresStoreInstanceChecker());\n      }\n    }\n\n    return inputOptions;\n  }\n\n  async bundle(\n    entryFile: string,\n    outputDirectory: string,\n    { toolsPaths, projectRoot }: { toolsPaths: (string | string[])[]; projectRoot: string },\n  ): Promise<void> {\n    return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot, enableEsmShim: false }, toolsPaths);\n  }\n\n  async deploy(): Promise<void> {\n    this.logger?.info('Deploying to Cloudflare failed. Please use the Cloudflare dashboard to deploy.');\n  }\n\n  /**\n   * TODO: Remove this method in the next major version\n   *\n   * @deprecated\n   */\n  async tagWorker(): Promise<void> {\n    throw new Error('tagWorker method is no longer supported. Use the Cloudflare dashboard or API directly.');\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        'Cloudflare Deployer does not support @libsql/client (which may have been installed by @mastra/libsql) as a dependency. Please use Cloudflare D1 instead: @mastra/cloudflare-d1.',\n      );\n      process.exit(1);\n    }\n  }\n}\n"]}