@mastra/deployer-cloudflare 0.14.2-alpha.2 → 0.14.3-alpha.0
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.
- package/CHANGELOG.md +22 -0
- package/dist/index.cjs +5 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -7
- package/dist/index.js.map +1 -1
- package/dist/plugins/postgres-store-instance-checker.d.ts.map +1 -1
- package/package.json +6 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @mastra/deployer-cloudflare
|
|
2
2
|
|
|
3
|
+
## 0.14.3-alpha.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fix cloudflare deployer build entry ([#8163](https://github.com/mastra-ai/mastra/pull/8163))
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`dc099b4`](https://github.com/mastra-ai/mastra/commit/dc099b40fb31147ba3f362f98d991892033c4c67), [`b342a68`](https://github.com/mastra-ai/mastra/commit/b342a68e1399cf1ece9ba11bda112db89d21118c), [`303a9c0`](https://github.com/mastra-ai/mastra/commit/303a9c0d7dd58795915979f06a0512359e4532fb), [`370f8a6`](https://github.com/mastra-ai/mastra/commit/370f8a6480faec70fef18d72e5f7538f27004301), [`623ffaf`](https://github.com/mastra-ai/mastra/commit/623ffaf2d969e11e99a0224633cf7b5a0815c857), [`9fc1613`](https://github.com/mastra-ai/mastra/commit/9fc16136400186648880fd990119ac15f7c02ee4), [`61f62aa`](https://github.com/mastra-ai/mastra/commit/61f62aa31bc88fe4ddf8da6240dbcfbeb07358bd), [`3e292ba`](https://github.com/mastra-ai/mastra/commit/3e292ba00837886d5d68a34cbc0d9b703c991883), [`418c136`](https://github.com/mastra-ai/mastra/commit/418c1366843d88e491bca3f87763899ce855ca29), [`c84b7d0`](https://github.com/mastra-ai/mastra/commit/c84b7d093c4657772140cbfd2b15ef72f3315ed5)]:
|
|
10
|
+
- @mastra/core@0.18.1-alpha.0
|
|
11
|
+
- @mastra/deployer@0.18.1-alpha.0
|
|
12
|
+
|
|
13
|
+
## 0.14.2
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- feat: implement trace scoring with batch processing capabilities ([#8033](https://github.com/mastra-ai/mastra/pull/8033))
|
|
18
|
+
|
|
19
|
+
- Update Peerdeps for packages based on core minor bump ([#8025](https://github.com/mastra-ai/mastra/pull/8025))
|
|
20
|
+
|
|
21
|
+
- Updated dependencies [[`288745a`](https://github.com/mastra-ai/mastra/commit/288745a19aa9557db3ab3c877d667ff59f14d79c), [`cf34503`](https://github.com/mastra-ai/mastra/commit/cf345031de4e157f29087946449e60b965e9c8a9), [`6b4b1e4`](https://github.com/mastra-ai/mastra/commit/6b4b1e4235428d39e51cbda9832704c0ba70ab32), [`3469fca`](https://github.com/mastra-ai/mastra/commit/3469fca7bb7e5e19369ff9f7044716a5e4b02585), [`a61f23f`](https://github.com/mastra-ai/mastra/commit/a61f23fbbca4b88b763d94f1d784c47895ed72d7), [`4b339b8`](https://github.com/mastra-ai/mastra/commit/4b339b8141c20d6a6d80583c7e8c5c05d8c19492), [`8f56160`](https://github.com/mastra-ai/mastra/commit/8f56160fd45c740076529148b9c225f6842d43b0), [`d1dc606`](https://github.com/mastra-ai/mastra/commit/d1dc6067b0557a71190b68d56ee15b48c26d2411), [`2d29ad9`](https://github.com/mastra-ai/mastra/commit/2d29ad92763cac02fc1d80c221ac93c39c0c5caf), [`c45298a`](https://github.com/mastra-ai/mastra/commit/c45298a0a0791db35cf79f1199d77004da0704cb), [`c4a8204`](https://github.com/mastra-ai/mastra/commit/c4a82046bfd241d6044e234bc5917d5a01fe6b55), [`d3bd4d4`](https://github.com/mastra-ai/mastra/commit/d3bd4d482a685bbb67bfa89be91c90dca3fa71ad), [`c591dfc`](https://github.com/mastra-ai/mastra/commit/c591dfc1e600fae1dedffe239357d250e146378f), [`1920c5c`](https://github.com/mastra-ai/mastra/commit/1920c5c6d666f687785c73021196aa551e579e0d), [`b6a3b65`](https://github.com/mastra-ai/mastra/commit/b6a3b65d830fa0ca7754ad6481661d1f2c878f21), [`af3abb6`](https://github.com/mastra-ai/mastra/commit/af3abb6f7c7585d856e22d27f4e7d2ece2186b9a), [`5b1ee71`](https://github.com/mastra-ai/mastra/commit/5b1ee71dc3ac92383226dc1e375642ca5f9b4224), [`282379f`](https://github.com/mastra-ai/mastra/commit/282379fafed80c6417fe1e791087110decd481ca)]:
|
|
22
|
+
- @mastra/deployer@0.18.0
|
|
23
|
+
- @mastra/core@0.18.0
|
|
24
|
+
|
|
3
25
|
## 0.14.2-alpha.2
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -117,14 +117,12 @@ function postgresStoreInstanceChecker2() {
|
|
|
117
117
|
configFile: false,
|
|
118
118
|
plugins: [postgresStoreInstanceChecker]
|
|
119
119
|
});
|
|
120
|
-
if (!result
|
|
121
|
-
|
|
122
|
-
"postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin."
|
|
123
|
-
);
|
|
120
|
+
if (!result || typeof result.code !== "string") {
|
|
121
|
+
return null;
|
|
124
122
|
}
|
|
125
123
|
return {
|
|
126
124
|
code: result.code,
|
|
127
|
-
map: result
|
|
125
|
+
map: result.map ?? null
|
|
128
126
|
};
|
|
129
127
|
}
|
|
130
128
|
};
|
|
@@ -199,8 +197,8 @@ var CloudflareDeployer = class extends deployer.Deployer {
|
|
|
199
197
|
fetch: async (request, env, context) => {
|
|
200
198
|
const _mastra = mastra();
|
|
201
199
|
|
|
202
|
-
if (
|
|
203
|
-
|
|
200
|
+
if (_mastra.getStorage()) {
|
|
201
|
+
_mastra.__registerInternalWorkflow(scoreTracesWorkflow);
|
|
204
202
|
}
|
|
205
203
|
|
|
206
204
|
registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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","Deployer","writeFile","join","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,MAA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W,eAAA,EAAiB,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,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 (!result?.code) {\n throw new Error(\n 'postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin.',\n );\n }\n\n return {\n code: result.code,\n map: result?.map,\n };\n },\n };\n}\n","import { writeFile } from 'fs/promises';\nimport { join } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\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 vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { scoreTracesWorkflow } from '@mastra/core/scores/scoreTraces';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n export default {\n fetch: async (request, env, context) => {\n const _mastra = mastra();\n\n if (mastra.getStorage()) {\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = _mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = _mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\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 async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap = false }: { enableSourcemap?: boolean } = {},\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n enableSourcemap,\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 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 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"]}
|
|
1
|
+
{"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","Deployer","writeFile","join","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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K,MAAA,EAAQ,KAAK,gFAAgF,CAAA;AAAA,EACpG;AAAA,EAEA,MAAM,SAAA,GAA2B;AAC/B,IAAA,MAAM,IAAI,MAAM,wFAAwF,CAAA;AAAA,EAC1G;AAAA,EAEA,MAAM,IAAA,CAAK,SAAA,EAAmB,eAAA,EAAyB,UAAA,EAAkD;AACvG,IAAA,MAAM,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,eAAA,EAAiB,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,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 'fs/promises';\nimport { join } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\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 vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { scoreTracesWorkflow } from '@mastra/core/scores/scoreTraces';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n export default {\n fetch: async (request, env, context) => {\n const _mastra = mastra();\n\n if (_mastra.getStorage()) {\n _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = _mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = _mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\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 async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap = false }: { enableSourcemap?: boolean } = {},\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n enableSourcemap,\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 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 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"]}
|
package/dist/index.js
CHANGED
|
@@ -93,14 +93,12 @@ function postgresStoreInstanceChecker2() {
|
|
|
93
93
|
configFile: false,
|
|
94
94
|
plugins: [postgresStoreInstanceChecker]
|
|
95
95
|
});
|
|
96
|
-
if (!result
|
|
97
|
-
|
|
98
|
-
"postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin."
|
|
99
|
-
);
|
|
96
|
+
if (!result || typeof result.code !== "string") {
|
|
97
|
+
return null;
|
|
100
98
|
}
|
|
101
99
|
return {
|
|
102
100
|
code: result.code,
|
|
103
|
-
map: result
|
|
101
|
+
map: result.map ?? null
|
|
104
102
|
};
|
|
105
103
|
}
|
|
106
104
|
};
|
|
@@ -175,8 +173,8 @@ var CloudflareDeployer = class extends Deployer {
|
|
|
175
173
|
fetch: async (request, env, context) => {
|
|
176
174
|
const _mastra = mastra();
|
|
177
175
|
|
|
178
|
-
if (
|
|
179
|
-
|
|
176
|
+
if (_mastra.getStorage()) {
|
|
177
|
+
_mastra.__registerInternalWorkflow(scoreTracesWorkflow);
|
|
180
178
|
}
|
|
181
179
|
|
|
182
180
|
registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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":["mastraInstanceWrapper","babel2","postgresStoreInstanceChecker","transformSync"],"mappings":";;;;;;;;AAwBO,SAAS,qBAAA,GAAmC;AACjD,EAAA,MAAM,UAAA,GAAa,QAAA;AACnB,EAAA,MAAM,SAAA,GAAY,QAAA;AAClB,EAAA,MAAM,CAAA,GAAU,KAAA,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,SAASA,uBAAsB,eAAA,EAAiC;AACrE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,CAAU,MAAM,EAAA,EAAI;AAClB,MAAA,IA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AAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.js","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 (!result?.code) {\n throw new Error(\n 'postgres-store-instance-checker plugin did not return code, there is likely a bug in the plugin.',\n );\n }\n\n return {\n code: result.code,\n map: result?.map,\n };\n },\n };\n}\n","import { writeFile } from 'fs/promises';\nimport { join } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\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 vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { scoreTracesWorkflow } from '@mastra/core/scores/scoreTraces';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n export default {\n fetch: async (request, env, context) => {\n const _mastra = mastra();\n\n if (mastra.getStorage()) {\n mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = _mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = _mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\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 async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap = false }: { enableSourcemap?: boolean } = {},\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n enableSourcemap,\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 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 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"]}
|
|
1
|
+
{"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":["mastraInstanceWrapper","babel2","postgresStoreInstanceChecker","transformSync"],"mappings":";;;;;;;;AAwBO,SAAS,qBAAA,GAAmC;AACjD,EAAA,MAAM,UAAA,GAAa,QAAA;AACnB,EAAA,MAAM,SAAA,GAAY,QAAA;AAClB,EAAA,MAAM,CAAA,GAAU,KAAA,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,Q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,IAAA,MAAM,IAAI,MAAM,wFAAwF,CAAA;AAAA,EAC1G;AAAA,EAEA,MAAM,IAAA,CAAK,SAAA,EAAmB,eAAA,EAAyB,UAAA,EAAkD;AACvG,IAAA,MAAM,KAAA,CAAM,IAAA,CAAK,SAAA,EAAW,eAAA,EAAiB,UAAU,CAAA;AAEvD,IAAA,MAAM,SAAA,GAAa,MAAM,IAAA,CAAK,IAAA,CAAK,kBAAkB,CAAC,gBAAgB,CAAC,CAAA,KAAO,CAAA,EAAA,CAAA;AAE9E,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,IAAA,CAAK,MAAA,CAAO,KAAA;AAAA,QACV;AAAA,OACF;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACF","file":"index.js","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 'fs/promises';\nimport { join } from 'path';\nimport { Deployer } from '@mastra/deployer';\nimport type { analyzeBundle } from '@mastra/deployer/analyze';\nimport virtual from '@rollup/plugin-virtual';\nimport { mastraInstanceWrapper } from './plugins/mastra-instance-wrapper';\nimport { postgresStoreInstanceChecker } from './plugins/postgres-store-instance-checker';\n\ninterface CFRoute {\n pattern: string;\n zone_name: string;\n custom_domain?: boolean;\n}\n\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n routes?: CFRoute[] = [];\n workerNamespace?: string;\n env?: Record<string, any>;\n projectName?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n\n constructor({\n env,\n projectName = 'mastra',\n routes,\n workerNamespace,\n d1Databases,\n kvNamespaces,\n }: {\n env?: Record<string, any>;\n projectName?: string;\n routes?: CFRoute[];\n workerNamespace?: string;\n d1Databases?: D1DatabaseBinding[];\n kvNamespaces?: KVNamespaceBinding[];\n }) {\n super({ name: 'CLOUDFLARE' });\n\n this.projectName = projectName;\n this.routes = routes;\n this.workerNamespace = workerNamespace;\n\n if (env) {\n this.env = env;\n }\n\n if (d1Databases) this.d1Databases = d1Databases;\n if (kvNamespaces) this.kvNamespaces = kvNamespaces;\n }\n\n async writeFiles(outputDirectory: string): Promise<void> {\n const env = await this.loadEnvVars();\n const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);\n\n const cfWorkerName = this.projectName;\n\n const wranglerConfig: Record<string, any> = {\n name: cfWorkerName,\n main: './index.mjs',\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 vars: envsAsObject,\n };\n\n if (!this.workerNamespace && this.routes) {\n wranglerConfig.routes = this.routes;\n }\n\n if (this.d1Databases?.length) {\n wranglerConfig.d1_databases = this.d1Databases;\n }\n if (this.kvNamespaces?.length) {\n wranglerConfig.kv_namespaces = this.kvNamespaces;\n }\n await writeFile(join(outputDirectory, this.outputDir, 'wrangler.json'), JSON.stringify(wranglerConfig));\n }\n\n private getEntry(): string {\n return `\n import '#polyfills';\n import { mastra } from '#mastra';\n import { createHonoServer, getToolExports } from '#server';\n import { tools } from '#tools';\n import { evaluate } from '@mastra/core/eval';\n import { AvailableHooks, registerHook } from '@mastra/core/hooks';\n import { TABLE_EVALS } from '@mastra/core/storage';\n import { scoreTracesWorkflow } from '@mastra/core/scores/scoreTraces';\n import { checkEvalStorageFields } from '@mastra/core/utils';\n\n export default {\n fetch: async (request, env, context) => {\n const _mastra = mastra();\n\n if (_mastra.getStorage()) {\n _mastra.__registerInternalWorkflow(scoreTracesWorkflow);\n }\n\n registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {\n evaluate({\n agentName,\n input,\n metric,\n output,\n runId,\n globalRunId: runId,\n instructions,\n });\n });\n\n registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {\n const storage = _mastra.getStorage();\n if (storage) {\n // Check for required fields\n const logger = _mastra?.getLogger();\n const areFieldsValid = checkEvalStorageFields(traceObject, logger);\n if (!areFieldsValid) return;\n\n await storage.insert({\n tableName: TABLE_EVALS,\n record: {\n input: traceObject.input,\n output: traceObject.output,\n result: JSON.stringify(traceObject.result || {}),\n agent_name: traceObject.agentName,\n metric_name: traceObject.metricName,\n instructions: traceObject.instructions,\n test_info: null,\n global_run_id: traceObject.globalRunId,\n run_id: traceObject.runId,\n created_at: new Date().toISOString(),\n },\n });\n }\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 async getBundlerOptions(\n serverFile: string,\n mastraEntryFile: string,\n analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>,\n toolsPaths: (string | string[])[],\n { enableSourcemap = false }: { enableSourcemap?: boolean } = {},\n ) {\n const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {\n enableSourcemap,\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 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 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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-store-instance-checker.d.ts","sourceRoot":"","sources":["../../src/plugins/postgres-store-instance-checker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC,wBAAgB,4BAA4B,IAAI,MAAM,
|
|
1
|
+
{"version":3,"file":"postgres-store-instance-checker.d.ts","sourceRoot":"","sources":["../../src/plugins/postgres-store-instance-checker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC,wBAAgB,4BAA4B,IAAI,MAAM,CAsBrD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/deployer-cloudflare",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.3-alpha.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -40,7 +40,8 @@
|
|
|
40
40
|
"@rollup/plugin-virtual": "^3.0.2",
|
|
41
41
|
"cloudflare": "^4.5.0",
|
|
42
42
|
"rollup": "~4.50.2",
|
|
43
|
-
"
|
|
43
|
+
"rollup-plugin-esbuild": "^6.2.1",
|
|
44
|
+
"@mastra/deployer": "^0.18.1-alpha.0"
|
|
44
45
|
},
|
|
45
46
|
"devDependencies": {
|
|
46
47
|
"@babel/types": "^7.28.4",
|
|
@@ -52,9 +53,9 @@
|
|
|
52
53
|
"typescript": "^5.8.3",
|
|
53
54
|
"vitest": "^3.2.4",
|
|
54
55
|
"zod": "^3.25.76",
|
|
55
|
-
"@internal/
|
|
56
|
-
"@internal/
|
|
57
|
-
"@mastra/core": "0.18.
|
|
56
|
+
"@internal/lint": "0.0.42",
|
|
57
|
+
"@internal/types-builder": "0.0.17",
|
|
58
|
+
"@mastra/core": "0.18.1-alpha.0"
|
|
58
59
|
},
|
|
59
60
|
"homepage": "https://mastra.ai",
|
|
60
61
|
"repository": {
|