@mastra/deployer 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.
Files changed (73) hide show
  1. package/.turbo/turbo-build.log +30 -0
  2. package/CHANGELOG.md +855 -0
  3. package/LICENSE +44 -0
  4. package/README.md +159 -0
  5. package/dist/_tsup-dts-rollup.d.ts +360 -0
  6. package/dist/build/analyze.d.ts +1 -0
  7. package/dist/build/analyze.js +2 -0
  8. package/dist/build/bundler.d.ts +2 -0
  9. package/dist/build/bundler.js +2 -0
  10. package/dist/build/index.d.ts +10 -0
  11. package/dist/build/index.js +5 -0
  12. package/dist/bundler/index.d.ts +1 -0
  13. package/dist/bundler/index.js +5 -0
  14. package/dist/chunk-AXS5WSIK.js +290 -0
  15. package/dist/chunk-BTUQ6UBB.js +254 -0
  16. package/dist/chunk-IHPQAB7O.js +113 -0
  17. package/dist/chunk-KXS4XYEJ.js +251 -0
  18. package/dist/chunk-SESHBX76.js +267 -0
  19. package/dist/chunk-YNXJO2XU.js +69 -0
  20. package/dist/index.d.ts +6 -0
  21. package/dist/index.js +131 -0
  22. package/dist/server/index.d.ts +2 -0
  23. package/dist/server/index.js +4907 -0
  24. package/dist/templates/instrumentation-template.js +86 -0
  25. package/eslint.config.js +6 -0
  26. package/global.d.ts +0 -0
  27. package/package.json +84 -0
  28. package/public/templates/instrumentation-template.js +86 -0
  29. package/src/build/analyze.ts +271 -0
  30. package/src/build/babel/fix-libsql.ts +41 -0
  31. package/src/build/babel/get-deployer.ts +54 -0
  32. package/src/build/babel/get-telemetry-config.ts +62 -0
  33. package/src/build/babel/remove-deployer.ts +43 -0
  34. package/src/build/bundle.ts +139 -0
  35. package/src/build/bundler.ts +126 -0
  36. package/src/build/deployer.ts +67 -0
  37. package/src/build/deps.ts +149 -0
  38. package/src/build/env.ts +76 -0
  39. package/src/build/fs.ts +66 -0
  40. package/src/build/index.ts +7 -0
  41. package/src/build/isNodeBuiltin.ts +7 -0
  42. package/src/build/plugins/fix-libsql.ts +69 -0
  43. package/src/build/plugins/hono-alias.ts +17 -0
  44. package/src/build/plugins/pino.ts +93 -0
  45. package/src/build/plugins/remove-deployer.ts +37 -0
  46. package/src/build/plugins/telemetry-fix.ts +54 -0
  47. package/src/build/telemetry.ts +76 -0
  48. package/src/build/utils.ts +12 -0
  49. package/src/build/watcher.ts +43 -0
  50. package/src/bundler/index.ts +145 -0
  51. package/src/deploy/base.ts +30 -0
  52. package/src/deploy/index.ts +2 -0
  53. package/src/deploy/log.ts +61 -0
  54. package/src/index.ts +3 -0
  55. package/src/server/handlers/agents.ts +210 -0
  56. package/src/server/handlers/client.ts +36 -0
  57. package/src/server/handlers/error.ts +29 -0
  58. package/src/server/handlers/logs.ts +53 -0
  59. package/src/server/handlers/memory.ts +196 -0
  60. package/src/server/handlers/prompt.ts +128 -0
  61. package/src/server/handlers/root.ts +6 -0
  62. package/src/server/handlers/telemetry.ts +48 -0
  63. package/src/server/handlers/tools.ts +107 -0
  64. package/src/server/handlers/utils.ts +15 -0
  65. package/src/server/handlers/vector.ts +149 -0
  66. package/src/server/handlers/workflows.ts +104 -0
  67. package/src/server/index.ts +1355 -0
  68. package/src/server/openapi.json +434 -0
  69. package/src/server/openapi.script.js +22 -0
  70. package/src/server/types.ts +4 -0
  71. package/src/server/welcome.ts +105 -0
  72. package/tsconfig.json +5 -0
  73. package/vitest.config.ts +8 -0
