@mastra/deployer-cloudflare 0.0.0-storage-20250225005900

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/LICENSE ADDED
@@ -0,0 +1,44 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ **Acceptance**
4
+ By using the software, you agree to all of the terms and conditions below.
5
+
6
+ **Copyright License**
7
+ 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
8
+
9
+ **Limitations**
10
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
11
+
12
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
13
+
14
+ 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.
15
+
16
+ **Patents**
17
+ 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.
18
+
19
+ **Notices**
20
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
21
+
22
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
23
+
24
+ **No Other Rights**
25
+ These terms do not imply any licenses other than those expressly granted in these terms.
26
+
27
+ **Termination**
28
+ 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.
29
+
30
+ **No Liability**
31
+ 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.
32
+
33
+ **Definitions**
34
+ 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.
35
+
36
+ _you_ refers to the individual or entity agreeing to these terms.
37
+
38
+ _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.
39
+
40
+ _your licenses_ are all the licenses granted to you for the software under these terms.
41
+
42
+ _use_ means anything you do with the software requiring one of your licenses.
43
+
44
+ _trademark_ means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,99 @@
1
+ # @mastra/deployer-cloudflare
2
+
3
+ A Cloudflare Workers deployer for Mastra applications.
4
+
5
+ ## Features
6
+
7
+ - Deploy Mastra applications to Cloudflare Workers
8
+ - Configure custom domains and routes
9
+ - Support for worker namespaces
10
+ - Automatic environment variable configuration
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add @mastra/deployer-cloudflare
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ The Cloudflare deployer is used as part of the Mastra framework:
21
+
22
+ ```typescript
23
+ import { Mastra } from '@mastra/core';
24
+ import { CloudflareDeployer } from '@mastra/deployer-cloudflare';
25
+
26
+ const deployer = new CloudflareDeployer({
27
+ scope: 'your-account-id',
28
+ projectName: 'your-project-name',
29
+ routes: [
30
+ {
31
+ pattern: 'example.com/*',
32
+ zone_name: 'example.com',
33
+ custom_domain: true,
34
+ },
35
+ ],
36
+ workerNamespace: 'your-namespace',
37
+ auth: {
38
+ apiToken: 'your-api-token',
39
+ apiEmail: 'your-email',
40
+ },
41
+ });
42
+
43
+ const mastra = new Mastra({
44
+ deployer,
45
+ // ... other Mastra configuration options
46
+ });
47
+ ```
48
+
49
+ ## Configuration
50
+
51
+ ### Constructor Options
52
+
53
+ - `scope` (required): Your Cloudflare account ID
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
63
+
64
+ ## Environment Variables
65
+
66
+ The deployer will automatically load environment variables from:
67
+
68
+ - `.env` files in your project
69
+ - Environment variables passed through the Mastra configuration
70
+
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
+ ## Requirements
96
+
97
+ - Cloudflare account with Workers enabled
98
+ - API token with appropriate permissions
99
+ - Domain(s) configured in Cloudflare (for custom domains)
@@ -0,0 +1,65 @@
1
+ import { Deployer } from '@mastra/deployer';
2
+
3
+ declare interface CFRoute {
4
+ pattern: string;
5
+ zone_name: string;
6
+ custom_domain?: boolean;
7
+ }
8
+
9
+ export declare class CloudflareDeployer extends Deployer {
10
+ private cloudflare;
11
+ routes?: CFRoute[];
12
+ workerNamespace?: string;
13
+ scope: string;
14
+ env?: Record<string, any>;
15
+ projectName?: string;
16
+ constructor({ scope, env, projectName, routes, workerNamespace, auth, }: {
17
+ env?: Record<string, any>;
18
+ scope: string;
19
+ projectName?: string;
20
+ routes?: CFRoute[];
21
+ workerNamespace?: string;
22
+ auth: {
23
+ apiToken: string;
24
+ apiEmail?: string;
25
+ };
26
+ });
27
+ writeFiles(outputDirectory: string): Promise<void>;
28
+ private getEntry;
29
+ prepare(outputDirectory: string): Promise<void>;
30
+ bundle(entryFile: string, outputDirectory: string): Promise<void>;
31
+ deploy(outputDirectory: string): Promise<void>;
32
+ tagWorker({ workerName, namespace, tags, scope, }: {
33
+ scope: string;
34
+ workerName: string;
35
+ namespace: string;
36
+ tags: string[];
37
+ }): Promise<void>;
38
+ }
39
+
40
+ export declare class CloudflareSecretsManager {
41
+ accountId: string;
42
+ apiToken: string;
43
+ baseUrl: string;
44
+ constructor({ accountId, apiToken }: {
45
+ accountId: string;
46
+ apiToken: string;
47
+ });
48
+ createSecret({ workerId, secretName, secretValue, }: {
49
+ workerId: string;
50
+ secretName: string;
51
+ secretValue: string;
52
+ }): Promise<any>;
53
+ createProjectSecrets({ workerId, customerId, envVars, }: {
54
+ workerId: string;
55
+ customerId: string;
56
+ envVars: Record<string, string>;
57
+ }): Promise<any>;
58
+ deleteSecret({ workerId, secretName }: {
59
+ workerId: string;
60
+ secretName: string;
61
+ }): Promise<any>;
62
+ listSecrets(workerId: string): Promise<any>;
63
+ }
64
+
65
+ export { }
@@ -0,0 +1 @@
1
+ export { CloudflareDeployer } from './_tsup-dts-rollup.js';
package/dist/index.js ADDED
@@ -0,0 +1,111 @@
1
+ import { Deployer, createChildProcessLogger } from '@mastra/deployer';
2
+ import '@mastra/deployer/build';
3
+ import '@rollup/plugin-virtual';
4
+ import { Cloudflare } from 'cloudflare';
5
+ import { writeFileSync } from 'fs';
6
+ import { join } from 'path';
7
+
8
+ // src/index.ts
9
+ var CloudflareDeployer = class extends Deployer {
10
+ cloudflare;
11
+ routes = [];
12
+ workerNamespace;
13
+ scope;
14
+ env;
15
+ projectName;
16
+ constructor({
17
+ scope,
18
+ env,
19
+ projectName = "mastra",
20
+ routes,
21
+ workerNamespace,
22
+ auth
23
+ }) {
24
+ super({ name: "CLOUDFLARE" });
25
+ this.scope = scope;
26
+ this.projectName = projectName;
27
+ this.routes = routes;
28
+ this.workerNamespace = workerNamespace;
29
+ if (env) {
30
+ this.env = env;
31
+ }
32
+ this.cloudflare = new Cloudflare(auth);
33
+ }
34
+ async writeFiles(outputDirectory) {
35
+ const env = await this.loadEnvVars();
36
+ const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);
37
+ const cfWorkerName = this.projectName;
38
+ const wranglerConfig = {
39
+ name: cfWorkerName,
40
+ main: "index.mjs",
41
+ compatibility_date: "2024-12-02",
42
+ compatibility_flags: ["nodejs_compat"],
43
+ observability: {
44
+ logs: {
45
+ enabled: true
46
+ }
47
+ },
48
+ vars: envsAsObject
49
+ };
50
+ if (!this.workerNamespace && this.routes) {
51
+ wranglerConfig.routes = this.routes;
52
+ }
53
+ writeFileSync(join(outputDirectory, "wrangler.json"), JSON.stringify(wranglerConfig));
54
+ }
55
+ getEntry() {
56
+ return `
57
+ export default {
58
+ fetch: async (request, env, context) => {
59
+ Object.keys(env).forEach(key => {
60
+ process.env[key] = env[key]
61
+ })
62
+
63
+ const { mastra } = await import('#mastra')
64
+ const { createHonoServer } = await import('#server')
65
+ const app = await createHonoServer(mastra)
66
+ return app.fetch(request, env, context);
67
+ }
68
+ }
69
+ `;
70
+ }
71
+ async prepare(outputDirectory) {
72
+ await super.prepare(outputDirectory);
73
+ await this.writeFiles(outputDirectory);
74
+ }
75
+ async bundle(entryFile, outputDirectory) {
76
+ return this._bundle(this.getEntry(), entryFile, outputDirectory);
77
+ }
78
+ async deploy(outputDirectory) {
79
+ const cmd = this.workerNamespace ? `npm exec -- wrangler deploy --dispatch-namespace ${this.workerNamespace}` : "npm exec -- wrangler deploy";
80
+ const cpLogger = createChildProcessLogger({
81
+ logger: this.logger,
82
+ root: outputDirectory
83
+ });
84
+ await cpLogger({
85
+ cmd,
86
+ args: [],
87
+ env: {
88
+ CLOUDFLARE_API_TOKEN: this.cloudflare.apiToken,
89
+ CLOUDFLARE_ACCOUNT_ID: this.scope,
90
+ ...this.env,
91
+ PATH: process.env.PATH
92
+ }
93
+ });
94
+ }
95
+ async tagWorker({
96
+ workerName,
97
+ namespace,
98
+ tags,
99
+ scope
100
+ }) {
101
+ if (!this.cloudflare) {
102
+ throw new Error("Cloudflare Deployer not initialized");
103
+ }
104
+ await this.cloudflare.workersForPlatforms.dispatch.namespaces.scripts.tags.update(namespace, workerName, {
105
+ account_id: scope,
106
+ body: tags
107
+ });
108
+ }
109
+ };
110
+
111
+ export { CloudflareDeployer };
@@ -0,0 +1 @@
1
+ export { CloudflareSecretsManager } from '../_tsup-dts-rollup.js';
@@ -0,0 +1,87 @@
1
+ // src/secrets-manager/index.ts
2
+ var CloudflareSecretsManager = class {
3
+ accountId;
4
+ apiToken;
5
+ baseUrl;
6
+ constructor({ accountId, apiToken }) {
7
+ this.accountId = accountId;
8
+ this.apiToken = apiToken;
9
+ this.baseUrl = "https://api.cloudflare.com/client/v4";
10
+ }
11
+ async createSecret({
12
+ workerId,
13
+ secretName,
14
+ secretValue
15
+ }) {
16
+ const url = `${this.baseUrl}/accounts/${this.accountId}/workers/scripts/${workerId}/secrets`;
17
+ try {
18
+ const response = await fetch(url, {
19
+ method: "PUT",
20
+ headers: {
21
+ Authorization: `Bearer ${this.apiToken}`,
22
+ "Content-Type": "application/json"
23
+ },
24
+ body: JSON.stringify({
25
+ name: secretName,
26
+ text: secretValue
27
+ })
28
+ });
29
+ const data = await response.json();
30
+ if (!data.success) {
31
+ throw new Error(data.errors[0].message);
32
+ }
33
+ return data.result;
34
+ } catch (error) {
35
+ console.error("Failed to create secret:", error);
36
+ throw error;
37
+ }
38
+ }
39
+ async createProjectSecrets({
40
+ workerId,
41
+ customerId,
42
+ envVars
43
+ }) {
44
+ const secretName = `PROJECT_${customerId.toUpperCase()}`;
45
+ const secretValue = JSON.stringify(envVars);
46
+ return this.createSecret({ workerId, secretName, secretValue });
47
+ }
48
+ async deleteSecret({ workerId, secretName }) {
49
+ const url = `${this.baseUrl}/accounts/${this.accountId}/workers/scripts/${workerId}/secrets/${secretName}`;
50
+ try {
51
+ const response = await fetch(url, {
52
+ method: "DELETE",
53
+ headers: {
54
+ Authorization: `Bearer ${this.apiToken}`
55
+ }
56
+ });
57
+ const data = await response.json();
58
+ if (!data.success) {
59
+ throw new Error(data.errors[0].message);
60
+ }
61
+ return data.result;
62
+ } catch (error) {
63
+ console.error("Failed to delete secret:", error);
64
+ throw error;
65
+ }
66
+ }
67
+ async listSecrets(workerId) {
68
+ const url = `${this.baseUrl}/accounts/${this.accountId}/workers/scripts/${workerId}/secrets`;
69
+ try {
70
+ const response = await fetch(url, {
71
+ headers: {
72
+ Authorization: `Bearer ${this.apiToken}`
73
+ }
74
+ });
75
+ const data = await response.json();
76
+ if (!data.success) {
77
+ throw new Error(data.errors[0].message);
78
+ }
79
+ return data.result;
80
+ } catch (error) {
81
+ console.error("Failed to list secrets:", error);
82
+ throw error;
83
+ }
84
+ }
85
+ };
86
+
87
+ export { CloudflareSecretsManager };
package/global.d.ts ADDED
@@ -0,0 +1 @@
1
+ declare module 'rollup-plugin-shim';
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@mastra/deployer-cloudflare",
3
+ "version": "0.0.0-storage-20250225005900",
4
+ "description": "",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./secrets-manager": {
14
+ "types": "./dist/secrets-manager/index.d.ts",
15
+ "default": "./dist/secrets-manager/index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "keywords": [],
20
+ "author": "",
21
+ "license": "ISC",
22
+ "dependencies": {
23
+ "@rollup/plugin-virtual": "^3.0.2",
24
+ "cloudflare": "^4.0.0",
25
+ "date-fns": "^4.1.0",
26
+ "execa": "^9.3.1",
27
+ "rollup-plugin-polyfill-node": "^0.13.0",
28
+ "rollup-plugin-shim": "^1.0.0",
29
+ "wrangler": "^3.103.2",
30
+ "zod": "^3.24.1",
31
+ "@mastra/core": "^0.0.0-storage-20250225005900",
32
+ "@mastra/deployer": "^0.0.0-storage-20250225005900"
33
+ },
34
+ "devDependencies": {
35
+ "@microsoft/api-extractor": "^7.49.2",
36
+ "@types/node": "^22.13.1",
37
+ "tsup": "^8.0.1",
38
+ "typescript": "^5.7.3",
39
+ "vitest": "^3.0.4"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup src/index.ts src/secrets-manager/index.ts --format esm --experimental-dts --clean --treeshake",
43
+ "build:watch": "pnpm build --watch",
44
+ "test": "vitest run"
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,148 @@
1
+ import { Deployer, createChildProcessLogger } from '@mastra/deployer';
2
+ import { getBundler } from '@mastra/deployer/build';
3
+ import virtual from '@rollup/plugin-virtual';
4
+ import { Cloudflare } from 'cloudflare';
5
+ import { writeFileSync } from 'fs';
6
+ import { join } from 'path';
7
+
8
+ interface CFRoute {
9
+ pattern: string;
10
+ zone_name: string;
11
+ custom_domain?: boolean;
12
+ }
13
+
14
+ export class CloudflareDeployer extends Deployer {
15
+ private cloudflare: Cloudflare | undefined;
16
+ routes?: CFRoute[] = [];
17
+ workerNamespace?: string;
18
+ scope: string;
19
+ env?: Record<string, any>;
20
+ projectName?: string;
21
+
22
+ constructor({
23
+ scope,
24
+ env,
25
+ projectName = 'mastra',
26
+ routes,
27
+ workerNamespace,
28
+ auth,
29
+ }: {
30
+ env?: Record<string, any>;
31
+ scope: string;
32
+ projectName?: string;
33
+ routes?: CFRoute[];
34
+ workerNamespace?: string;
35
+ auth: {
36
+ apiToken: string;
37
+ apiEmail?: string;
38
+ };
39
+ }) {
40
+ super({ name: 'CLOUDFLARE' });
41
+
42
+ this.scope = scope;
43
+ this.projectName = projectName;
44
+ this.routes = routes;
45
+ this.workerNamespace = workerNamespace;
46
+
47
+ if (env) {
48
+ this.env = env;
49
+ }
50
+
51
+ this.cloudflare = new Cloudflare(auth);
52
+ }
53
+
54
+ async writeFiles(outputDirectory: string): Promise<void> {
55
+ const env = await this.loadEnvVars();
56
+
57
+ const envsAsObject = Object.assign({}, Object.fromEntries(env.entries()), this.env);
58
+
59
+ const cfWorkerName = this.projectName;
60
+
61
+ const wranglerConfig: Record<string, any> = {
62
+ name: cfWorkerName,
63
+ main: 'index.mjs',
64
+ compatibility_date: '2024-12-02',
65
+ compatibility_flags: ['nodejs_compat'],
66
+ observability: {
67
+ logs: {
68
+ enabled: true,
69
+ },
70
+ },
71
+ vars: envsAsObject,
72
+ };
73
+
74
+ if (!this.workerNamespace && this.routes) {
75
+ wranglerConfig.routes = this.routes;
76
+ }
77
+
78
+ writeFileSync(join(outputDirectory, 'wrangler.json'), JSON.stringify(wranglerConfig));
79
+ }
80
+
81
+ private getEntry(): string {
82
+ return `
83
+ export default {
84
+ fetch: async (request, env, context) => {
85
+ Object.keys(env).forEach(key => {
86
+ process.env[key] = env[key]
87
+ })
88
+
89
+ const { mastra } = await import('#mastra')
90
+ const { createHonoServer } = await import('#server')
91
+ const app = await createHonoServer(mastra)
92
+ return app.fetch(request, env, context);
93
+ }
94
+ }
95
+ `;
96
+ }
97
+ async prepare(outputDirectory: string): Promise<void> {
98
+ await super.prepare(outputDirectory);
99
+ await this.writeFiles(outputDirectory);
100
+ }
101
+
102
+ async bundle(entryFile: string, outputDirectory: string): Promise<void> {
103
+ return this._bundle(this.getEntry(), entryFile, outputDirectory);
104
+ }
105
+
106
+ async deploy(outputDirectory: string): Promise<void> {
107
+ const cmd = this.workerNamespace
108
+ ? `npm exec -- wrangler deploy --dispatch-namespace ${this.workerNamespace}`
109
+ : 'npm exec -- wrangler deploy';
110
+
111
+ const cpLogger = createChildProcessLogger({
112
+ logger: this.logger,
113
+ root: outputDirectory,
114
+ });
115
+
116
+ await cpLogger({
117
+ cmd,
118
+ args: [],
119
+ env: {
120
+ CLOUDFLARE_API_TOKEN: this.cloudflare!.apiToken!,
121
+ CLOUDFLARE_ACCOUNT_ID: this.scope,
122
+ ...this.env,
123
+ PATH: process.env.PATH!,
124
+ },
125
+ });
126
+ }
127
+
128
+ async tagWorker({
129
+ workerName,
130
+ namespace,
131
+ tags,
132
+ scope,
133
+ }: {
134
+ scope: string;
135
+ workerName: string;
136
+ namespace: string;
137
+ tags: string[];
138
+ }): Promise<void> {
139
+ if (!this.cloudflare) {
140
+ throw new Error('Cloudflare Deployer not initialized');
141
+ }
142
+
143
+ await this.cloudflare.workersForPlatforms.dispatch.namespaces.scripts.tags.update(namespace, workerName, {
144
+ account_id: scope,
145
+ body: tags,
146
+ });
147
+ }
148
+ }