@mastra/deployer-cloudflare 0.0.0-trigger-playground-ui-package-20250506151043 → 0.0.0-type-testing-20260120105120
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 +4330 -0
- package/LICENSE.md +11 -42
- package/README.md +6 -44
- package/dist/babel/mastra-instance-wrapper.d.ts +24 -0
- package/dist/babel/mastra-instance-wrapper.d.ts.map +1 -0
- package/dist/babel/postgres-store-instance-checker.d.ts +21 -0
- package/dist/babel/postgres-store-instance-checker.d.ts.map +1 -0
- package/dist/index.cjs +173 -115
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +42 -1
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +156 -116
- package/dist/index.js.map +1 -0
- package/dist/plugins/__fixtures__/basic.d.ts +5 -0
- package/dist/plugins/__fixtures__/basic.d.ts.map +1 -0
- package/dist/plugins/__fixtures__/empty-mastra.d.ts +3 -0
- package/dist/plugins/__fixtures__/empty-mastra.d.ts.map +1 -0
- package/dist/plugins/__fixtures__/multiple-postgres-stores.d.ts +6 -0
- package/dist/plugins/__fixtures__/multiple-postgres-stores.d.ts.map +1 -0
- package/dist/plugins/mastra-instance-wrapper.d.ts +3 -0
- package/dist/plugins/mastra-instance-wrapper.d.ts.map +1 -0
- package/dist/plugins/postgres-store-instance-checker.d.ts +3 -0
- package/dist/plugins/postgres-store-instance-checker.d.ts.map +1 -0
- package/dist/secrets-manager/index.cjs +2 -0
- package/dist/secrets-manager/index.cjs.map +1 -0
- package/dist/secrets-manager/index.d.ts +25 -1
- package/dist/secrets-manager/index.d.ts.map +1 -0
- package/dist/secrets-manager/index.js +2 -0
- package/dist/secrets-manager/index.js.map +1 -0
- package/package.json +50 -22
- package/dist/_tsup-dts-rollup.d.cts +0 -69
- package/dist/_tsup-dts-rollup.d.ts +0 -69
- package/dist/index.d.cts +0 -1
- package/dist/secrets-manager/index.d.cts +0 -1
package/LICENSE.md
CHANGED
|
@@ -1,46 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Apache License 2.0
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2025
|
|
3
|
+
Copyright (c) 2025 Kepler Software, Inc.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
you may not use this file except in compliance with the License.
|
|
7
|
+
You may obtain a copy of the License at
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
|
|
9
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
|
|
17
|
-
|
|
18
|
-
**Patents**
|
|
19
|
-
The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
20
|
-
|
|
21
|
-
**Notices**
|
|
22
|
-
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
|
|
23
|
-
|
|
24
|
-
If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
|
|
25
|
-
|
|
26
|
-
**No Other Rights**
|
|
27
|
-
These terms do not imply any licenses other than those expressly granted in these terms.
|
|
28
|
-
|
|
29
|
-
**Termination**
|
|
30
|
-
If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
|
|
31
|
-
|
|
32
|
-
**No Liability**
|
|
33
|
-
As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
|
|
34
|
-
|
|
35
|
-
**Definitions**
|
|
36
|
-
The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
|
|
37
|
-
|
|
38
|
-
_you_ refers to the individual or entity agreeing to these terms.
|
|
39
|
-
|
|
40
|
-
_your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
41
|
-
|
|
42
|
-
_your licenses_ are all the licenses granted to you for the software under these terms.
|
|
43
|
-
|
|
44
|
-
_use_ means anything you do with the software requiring one of your licenses.
|
|
45
|
-
|
|
46
|
-
_trademark_ means trademarks, service marks, and similar rights.
|
|
11
|
+
Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
See the License for the specific language governing permissions and
|
|
15
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -5,8 +5,6 @@ A Cloudflare Workers deployer for Mastra applications.
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
7
|
- Deploy Mastra applications to Cloudflare Workers
|
|
8
|
-
- Configure custom domains and routes
|
|
9
|
-
- Support for worker namespaces
|
|
10
8
|
- Automatic environment variable configuration
|
|
11
9
|
|
|
12
10
|
## Installation
|
|
@@ -20,12 +18,11 @@ pnpm add @mastra/deployer-cloudflare
|
|
|
20
18
|
The Cloudflare deployer is used as part of the Mastra framework:
|
|
21
19
|
|
|
22
20
|
```typescript
|
|
23
|
-
import { Mastra } from '@mastra/core';
|
|
21
|
+
import { Mastra } from '@mastra/core/mastra';
|
|
24
22
|
import { CloudflareDeployer } from '@mastra/deployer-cloudflare';
|
|
25
23
|
|
|
26
24
|
const deployer = new CloudflareDeployer({
|
|
27
|
-
|
|
28
|
-
projectName: 'your-project-name',
|
|
25
|
+
name: 'your-project-name',
|
|
29
26
|
routes: [
|
|
30
27
|
{
|
|
31
28
|
pattern: 'example.com/*',
|
|
@@ -33,10 +30,8 @@ const deployer = new CloudflareDeployer({
|
|
|
33
30
|
custom_domain: true,
|
|
34
31
|
},
|
|
35
32
|
],
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
apiToken: 'your-api-token',
|
|
39
|
-
apiEmail: 'your-email',
|
|
33
|
+
assets: {
|
|
34
|
+
directory: './assets/',
|
|
40
35
|
},
|
|
41
36
|
});
|
|
42
37
|
|
|
@@ -48,18 +43,9 @@ const mastra = new Mastra({
|
|
|
48
43
|
|
|
49
44
|
## Configuration
|
|
50
45
|
|
|
51
|
-
|
|
46
|
+
The `CloudflareDeployer` constructor accepts the same configuration options as `wrangler.json`. See the [Wrangler configuration documentation](https://developers.cloudflare.com/workers/wrangler/configuration/) for all available options.
|
|
52
47
|
|
|
53
|
-
|
|
54
|
-
- `projectName`: Name of your worker project
|
|
55
|
-
- `routes`: Array of route configurations for your worker
|
|
56
|
-
- `pattern`: URL pattern to match
|
|
57
|
-
- `zone_name`: Domain zone name
|
|
58
|
-
- `custom_domain`: Whether to use a custom domain
|
|
59
|
-
- `workerNamespace`: Namespace for your worker
|
|
60
|
-
- `auth`: Cloudflare authentication details
|
|
61
|
-
- `apiToken`: Your Cloudflare API token
|
|
62
|
-
- `apiEmail`: Your Cloudflare account email
|
|
48
|
+
**Deprecated fields:** If migrating from an earlier version, note that `projectName`, `d1Databases`, `kvNamespaces`, and `workerNamespace` are deprecated. Use the standard `wrangler.json` property names instead (`name`, `d1_databases`, `kv_namespaces`).
|
|
63
49
|
|
|
64
50
|
## Environment Variables
|
|
65
51
|
|
|
@@ -68,30 +54,6 @@ The deployer will automatically load environment variables from:
|
|
|
68
54
|
- `.env` files in your project
|
|
69
55
|
- Environment variables passed through the Mastra configuration
|
|
70
56
|
|
|
71
|
-
## Routes
|
|
72
|
-
|
|
73
|
-
Routes can be configured to direct traffic to your worker based on URL patterns and domains:
|
|
74
|
-
|
|
75
|
-
```typescript
|
|
76
|
-
const routes = [
|
|
77
|
-
{
|
|
78
|
-
pattern: 'api.example.com/*',
|
|
79
|
-
zone_name: 'example.com',
|
|
80
|
-
custom_domain: true,
|
|
81
|
-
},
|
|
82
|
-
{
|
|
83
|
-
pattern: 'example.com/api/*',
|
|
84
|
-
zone_name: 'example.com',
|
|
85
|
-
},
|
|
86
|
-
];
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
Each route requires:
|
|
90
|
-
|
|
91
|
-
- `pattern`: URL pattern to match
|
|
92
|
-
- `zone_name`: Domain zone name
|
|
93
|
-
- `custom_domain`: (optional) Set to true to use a custom domain
|
|
94
|
-
|
|
95
57
|
## Requirements
|
|
96
58
|
|
|
97
59
|
- Cloudflare account with Workers enabled
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { PluginObj } from '@babel/core';
|
|
2
|
+
/**
|
|
3
|
+
* Babel plugin that transforms Mastra exports for Cloudflare Workers compatibility.
|
|
4
|
+
*
|
|
5
|
+
* This plugin:
|
|
6
|
+
* 1. Identifies named exports of the 'mastra' variable
|
|
7
|
+
* 2. Checks if the export is a new instance of the 'Mastra' class
|
|
8
|
+
* 3. Wraps the Mastra instantiation in an arrow function to ensure proper initialization
|
|
9
|
+
* in the Cloudflare Workers environment
|
|
10
|
+
*
|
|
11
|
+
* The transformation ensures the Mastra instance is properly scoped and initialized
|
|
12
|
+
* for each request in the Cloudflare Workers environment.
|
|
13
|
+
*
|
|
14
|
+
* @returns {PluginObj} A Babel plugin object with a visitor that performs the transformation
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* // Before transformation:
|
|
18
|
+
* export const mastra = new Mastra();
|
|
19
|
+
*
|
|
20
|
+
* // After transformation:
|
|
21
|
+
* export const mastra = () => new Mastra();
|
|
22
|
+
*/
|
|
23
|
+
export declare function mastraInstanceWrapper(): PluginObj;
|
|
24
|
+
//# sourceMappingURL=mastra-instance-wrapper.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mastra-instance-wrapper.d.ts","sourceRoot":"","sources":["../../src/babel/mastra-instance-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAG7C;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,qBAAqB,IAAI,SAAS,CAyBjD"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { PluginObj } from '@babel/core';
|
|
2
|
+
/**
|
|
3
|
+
* Babel plugin that enforces singleton PostgresStore instances in Cloudflare Workers.
|
|
4
|
+
*
|
|
5
|
+
* This plugin:
|
|
6
|
+
* 1. Scans for all `new PostgresStore()` instantiations
|
|
7
|
+
* 2. Records their file locations
|
|
8
|
+
* 3. Throws an error if multiple instances are found
|
|
9
|
+
*
|
|
10
|
+
* Cloudflare Workers should only create one PostgresStore instance to avoid connection
|
|
11
|
+
* pool exhaustion and ensure proper resource management.
|
|
12
|
+
*
|
|
13
|
+
* @returns {PluginObj} A Babel plugin object that validates PostgresStore usage
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* // Throws error if multiple instances found:
|
|
17
|
+
* const store1 = new PostgresStore();
|
|
18
|
+
* const store2 = new PostgresStore(); // Error thrown here
|
|
19
|
+
*/
|
|
20
|
+
export declare function postgresStoreInstanceChecker(): PluginObj;
|
|
21
|
+
//# sourceMappingURL=postgres-store-instance-checker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres-store-instance-checker.d.ts","sourceRoot":"","sources":["../../src/babel/postgres-store-instance-checker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAY,SAAS,EAAE,MAAM,aAAa,CAAC;AAIvD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,4BAA4B,IAAI,SAAS,CAkCxD"}
|
package/dist/index.cjs
CHANGED
|
@@ -4,45 +4,158 @@ var promises = require('fs/promises');
|
|
|
4
4
|
var path = require('path');
|
|
5
5
|
var deployer = require('@mastra/deployer');
|
|
6
6
|
var virtual = require('@rollup/plugin-virtual');
|
|
7
|
-
var
|
|
7
|
+
var babel = require('@babel/core');
|
|
8
8
|
|
|
9
9
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
10
10
|
|
|
11
|
+
function _interopNamespace(e) {
|
|
12
|
+
if (e && e.__esModule) return e;
|
|
13
|
+
var n = Object.create(null);
|
|
14
|
+
if (e) {
|
|
15
|
+
Object.keys(e).forEach(function (k) {
|
|
16
|
+
if (k !== 'default') {
|
|
17
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
18
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
19
|
+
enumerable: true,
|
|
20
|
+
get: function () { return e[k]; }
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
n.default = e;
|
|
26
|
+
return Object.freeze(n);
|
|
27
|
+
}
|
|
28
|
+
|
|
11
29
|
var virtual__default = /*#__PURE__*/_interopDefault(virtual);
|
|
30
|
+
var babel__namespace = /*#__PURE__*/_interopNamespace(babel);
|
|
31
|
+
|
|
32
|
+
// src/index.ts
|
|
33
|
+
function mastraInstanceWrapper() {
|
|
34
|
+
const exportName = "mastra";
|
|
35
|
+
const className = "Mastra";
|
|
36
|
+
const t = babel__namespace.types;
|
|
37
|
+
return {
|
|
38
|
+
name: "wrap-mastra",
|
|
39
|
+
visitor: {
|
|
40
|
+
ExportNamedDeclaration(path) {
|
|
41
|
+
if (t.isVariableDeclaration(path.node?.declaration)) {
|
|
42
|
+
for (const declaration of path.node.declaration.declarations) {
|
|
43
|
+
if (t.isIdentifier(declaration?.id, { name: exportName }) && t.isNewExpression(declaration?.init) && t.isIdentifier(declaration.init.callee, { name: className })) {
|
|
44
|
+
declaration.init = t.arrowFunctionExpression([], declaration.init);
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/plugins/mastra-instance-wrapper.ts
|
|
55
|
+
function mastraInstanceWrapper2(mastraEntryFile) {
|
|
56
|
+
return {
|
|
57
|
+
name: "mastra-wrapper",
|
|
58
|
+
transform(code, id) {
|
|
59
|
+
if (id !== mastraEntryFile) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
const result = babel.transformSync(code, {
|
|
63
|
+
filename: id,
|
|
64
|
+
babelrc: false,
|
|
65
|
+
configFile: false,
|
|
66
|
+
plugins: [mastraInstanceWrapper]
|
|
67
|
+
});
|
|
68
|
+
if (!result?.code) {
|
|
69
|
+
throw new Error("mastra-wrapper plugin did not return code, there is likely a bug in the plugin.");
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
code: result.code,
|
|
73
|
+
map: result?.map
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function postgresStoreInstanceChecker() {
|
|
79
|
+
const t = babel__namespace.types;
|
|
80
|
+
const instances = [];
|
|
81
|
+
return {
|
|
82
|
+
name: "postgresstore-instance-checker",
|
|
83
|
+
visitor: {
|
|
84
|
+
NewExpression(path, state) {
|
|
85
|
+
if (t.isIdentifier(path.node.callee) && path.node.callee.name === "PostgresStore") {
|
|
86
|
+
const filename = state.file?.opts?.filename || "unknown file";
|
|
87
|
+
const location = path.node.loc ? `${filename}: line ${path.node.loc.start.line}, column ${path.node.loc.start.column}` : "unknown location";
|
|
88
|
+
instances.push({
|
|
89
|
+
path,
|
|
90
|
+
location
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
post() {
|
|
96
|
+
if (instances.length > 1) {
|
|
97
|
+
const errorMessage = [
|
|
98
|
+
`Found ${instances.length} PostgresStore instantiations:`,
|
|
99
|
+
...instances.map((instance, i) => ` ${i + 1}. At ${instance.location}`),
|
|
100
|
+
"Only one PostgresStore instance should be created per Cloudflare Worker."
|
|
101
|
+
].join("\n");
|
|
102
|
+
const lastInstance = instances[instances.length - 1];
|
|
103
|
+
throw lastInstance?.path.buildCodeFrameError(errorMessage);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/plugins/postgres-store-instance-checker.ts
|
|
110
|
+
function postgresStoreInstanceChecker2() {
|
|
111
|
+
return {
|
|
112
|
+
name: "postgres-store-instance-checker",
|
|
113
|
+
transform(code, id) {
|
|
114
|
+
const result = babel.transformSync(code, {
|
|
115
|
+
filename: id,
|
|
116
|
+
babelrc: false,
|
|
117
|
+
configFile: false,
|
|
118
|
+
plugins: [postgresStoreInstanceChecker]
|
|
119
|
+
});
|
|
120
|
+
if (!result || typeof result.code !== "string") {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
code: result.code,
|
|
125
|
+
map: result.map ?? null
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
12
130
|
|
|
13
131
|
// src/index.ts
|
|
14
132
|
var CloudflareDeployer = class extends deployer.Deployer {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
workerNamespace;
|
|
18
|
-
scope;
|
|
19
|
-
env;
|
|
20
|
-
projectName;
|
|
21
|
-
constructor({
|
|
22
|
-
scope,
|
|
23
|
-
env,
|
|
24
|
-
projectName = "mastra",
|
|
25
|
-
routes,
|
|
26
|
-
workerNamespace,
|
|
27
|
-
auth
|
|
28
|
-
}) {
|
|
133
|
+
userConfig;
|
|
134
|
+
constructor(userConfig) {
|
|
29
135
|
super({ name: "CLOUDFLARE" });
|
|
30
|
-
this.
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
if (
|
|
35
|
-
this.
|
|
136
|
+
this.userConfig = { ...userConfig };
|
|
137
|
+
if (userConfig.workerNamespace) {
|
|
138
|
+
console.warn("[CloudflareDeployer]: `workerNamespace` is no longer used");
|
|
139
|
+
}
|
|
140
|
+
if (!userConfig.name && userConfig.projectName) {
|
|
141
|
+
this.userConfig.name = userConfig.projectName;
|
|
142
|
+
console.warn("[CloudflareDeployer]: `projectName` is deprecated, use `name` instead");
|
|
143
|
+
}
|
|
144
|
+
if (!userConfig.d1_databases && userConfig.d1Databases) {
|
|
145
|
+
this.userConfig.d1_databases = userConfig.d1Databases;
|
|
146
|
+
console.warn("[CloudflareDeployer]: `d1Databases` is deprecated, use `d1_databases` instead");
|
|
147
|
+
}
|
|
148
|
+
if (!userConfig.kv_namespaces && userConfig.kvNamespaces) {
|
|
149
|
+
this.userConfig.kv_namespaces = userConfig.kvNamespaces;
|
|
150
|
+
console.warn("[CloudflareDeployer]: `kvNamespaces` is deprecated, use `kv_namespaces` instead");
|
|
36
151
|
}
|
|
37
|
-
this.cloudflare = new cloudflare.Cloudflare(auth);
|
|
38
152
|
}
|
|
39
153
|
async writeFiles(outputDirectory) {
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
const
|
|
154
|
+
const { vars: userVars, ...userConfig } = this.userConfig;
|
|
155
|
+
const loadedEnvVars = await this.loadEnvVars();
|
|
156
|
+
const envsAsObject = Object.assign({}, Object.fromEntries(loadedEnvVars.entries()), userVars);
|
|
43
157
|
const wranglerConfig = {
|
|
44
|
-
name:
|
|
45
|
-
main: "./index.mjs",
|
|
158
|
+
name: "mastra",
|
|
46
159
|
compatibility_date: "2025-04-01",
|
|
47
160
|
compatibility_flags: ["nodejs_compat", "nodejs_compat_populate_process_env"],
|
|
48
161
|
observability: {
|
|
@@ -50,69 +163,29 @@ var CloudflareDeployer = class extends deployer.Deployer {
|
|
|
50
163
|
enabled: true
|
|
51
164
|
}
|
|
52
165
|
},
|
|
166
|
+
...userConfig,
|
|
167
|
+
main: "./index.mjs",
|
|
53
168
|
vars: envsAsObject
|
|
54
169
|
};
|
|
55
|
-
if (!this.workerNamespace && this.routes) {
|
|
56
|
-
wranglerConfig.routes = this.routes;
|
|
57
|
-
}
|
|
58
170
|
await promises.writeFile(path.join(outputDirectory, this.outputDir, "wrangler.json"), JSON.stringify(wranglerConfig));
|
|
59
171
|
}
|
|
60
172
|
getEntry() {
|
|
61
173
|
return `
|
|
62
174
|
import '#polyfills';
|
|
63
|
-
import {
|
|
64
|
-
import { createHonoServer } from '#server';
|
|
65
|
-
import { evaluate } from '@mastra/core/eval';
|
|
66
|
-
import { AvailableHooks, registerHook } from '@mastra/core/hooks';
|
|
67
|
-
import { TABLE_EVALS } from '@mastra/core/storage';
|
|
68
|
-
import { checkEvalStorageFields } from '@mastra/core/utils';
|
|
69
|
-
|
|
70
|
-
registerHook(AvailableHooks.ON_GENERATION, ({ input, output, metric, runId, agentName, instructions }) => {
|
|
71
|
-
evaluate({
|
|
72
|
-
agentName,
|
|
73
|
-
input,
|
|
74
|
-
metric,
|
|
75
|
-
output,
|
|
76
|
-
runId,
|
|
77
|
-
globalRunId: runId,
|
|
78
|
-
instructions,
|
|
79
|
-
});
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
if (mastra.getStorage()) {
|
|
83
|
-
// start storage init in the background
|
|
84
|
-
mastra.getStorage().init();
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
registerHook(AvailableHooks.ON_EVALUATION, async traceObject => {
|
|
88
|
-
const storage = mastra.getStorage();
|
|
89
|
-
if (storage) {
|
|
90
|
-
// Check for required fields
|
|
91
|
-
const logger = mastra?.getLogger();
|
|
92
|
-
const areFieldsValid = checkEvalStorageFields(traceObject, logger);
|
|
93
|
-
if (!areFieldsValid) return;
|
|
94
|
-
|
|
95
|
-
await storage.insert({
|
|
96
|
-
tableName: TABLE_EVALS,
|
|
97
|
-
record: {
|
|
98
|
-
input: traceObject.input,
|
|
99
|
-
output: traceObject.output,
|
|
100
|
-
result: JSON.stringify(traceObject.result || {}),
|
|
101
|
-
agent_name: traceObject.agentName,
|
|
102
|
-
metric_name: traceObject.metricName,
|
|
103
|
-
instructions: traceObject.instructions,
|
|
104
|
-
test_info: null,
|
|
105
|
-
global_run_id: traceObject.globalRunId,
|
|
106
|
-
run_id: traceObject.runId,
|
|
107
|
-
created_at: new Date().toISOString(),
|
|
108
|
-
},
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
});
|
|
175
|
+
import { scoreTracesWorkflow } from '@mastra/core/evals/scoreTraces';
|
|
112
176
|
|
|
113
177
|
export default {
|
|
114
178
|
fetch: async (request, env, context) => {
|
|
115
|
-
const
|
|
179
|
+
const { mastra } = await import('#mastra');
|
|
180
|
+
const { tools } = await import('#tools');
|
|
181
|
+
const {createHonoServer, getToolExports} = await import('#server');
|
|
182
|
+
const _mastra = mastra();
|
|
183
|
+
|
|
184
|
+
if (_mastra.getStorage()) {
|
|
185
|
+
_mastra.__registerInternalWorkflow(scoreTracesWorkflow);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const app = await createHonoServer(_mastra, { tools: getToolExports(tools) });
|
|
116
189
|
return app.fetch(request, env, context);
|
|
117
190
|
}
|
|
118
191
|
}
|
|
@@ -122,8 +195,12 @@ var CloudflareDeployer = class extends deployer.Deployer {
|
|
|
122
195
|
await super.prepare(outputDirectory);
|
|
123
196
|
await this.writeFiles(outputDirectory);
|
|
124
197
|
}
|
|
125
|
-
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths) {
|
|
126
|
-
const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths
|
|
198
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, bundlerOptions) {
|
|
199
|
+
const inputOptions = await super.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, {
|
|
200
|
+
...bundlerOptions,
|
|
201
|
+
enableEsmShim: false
|
|
202
|
+
});
|
|
203
|
+
const hasPostgresStore = await this.deps.checkDependencies(["@mastra/pg"]) === `ok`;
|
|
127
204
|
if (Array.isArray(inputOptions.plugins)) {
|
|
128
205
|
inputOptions.plugins = [
|
|
129
206
|
virtual__default.default({
|
|
@@ -132,51 +209,30 @@ process.versions = process.versions || {};
|
|
|
132
209
|
process.versions.node = '${process.versions.node}';
|
|
133
210
|
`
|
|
134
211
|
}),
|
|
135
|
-
...inputOptions.plugins
|
|
212
|
+
...inputOptions.plugins,
|
|
213
|
+
mastraInstanceWrapper2(mastraEntryFile)
|
|
136
214
|
];
|
|
215
|
+
if (hasPostgresStore) {
|
|
216
|
+
inputOptions.plugins.push(postgresStoreInstanceChecker2());
|
|
217
|
+
}
|
|
137
218
|
}
|
|
138
219
|
return inputOptions;
|
|
139
220
|
}
|
|
140
|
-
async bundle(entryFile, outputDirectory, toolsPaths) {
|
|
141
|
-
return this._bundle(this.getEntry(), entryFile, outputDirectory, toolsPaths);
|
|
221
|
+
async bundle(entryFile, outputDirectory, { toolsPaths, projectRoot }) {
|
|
222
|
+
return this._bundle(this.getEntry(), entryFile, { outputDirectory, projectRoot, enableEsmShim: false }, toolsPaths);
|
|
142
223
|
}
|
|
143
|
-
async deploy(
|
|
144
|
-
|
|
145
|
-
const cpLogger = deployer.createChildProcessLogger({
|
|
146
|
-
logger: this.logger,
|
|
147
|
-
root: path.join(outputDirectory, this.outputDir)
|
|
148
|
-
});
|
|
149
|
-
await cpLogger({
|
|
150
|
-
cmd,
|
|
151
|
-
args: [],
|
|
152
|
-
env: {
|
|
153
|
-
CLOUDFLARE_API_TOKEN: this.cloudflare.apiToken,
|
|
154
|
-
CLOUDFLARE_ACCOUNT_ID: this.scope,
|
|
155
|
-
...this.env,
|
|
156
|
-
PATH: process.env.PATH
|
|
157
|
-
}
|
|
158
|
-
});
|
|
224
|
+
async deploy() {
|
|
225
|
+
this.logger?.info("Deploying to Cloudflare failed. Please use the Cloudflare dashboard to deploy.");
|
|
159
226
|
}
|
|
160
|
-
async tagWorker({
|
|
161
|
-
|
|
162
|
-
namespace,
|
|
163
|
-
tags,
|
|
164
|
-
scope
|
|
165
|
-
}) {
|
|
166
|
-
if (!this.cloudflare) {
|
|
167
|
-
throw new Error("Cloudflare Deployer not initialized");
|
|
168
|
-
}
|
|
169
|
-
await this.cloudflare.workersForPlatforms.dispatch.namespaces.scripts.tags.update(namespace, workerName, {
|
|
170
|
-
account_id: scope,
|
|
171
|
-
body: tags
|
|
172
|
-
});
|
|
227
|
+
async tagWorker() {
|
|
228
|
+
throw new Error("tagWorker method is no longer supported. Use the Cloudflare dashboard or API directly.");
|
|
173
229
|
}
|
|
174
230
|
async lint(entryFile, outputDirectory, toolsPaths) {
|
|
175
231
|
await super.lint(entryFile, outputDirectory, toolsPaths);
|
|
176
232
|
const hasLibsql = await this.deps.checkDependencies(["@mastra/libsql"]) === `ok`;
|
|
177
233
|
if (hasLibsql) {
|
|
178
234
|
this.logger.error(
|
|
179
|
-
"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"
|
|
235
|
+
"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."
|
|
180
236
|
);
|
|
181
237
|
process.exit(1);
|
|
182
238
|
}
|
|
@@ -184,3 +240,5 @@ process.versions.node = '${process.versions.node}';
|
|
|
184
240
|
};
|
|
185
241
|
|
|
186
242
|
exports.CloudflareDeployer = CloudflareDeployer;
|
|
243
|
+
//# sourceMappingURL=index.cjs.map
|
|
244
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +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,MAAA,IAAI,OAAO,eAAA,EA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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 { join } 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 { 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\n/** @deprecated TODO remove deprecated fields in next major version */\ninterface D1DatabaseBinding {\n binding: string;\n database_name: string;\n database_id: string;\n preview_database_id?: string;\n}\n\n/** @deprecated TODO remove deprecated fields in next major version */\ninterface KVNamespaceBinding {\n binding: string;\n id: string;\n}\n\nexport class CloudflareDeployer extends Deployer {\n readonly userConfig: Omit<Unstable_RawConfig, 'main'>;\n\n constructor(\n userConfig: Omit<Unstable_RawConfig, 'main'> &\n // TODO remove deprecated fields in next major version\n {\n /** @deprecated `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 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 { vars: userVars, ...userConfig } = this.userConfig;\n const loadedEnvVars = await this.loadEnvVars();\n\n // Merge env vars from .env files with user-provided vars\n const envsAsObject = Object.assign({}, Object.fromEntries(loadedEnvVars.entries()), userVars);\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 };\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 { 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 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.d.ts
CHANGED
|
@@ -1 +1,42 @@
|
|
|
1
|
-
|
|
1
|
+
import { Deployer } from '@mastra/deployer';
|
|
2
|
+
import type { analyzeBundle } from '@mastra/deployer/analyze';
|
|
3
|
+
import type { BundlerOptions } from '@mastra/deployer/bundler';
|
|
4
|
+
import type { Unstable_RawConfig } from 'wrangler';
|
|
5
|
+
/** @deprecated TODO remove deprecated fields in next major version */
|
|
6
|
+
interface D1DatabaseBinding {
|
|
7
|
+
binding: string;
|
|
8
|
+
database_name: string;
|
|
9
|
+
database_id: string;
|
|
10
|
+
preview_database_id?: string;
|
|
11
|
+
}
|
|
12
|
+
/** @deprecated TODO remove deprecated fields in next major version */
|
|
13
|
+
interface KVNamespaceBinding {
|
|
14
|
+
binding: string;
|
|
15
|
+
id: string;
|
|
16
|
+
}
|
|
17
|
+
export declare class CloudflareDeployer extends Deployer {
|
|
18
|
+
readonly userConfig: Omit<Unstable_RawConfig, 'main'>;
|
|
19
|
+
constructor(userConfig: Omit<Unstable_RawConfig, 'main'> & {
|
|
20
|
+
/** @deprecated `name` instead. */
|
|
21
|
+
projectName?: string;
|
|
22
|
+
/** @deprecated this parameter is not used internally. */
|
|
23
|
+
workerNamespace?: string;
|
|
24
|
+
/** @deprecated use `d1_databases` instead. */
|
|
25
|
+
d1Databases?: D1DatabaseBinding[];
|
|
26
|
+
/** @deprecated use `kv_namespaces` instead. */
|
|
27
|
+
kvNamespaces?: KVNamespaceBinding[];
|
|
28
|
+
});
|
|
29
|
+
writeFiles(outputDirectory: string): Promise<void>;
|
|
30
|
+
private getEntry;
|
|
31
|
+
prepare(outputDirectory: string): Promise<void>;
|
|
32
|
+
protected getBundlerOptions(serverFile: string, mastraEntryFile: string, analyzedBundleInfo: Awaited<ReturnType<typeof analyzeBundle>>, toolsPaths: (string | string[])[], bundlerOptions: BundlerOptions): Promise<import("rollup").InputOptions>;
|
|
33
|
+
bundle(entryFile: string, outputDirectory: string, { toolsPaths, projectRoot }: {
|
|
34
|
+
toolsPaths: (string | string[])[];
|
|
35
|
+
projectRoot: string;
|
|
36
|
+
}): Promise<void>;
|
|
37
|
+
deploy(): Promise<void>;
|
|
38
|
+
tagWorker(): Promise<void>;
|
|
39
|
+
lint(entryFile: string, outputDirectory: string, toolsPaths: (string | string[])[]): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export {};
|
|
42
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,KAAK,EAAE,aAAa,EAAE,M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