@@ -0,0 +1,290 @@
1
+ import { spawn } from 'child_process';
2
+ import { Transform } from 'stream';
3
+ import { MastraBase } from '@mastra/core/base';
4
+ import fs from 'fs';
5
+ import path, { dirname } from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import fsExtra from 'fs-extra/esm';
8
+ import fsPromises from 'fs/promises';
9
+ import * as babel from '@babel/core';
10
+ import babel__default from '@babel/core';
11
+ import { rollup } from 'rollup';
12
+ import esbuild from 'rollup-plugin-esbuild';
13
+
14
+ // src/deploy/log.ts
15
+ var createPinoStream = (logger) => {
16
+ return new Transform({
17
+ transform(chunk, _encoding, callback) {
18
+ const line = chunk.toString().trim();
19
+ if (line) {
20
+ console.log(line);
21
+ logger.info(line);
22
+ }
23
+ callback(null, chunk);
24
+ }
25
+ });
26
+ };
27
+ function createChildProcessLogger({ logger, root }) {
28
+ const pinoStream = createPinoStream(logger);
29
+ return async ({ cmd, args, env }) => {
30
+ try {
31
+ const subprocess = spawn(cmd, args, {
32
+ cwd: root,
33
+ shell: true,
34
+ env
35
+ });
36
+ subprocess.stdout?.pipe(pinoStream);
37
+ subprocess.stderr?.pipe(pinoStream);
38
+ return new Promise((resolve, reject) => {
39
+ subprocess.on("close", (code) => {
40
+ pinoStream.end();
41
+ if (code === 0) {
42
+ resolve({ success: true });
43
+ } else {
44
+ reject(new Error(`Process exited with code ${code}`));
45
+ }
46
+ });
47
+ subprocess.on("error", (error) => {
48
+ pinoStream.end();
49
+ logger.error("Process failed", { error });
50
+ reject(error);
51
+ });
52
+ });
53
+ } catch (error) {
54
+ console.log(error);
55
+ logger.error("Process failed", { error });
56
+ pinoStream.end();
57
+ return { success: false, error };
58
+ }
59
+ };
60
+ }
61
+ var Deps = class extends MastraBase {
62
+ packageManager;
63
+ rootDir;
64
+ constructor(rootDir = process.cwd()) {
65
+ super({ component: "DEPLOYER", name: "DEPS" });
66
+ this.rootDir = rootDir;
67
+ this.packageManager = this.getPackageManager();
68
+ }
69
+ findLockFile(dir) {
70
+ const lockFiles = ["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "bun.lock"];
71
+ for (const file of lockFiles) {
72
+ if (fs.existsSync(path.join(dir, file))) {
73
+ return file;
74
+ }
75
+ }
76
+ const parentDir = path.resolve(dir, "..");
77
+ if (parentDir !== dir) {
78
+ return this.findLockFile(parentDir);
79
+ }
80
+ return null;
81
+ }
82
+ getPackageManager() {
83
+ const lockFile = this.findLockFile(this.rootDir);
84
+ switch (lockFile) {
85
+ case "pnpm-lock.yaml":
86
+ return "pnpm";
87
+ case "package-lock.json":
88
+ return "npm";
89
+ case "yarn.lock":
90
+ return "yarn";
91
+ case "bun.lock":
92
+ return "bun";
93
+ default:
94
+ return "npm";
95
+ }
96
+ }
97
+ async install({ dir = this.rootDir, packages = [] }) {
98
+ let runCommand = this.packageManager;
99
+ if (this.packageManager === "npm") {
100
+ runCommand = `${this.packageManager} i`;
101
+ } else {
102
+ runCommand = `${this.packageManager} ${packages?.length > 0 ? `add` : `install`}`;
103
+ }
104
+ const cpLogger = createChildProcessLogger({
105
+ logger: this.logger,
106
+ root: dir
107
+ });
108
+ return cpLogger({
109
+ cmd: runCommand,
110
+ args: packages,
111
+ env: {
112
+ PATH: process.env.PATH
113
+ }
114
+ });
115
+ }
116
+ async installPackages(packages) {
117
+ let runCommand = this.packageManager;
118
+ if (this.packageManager === "npm") {
119
+ runCommand = `${this.packageManager} i`;
120
+ } else {
121
+ runCommand = `${this.packageManager} add`;
122
+ }
123
+ const cpLogger = createChildProcessLogger({
124
+ logger: this.logger,
125
+ root: ""
126
+ });
127
+ return cpLogger({
128
+ cmd: `${runCommand}`,
129
+ args: packages,
130
+ env: {
131
+ PATH: process.env.PATH
132
+ }
133
+ });
134
+ }
135
+ async checkDependencies(dependencies) {
136
+ try {
137
+ const packageJsonPath = path.join(this.rootDir, "package.json");
138
+ try {
139
+ await fsPromises.access(packageJsonPath);
140
+ } catch {
141
+ return "No package.json file found in the current directory";
142
+ }
143
+ const packageJson = JSON.parse(await fsPromises.readFile(packageJsonPath, "utf-8"));
144
+ for (const dependency of dependencies) {
145
+ if (!packageJson.dependencies || !packageJson.dependencies[dependency]) {
146
+ return `Please install ${dependency} before running this command (${this.packageManager} install ${dependency})`;
147
+ }
148
+ }
149
+ return "ok";
150
+ } catch (err) {
151
+ console.error(err);
152
+ return "Could not check dependencies";
153
+ }
154
+ }
155
+ async getProjectName() {
156
+ try {
157
+ const packageJsonPath = path.join(this.rootDir, "package.json");
158
+ const packageJson = await fsPromises.readFile(packageJsonPath, "utf-8");
159
+ const pkg = JSON.parse(packageJson);
160
+ return pkg.name;
161
+ } catch (err) {
162
+ throw err;
163
+ }
164
+ }
165
+ async getPackageVersion() {
166
+ const __filename = fileURLToPath(import.meta.url);
167
+ const __dirname = dirname(__filename);
168
+ const pkgJsonPath = path.join(__dirname, "..", "..", "package.json");
169
+ const content = await fsExtra.readJSON(pkgJsonPath);
170
+ return content.version;
171
+ }
172
+ async addScriptsToPackageJson(scripts) {
173
+ const packageJson = JSON.parse(await fsPromises.readFile("package.json", "utf-8"));
174
+ packageJson.scripts = {
175
+ ...packageJson.scripts,
176
+ ...scripts
177
+ };
178
+ await fsPromises.writeFile("package.json", JSON.stringify(packageJson, null, 2));
179
+ }
180
+ };
181
+ function removeAllExceptTelemetryConfig(result) {
182
+ let mastraClass = null;
183
+ const t = babel__default.types;
184
+ return {
185
+ name: "remove-all-except-telemetry-config",
186
+ visitor: {
187
+ ExportNamedDeclaration: {
188
+ // remove all exports
189
+ exit(path2) {
190
+ path2.remove();
191
+ }
192
+ },
193
+ ImportDeclaration(path2) {
194
+ if ((path2.node.source.value === "@mastra/core" || path2.node.source.value === "@mastra/core/mastra") && path2.node.specifiers) {
195
+ mastraClass = path2.node.specifiers.find(
196
+ // @ts-ignore - no need to type
197
+ (p) => p.imported?.name === "Mastra"
198
+ )?.local?.name ?? null;
199
+ }
200
+ },
201
+ NewExpression(path2) {
202
+ if (mastraClass && path2.node.callee.name === mastraClass) {
203
+ let telemetry = path2.node.arguments[0]?.properties?.find(
204
+ // @ts-ignore
205
+ (prop) => prop.key.name === "telemetry"
206
+ );
207
+ const programPath = path2.scope.getProgramParent().path;
208
+ if (!programPath) {
209
+ return;
210
+ }
211
+ if (telemetry) {
212
+ result.hasCustomConfig = true;
213
+ } else {
214
+ telemetry = {
215
+ value: t.objectExpression([])
216
+ };
217
+ }
218
+ const exportDeclaration = t.exportNamedDeclaration(
219
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier("telemetry"), telemetry.value)]),
220
+ []
221
+ );
222
+ programPath.node.body.push(exportDeclaration);
223
+ }
224
+ }
225
+ }
226
+ };
227
+ }
228
+
229
+ // src/build/telemetry.ts
230
+ async function writeTelemetryConfig(entryFile, outputDir) {
231
+ const result = {
232
+ hasCustomConfig: false
233
+ };
234
+ const bundle = await rollup({
235
+ input: {
236
+ "telemetry-config": entryFile
237
+ },
238
+ treeshake: true,
239
+ plugins: [
240
+ // transpile typescript to something we understand
241
+ esbuild({
242
+ target: "node20",
243
+ platform: "node",
244
+ minify: false
245
+ }),
246
+ {
247
+ name: "get-telemetry-config",
248
+ transform(code, id) {
249
+ if (!this.getModuleInfo(id)?.isEntry) {
250
+ return;
251
+ }
252
+ return new Promise((resolve, reject) => {
253
+ babel.transform(
254
+ code,
255
+ {
256
+ babelrc: false,
257
+ configFile: false,
258
+ filename: id,
259
+ plugins: [removeAllExceptTelemetryConfig(result)]
260
+ },
261
+ (err, result2) => {
262
+ if (err) {
263
+ return reject(err);
264
+ }
265
+ resolve({
266
+ code: result2.code,
267
+ map: result2.map
268
+ });
269
+ }
270
+ );
271
+ });
272
+ }
273
+ },
274
+ // let esbuild remove all unused imports
275
+ esbuild({
276
+ target: "node20",
277
+ platform: "node",
278
+ minify: false
279
+ })
280
+ ]
281
+ });
282
+ await bundle.write({
283
+ dir: outputDir,
284
+ format: "es",
285
+ entryFileNames: "[name].mjs"
286
+ });
287
+ return result;
288
+ }
289
+
290
+ export { Deps, createChildProcessLogger, createPinoStream, writeTelemetryConfig };
@@ -0,0 +1,254 @@
1
+ import { aliasHono } from './chunk-SESHBX76.js';
2
+ import { getInputOptions, telemetryFix, libSqlFix } from './chunk-KXS4XYEJ.js';
3
+ import { removeDeployer } from './chunk-YNXJO2XU.js';
4
+ import alias from '@rollup/plugin-alias';
5
+ import commonjs from '@rollup/plugin-commonjs';
6
+ import json from '@rollup/plugin-json';
7
+ import { nodeResolve } from '@rollup/plugin-node-resolve';
8
+ import { builtinModules } from 'node:module';
9
+ import path, { join } from 'path';
10
+ import { rollup, watch } from 'rollup';
11
+ import esbuild from 'rollup-plugin-esbuild';
12
+ import { fileURLToPath } from 'url';
13
+ import * as fs2 from 'fs';
14
+ import fs2__default from 'fs';
15
+ import fsExtra from 'fs-extra/esm';
16
+
17
+ var EnvService = class {
18
+ };
19
+ var FileEnvService = class extends EnvService {
20
+ filePath;
21
+ constructor(filePath) {
22
+ super();
23
+ this.filePath = filePath;
24
+ }
25
+ readFile(filePath) {
26
+ return new Promise((resolve, reject) => {
27
+ fs2.readFile(filePath, "utf8", (err, data) => {
28
+ if (err) reject(err);
29
+ else resolve(data);
30
+ });
31
+ });
32
+ }
33
+ writeFile({ filePath, data }) {
34
+ return new Promise((resolve, reject) => {
35
+ fs2.writeFile(filePath, data, "utf8", (err) => {
36
+ if (err) reject(err);
37
+ else resolve();
38
+ });
39
+ });
40
+ }
41
+ async updateEnvData({
42
+ key,
43
+ value,
44
+ filePath = this.filePath,
45
+ data
46
+ }) {
47
+ const regex = new RegExp(`^${key}=.*$`, "m");
48
+ if (data.match(regex)) {
49
+ data = data.replace(regex, `${key}=${value}`);
50
+ } else {
51
+ data += `
52
+ ${key}=${value}`;
53
+ }
54
+ await this.writeFile({ filePath, data });
55
+ console.log(`${key} set to ${value} in ENV file.`);
56
+ return data;
57
+ }
58
+ async getEnvValue(key) {
59
+ try {
60
+ const data = await this.readFile(this.filePath);
61
+ const regex = new RegExp(`^${key}=(.*)$`, "m");
62
+ const match = data.match(regex);
63
+ return match?.[1] || null;
64
+ } catch (err) {
65
+ console.error(`Error reading ENV value: ${err}`);
66
+ return null;
67
+ }
68
+ }
69
+ async setEnvValue(key, value) {
70
+ try {
71
+ const data = await this.readFile(this.filePath);
72
+ await this.updateEnvData({ key, value, data });
73
+ } catch (err) {
74
+ console.error(`Error writing ENV value: ${err}`);
75
+ }
76
+ }
77
+ };
78
+
79
+ // src/build/fs.ts
80
+ var FileService = class {
81
+ /**
82
+ *
83
+ * @param inputFile the file in the starter files directory to copy
84
+ * @param outputFilePath the destination path
85
+ * @param replaceIfExists flag to replace if it exists
86
+ * @returns
87
+ */
88
+ async copyStarterFile(inputFile, outputFilePath, replaceIfExists) {
89
+ const __filename = fileURLToPath(import.meta.url);
90
+ const __dirname = path.dirname(__filename);
91
+ const filePath = path.resolve(__dirname, "..", "starter-files", inputFile);
92
+ const fileString = fs2__default.readFileSync(filePath, "utf8");
93
+ if (fs2__default.existsSync(outputFilePath) && !replaceIfExists) {
94
+ console.log(`${outputFilePath} already exists`);
95
+ return false;
96
+ }
97
+ await fsExtra.outputFile(outputFilePath, fileString);
98
+ return true;
99
+ }
100
+ async setupEnvFile({ dbUrl }) {
101
+ const envPath = path.join(process.cwd(), ".env.development");
102
+ await fsExtra.ensureFile(envPath);
103
+ const fileEnvService = new FileEnvService(envPath);
104
+ await fileEnvService.setEnvValue("DB_URL", dbUrl);
105
+ }
106
+ getFirstExistingFile(files) {
107
+ for (const f of files) {
108
+ if (fs2__default.existsSync(f)) {
109
+ return f;
110
+ }
111
+ }
112
+ throw new Error("Missing required file, checked the following paths: " + files.join(", "));
113
+ }
114
+ replaceValuesInFile({
115
+ filePath,
116
+ replacements
117
+ }) {
118
+ let fileContent = fs2__default.readFileSync(filePath, "utf8");
119
+ replacements.forEach(({ search, replace }) => {
120
+ fileContent = fileContent.replaceAll(search, replace);
121
+ });
122
+ fs2__default.writeFileSync(filePath, fileContent);
123
+ }
124
+ };
125
+
126
+ // src/build/bundle.ts
127
+ function getOptions(inputOptions, platform, root) {
128
+ const fileService = new FileService();
129
+ const entry = fileService.getFirstExistingFile([
130
+ join(root, "src/mastra/index.ts"),
131
+ join(root, "src/mastra/index.js")
132
+ ]);
133
+ const nodeBuiltins = platform === "node" ? builtinModules : [];
134
+ let nodeResolvePlugin = platform === "node" ? nodeResolve({
135
+ preferBuiltins: true,
136
+ exportConditions: ["node", "import", "require"],
137
+ mainFields: ["module", "main"]
138
+ }) : nodeResolve({
139
+ preferBuiltins: false,
140
+ exportConditions: ["browser", "import", "require"],
141
+ mainFields: ["module", "main"],
142
+ browser: true
143
+ });
144
+ return {
145
+ logLevel: "silent",
146
+ ...inputOptions,
147
+ treeshake: false,
148
+ preserveSymlinks: true,
149
+ external: [
150
+ ...nodeBuiltins,
151
+ ...nodeBuiltins.map((builtin) => "node:" + builtin),
152
+ ...inputOptions.external ?? []
153
+ ],
154
+ plugins: [
155
+ ...inputOptions.plugins ?? [],
156
+ telemetryFix(),
157
+ alias({
158
+ entries: [
159
+ {
160
+ find: /^\#server$/,
161
+ replacement: fileURLToPath(import.meta.resolve("@mastra/deployer/server")).replaceAll("\\", "/")
162
+ },
163
+ { find: /^\#mastra$/, replacement: entry.replaceAll("\\", "/") },
164
+ {
165
+ find: /^hono\//,
166
+ replacement: "hono/",
167
+ customResolver: (id, importer) => {
168
+ if (!importer?.startsWith("\0virtual")) {
169
+ return null;
170
+ }
171
+ const path2 = import.meta.resolve(id);
172
+ return fileURLToPath(path2);
173
+ }
174
+ }
175
+ ]
176
+ }),
177
+ commonjs({
178
+ strictRequires: "strict",
179
+ transformMixedEsModules: true
180
+ // dynamicRequireTargets: ['node_modules/**/@libsql+win32-*/*'],
181
+ }),
182
+ libSqlFix(),
183
+ // for debugging
184
+ // {
185
+ // name: 'logger',
186
+ // // @ts-ignore
187
+ // resolveId(id, ...args) {
188
+ // console.log({ id, args });
189
+ // },
190
+ // },
191
+ nodeResolvePlugin,
192
+ json(),
193
+ esbuild({
194
+ include: /\.tsx?$/,
195
+ target: "node20",
196
+ platform,
197
+ minify: false,
198
+ define: {
199
+ "process.env.NODE_ENV": JSON.stringify("production")
200
+ }
201
+ }),
202
+ removeDeployer(entry),
203
+ esbuild({
204
+ include: entry,
205
+ target: "node20",
206
+ platform,
207
+ minify: false
208
+ })
209
+ ].filter(Boolean)
210
+ };
211
+ }
212
+ async function getBundler(inputOptions, args = {}) {
213
+ const { platform = "node", dir = process.cwd() } = args;
214
+ const bundle = await rollup(getOptions(inputOptions, platform, dir));
215
+ return bundle;
216
+ }
217
+ async function getWatcher(inputOptions, args = {}) {
218
+ const { platform = "node", dir = process.cwd() } = args;
219
+ const watcher = watch(getOptions(inputOptions, platform, dir));
220
+ return watcher;
221
+ }
222
+ async function getInputOptions2(entryFile, platform) {
223
+ const inputOptions = await getInputOptions(
224
+ entryFile,
225
+ {
226
+ dependencies: /* @__PURE__ */ new Map(),
227
+ externalDependencies: /* @__PURE__ */ new Set(),
228
+ invalidChunks: /* @__PURE__ */ new Set()
229
+ },
230
+ platform
231
+ );
232
+ if (Array.isArray(inputOptions.plugins)) {
233
+ inputOptions.plugins = inputOptions.plugins.filter(
234
+ // @ts-ignore
235
+ (plugin) => !plugin || !plugin?.name || plugin.name !== "node-resolve"
236
+ );
237
+ inputOptions.plugins.push(aliasHono());
238
+ }
239
+ return inputOptions;
240
+ }
241
+ async function createWatcher(inputOptions, outputOptions) {
242
+ const watcher = await watch({
243
+ ...inputOptions,
244
+ output: {
245
+ ...outputOptions,
246
+ format: "esm",
247
+ entryFileNames: "[name].mjs",
248
+ chunkFileNames: "[name].mjs"
249
+ }
250
+ });
251
+ return watcher;
252
+ }
253
+
254
+ export { FileService, createWatcher, getBundler, getInputOptions2 as getInputOptions, getWatcher };
@@ -0,0 +1,113 @@
1
+ import { Deps, writeTelemetryConfig } from './chunk-AXS5WSIK.js';
2
+ import { analyzeBundle } from './chunk-SESHBX76.js';
3
+ import { createBundler, getInputOptions } from './chunk-KXS4XYEJ.js';
4
+ import { MastraBundler } from '@mastra/core/bundler';
5
+ import virtual from '@rollup/plugin-virtual';
6
+ import { ensureDir, copy } from 'fs-extra';
7
+ import { existsSync } from 'node:fs';
8
+ import { writeFile } from 'node:fs/promises';
9
+ import { join, dirname } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import fsExtra from 'fs-extra/esm';
12
+
13
+ var Bundler = class extends MastraBundler {
14
+ analyzeOutputDir = ".build";
15
+ outputDir = "output";
16
+ constructor(name, component = "BUNDLER") {
17
+ super({ name, component });
18
+ }
19
+ async prepare(outputDirectory) {
20
+ await fsExtra.emptyDir(outputDirectory);
21
+ await ensureDir(join(outputDirectory, this.analyzeOutputDir));
22
+ await ensureDir(join(outputDirectory, this.outputDir));
23
+ }
24
+ async writeInstrumentationFile(outputDirectory) {
25
+ const instrumentationFile = join(outputDirectory, "instrumentation.mjs");
26
+ const __dirname = dirname(fileURLToPath(import.meta.url));
27
+ await copy(join(__dirname, "templates", "instrumentation-template.js"), instrumentationFile);
28
+ }
29
+ async writePackageJson(outputDirectory, dependencies) {
30
+ this.logger.debug(`Writing project's package.json`);
31
+ await ensureDir(outputDirectory);
32
+ const pkgPath = join(outputDirectory, "package.json");
33
+ const dependenciesMap = /* @__PURE__ */ new Map();
34
+ for (const [key, value] of dependencies.entries()) {
35
+ if (key.startsWith("@")) {
36
+ const pkgChunks = key.split("/");
37
+ dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);
38
+ continue;
39
+ }
40
+ dependenciesMap.set(key, value);
41
+ }
42
+ dependenciesMap.set("@opentelemetry/instrumentation", "latest");
43
+ await writeFile(
44
+ pkgPath,
45
+ JSON.stringify(
46
+ {
47
+ name: "server",
48
+ version: "1.0.0",
49
+ description: "",
50
+ type: "module",
51
+ main: "index.mjs",
52
+ scripts: {
53
+ start: "node ./index.mjs"
54
+ },
55
+ author: "Mastra",
56
+ license: "ISC",
57
+ dependencies: Object.fromEntries(dependenciesMap.entries())
58
+ },
59
+ null,
60
+ 2
61
+ )
62
+ );
63
+ }
64
+ createBundler(inputOptions, outputOptions) {
65
+ return createBundler(inputOptions, outputOptions);
66
+ }
67
+ async analyze(entry, mastraFile, outputDirectory) {
68
+ return await analyzeBundle(entry, mastraFile, join(outputDirectory, this.analyzeOutputDir), "node", this.logger);
69
+ }
70
+ async installDependencies(outputDirectory, rootDir = process.cwd()) {
71
+ const deps = new Deps(rootDir);
72
+ deps.__setLogger(this.logger);
73
+ await deps.install({ dir: join(outputDirectory, this.outputDir) });
74
+ }
75
+ async _bundle(serverFile, mastraEntryFile, outputDirectory, bundleLocation = join(outputDirectory, this.outputDir)) {
76
+ this.logger.info("Start bundling Mastra");
77
+ const isVirtual = serverFile.includes("\n") || existsSync(serverFile);
78
+ const analyzedBundleInfo = await analyzeBundle(
79
+ serverFile,
80
+ mastraEntryFile,
81
+ join(outputDirectory, this.analyzeOutputDir),
82
+ "node",
83
+ this.logger
84
+ );
85
+ await writeTelemetryConfig(mastraEntryFile, join(outputDirectory, this.outputDir));
86
+ const dependenciesToInstall = Array.from(analyzedBundleInfo.externalDependencies).reduce((acc, dep) => {
87
+ acc.set(dep, "latest");
88
+ return acc;
89
+ }, /* @__PURE__ */ new Map());
90
+ await this.writePackageJson(join(outputDirectory, this.outputDir), dependenciesToInstall);
91
+ await this.writeInstrumentationFile(join(outputDirectory, this.outputDir));
92
+ this.logger.info("Bundling Mastra application");
93
+ const inputOptions = await getInputOptions(mastraEntryFile, analyzedBundleInfo, "node");
94
+ if (isVirtual) {
95
+ inputOptions.input = { index: "#entry" };
96
+ if (Array.isArray(inputOptions.plugins)) {
97
+ inputOptions.plugins.unshift(virtual({ "#entry": serverFile }));
98
+ } else {
99
+ inputOptions.plugins = [virtual({ "#entry": serverFile })];
100
+ }
101
+ } else {
102
+ inputOptions.input = { index: serverFile };
103
+ }
104
+ const bundler = await this.createBundler(inputOptions, { dir: bundleLocation });
105
+ await bundler.write();
106
+ this.logger.info("Bundling Mastra done");
107
+ this.logger.info("Installing dependencies");
108
+ await this.installDependencies(outputDirectory);
109
+ this.logger.info("Done installing dependencies");
110
+ }
111
+ };
112
+
113
+ export { Bundler };