@mastra/deployer 0.0.0-afterToolExecute-20250414225911

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 (58) hide show
  1. package/LICENSE.md +46 -0
  2. package/README.md +159 -0
  3. package/dist/_tsup-dts-rollup.d.cts +479 -0
  4. package/dist/_tsup-dts-rollup.d.ts +479 -0
  5. package/dist/build/analyze.cjs +10 -0
  6. package/dist/build/analyze.d.cts +1 -0
  7. package/dist/build/analyze.d.ts +1 -0
  8. package/dist/build/analyze.js +1 -0
  9. package/dist/build/bundler.cjs +14 -0
  10. package/dist/build/bundler.d.cts +2 -0
  11. package/dist/build/bundler.d.ts +2 -0
  12. package/dist/build/bundler.js +1 -0
  13. package/dist/build/index.cjs +47 -0
  14. package/dist/build/index.d.cts +9 -0
  15. package/dist/build/index.d.ts +9 -0
  16. package/dist/build/index.js +6 -0
  17. package/dist/bundler/index.cjs +10 -0
  18. package/dist/bundler/index.d.cts +1 -0
  19. package/dist/bundler/index.d.ts +1 -0
  20. package/dist/bundler/index.js +1 -0
  21. package/dist/chunk-2ZPQX6BX.cjs +254 -0
  22. package/dist/chunk-4AYFLP6G.js +227 -0
  23. package/dist/chunk-54KOF3NB.cjs +137 -0
  24. package/dist/chunk-AE4CVAPK.cjs +151 -0
  25. package/dist/chunk-BDTZS3JM.js +299 -0
  26. package/dist/chunk-DYQ225MJ.js +115 -0
  27. package/dist/chunk-I3UVE6EH.cjs +161 -0
  28. package/dist/chunk-IKPL4RGG.js +140 -0
  29. package/dist/chunk-JDY6E7BT.cjs +152 -0
  30. package/dist/chunk-MYE33AKL.cjs +195 -0
  31. package/dist/chunk-NCROGJGB.cjs +142 -0
  32. package/dist/chunk-P5SATU7G.cjs +310 -0
  33. package/dist/chunk-SQQUYWPS.js +144 -0
  34. package/dist/chunk-WB3T6NKI.js +133 -0
  35. package/dist/chunk-WVBUOQT6.js +111 -0
  36. package/dist/chunk-YQB677IB.js +183 -0
  37. package/dist/index.cjs +191 -0
  38. package/dist/index.d.cts +6 -0
  39. package/dist/index.d.ts +6 -0
  40. package/dist/index.js +151 -0
  41. package/dist/server/index.cjs +3860 -0
  42. package/dist/server/index.d.cts +2 -0
  43. package/dist/server/index.d.ts +2 -0
  44. package/dist/server/index.js +3853 -0
  45. package/dist/services/index.cjs +19 -0
  46. package/dist/services/index.d.cts +3 -0
  47. package/dist/services/index.d.ts +3 -0
  48. package/dist/services/index.js +2 -0
  49. package/dist/templates/instrumentation-template.js +89 -0
  50. package/dist/validator/custom-resolver.cjs +52 -0
  51. package/dist/validator/custom-resolver.d.cts +1 -0
  52. package/dist/validator/custom-resolver.d.ts +1 -0
  53. package/dist/validator/custom-resolver.js +50 -0
  54. package/dist/validator/loader.cjs +7 -0
  55. package/dist/validator/loader.d.cts +1 -0
  56. package/dist/validator/loader.d.ts +1 -0
  57. package/dist/validator/loader.js +4 -0
  58. package/package.json +138 -0
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ var fs2 = require('fs');
4
+ var path = require('path');
5
+ var url = require('url');
6
+ var fsExtra = require('fs-extra/esm');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
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
+
29
+ var fs2__namespace = /*#__PURE__*/_interopNamespace(fs2);
30
+ var path__default = /*#__PURE__*/_interopDefault(path);
31
+ var fsExtra__default = /*#__PURE__*/_interopDefault(fsExtra);
32
+
33
+ // src/services/env.ts
34
+ var EnvService = class {
35
+ };
36
+ var FileEnvService = class extends EnvService {
37
+ filePath;
38
+ constructor(filePath) {
39
+ super();
40
+ this.filePath = filePath;
41
+ }
42
+ readFile(filePath) {
43
+ return new Promise((resolve, reject) => {
44
+ fs2__namespace.readFile(filePath, "utf8", (err, data) => {
45
+ if (err) reject(err);
46
+ else resolve(data);
47
+ });
48
+ });
49
+ }
50
+ writeFile({ filePath, data }) {
51
+ return new Promise((resolve, reject) => {
52
+ fs2__namespace.writeFile(filePath, data, "utf8", (err) => {
53
+ if (err) reject(err);
54
+ else resolve();
55
+ });
56
+ });
57
+ }
58
+ async updateEnvData({
59
+ key,
60
+ value,
61
+ filePath = this.filePath,
62
+ data
63
+ }) {
64
+ const regex = new RegExp(`^${key}=.*$`, "m");
65
+ if (data.match(regex)) {
66
+ data = data.replace(regex, `${key}=${value}`);
67
+ } else {
68
+ data += `
69
+ ${key}=${value}`;
70
+ }
71
+ await this.writeFile({ filePath, data });
72
+ console.log(`${key} set to ${value} in ENV file.`);
73
+ return data;
74
+ }
75
+ async getEnvValue(key) {
76
+ try {
77
+ const data = await this.readFile(this.filePath);
78
+ const regex = new RegExp(`^${key}=(.*)$`, "m");
79
+ const match = data.match(regex);
80
+ return match?.[1] || null;
81
+ } catch (err) {
82
+ console.error(`Error reading ENV value: ${err}`);
83
+ return null;
84
+ }
85
+ }
86
+ async setEnvValue(key, value) {
87
+ try {
88
+ const data = await this.readFile(this.filePath);
89
+ await this.updateEnvData({ key, value, data });
90
+ } catch (err) {
91
+ console.error(`Error writing ENV value: ${err}`);
92
+ }
93
+ }
94
+ };
95
+ var FileService = class {
96
+ /**
97
+ *
98
+ * @param inputFile the file in the starter files directory to copy
99
+ * @param outputFilePath the destination path
100
+ * @param replaceIfExists flag to replace if it exists
101
+ * @returns
102
+ */
103
+ async copyStarterFile(inputFile, outputFilePath, replaceIfExists) {
104
+ const __filename = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-NCROGJGB.cjs', document.baseURI).href)));
105
+ const __dirname = path__default.default.dirname(__filename);
106
+ const filePath = path__default.default.resolve(__dirname, "..", "starter-files", inputFile);
107
+ const fileString = fs2__namespace.default.readFileSync(filePath, "utf8");
108
+ if (fs2__namespace.default.existsSync(outputFilePath) && !replaceIfExists) {
109
+ console.log(`${outputFilePath} already exists`);
110
+ return false;
111
+ }
112
+ await fsExtra__default.default.outputFile(outputFilePath, fileString);
113
+ return true;
114
+ }
115
+ async setupEnvFile({ dbUrl }) {
116
+ const envPath = path__default.default.join(process.cwd(), ".env.development");
117
+ await fsExtra__default.default.ensureFile(envPath);
118
+ const fileEnvService = new FileEnvService(envPath);
119
+ await fileEnvService.setEnvValue("DB_URL", dbUrl);
120
+ }
121
+ getFirstExistingFile(files) {
122
+ for (const f of files) {
123
+ if (fs2__namespace.default.existsSync(f)) {
124
+ return f;
125
+ }
126
+ }
127
+ throw new Error("Missing required file, checked the following paths: " + files.join(", "));
128
+ }
129
+ replaceValuesInFile({
130
+ filePath,
131
+ replacements
132
+ }) {
133
+ let fileContent = fs2__namespace.default.readFileSync(filePath, "utf8");
134
+ replacements.forEach(({ search, replace }) => {
135
+ fileContent = fileContent.replaceAll(search, replace);
136
+ });
137
+ fs2__namespace.default.writeFileSync(filePath, fileContent);
138
+ }
139
+ };
140
+
141
+ exports.EnvService = EnvService;
142
+ exports.FileService = FileService;
@@ -0,0 +1,310 @@
1
+ 'use strict';
2
+
3
+ var chunk54KOF3NB_cjs = require('./chunk-54KOF3NB.cjs');
4
+ var commonjs = require('@rollup/plugin-commonjs');
5
+ var json = require('@rollup/plugin-json');
6
+ var nodeResolve = require('@rollup/plugin-node-resolve');
7
+ var virtual = require('@rollup/plugin-virtual');
8
+ var fs = require('fs');
9
+ var url = require('url');
10
+ var rollup = require('rollup');
11
+ var esbuild = require('rollup-plugin-esbuild');
12
+ var module$1 = require('module');
13
+ var path = require('path');
14
+ var child_process = require('child_process');
15
+ var promises = require('fs/promises');
16
+
17
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
+
19
+ var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
20
+ var json__default = /*#__PURE__*/_interopDefault(json);
21
+ var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve);
22
+ var virtual__default = /*#__PURE__*/_interopDefault(virtual);
23
+ var esbuild__default = /*#__PURE__*/_interopDefault(esbuild);
24
+
25
+ function isNodeBuiltin(dep) {
26
+ const [pkg] = dep.split("/");
27
+ return dep.startsWith("node:") || module$1.builtinModules.includes(dep) || module$1.builtinModules.includes(pkg);
28
+ }
29
+ function aliasHono() {
30
+ return {
31
+ name: "hono-alias",
32
+ resolveId(id) {
33
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
34
+ return;
35
+ }
36
+ const path = undefined(id);
37
+ return url.fileURLToPath(path);
38
+ }
39
+ };
40
+ }
41
+ function spawn(command, args = [], options = {}) {
42
+ return new Promise((resolve, reject) => {
43
+ const childProcess = child_process.spawn(command, args, {
44
+ // stdio: 'inherit',
45
+ ...options
46
+ });
47
+ childProcess.on("error", (error) => {
48
+ reject(error);
49
+ });
50
+ let stderr = "";
51
+ childProcess.stderr?.on("data", (message) => {
52
+ stderr += message;
53
+ });
54
+ childProcess.on("close", (code) => {
55
+ if (code === 0) {
56
+ resolve();
57
+ } else {
58
+ reject(new Error(stderr));
59
+ }
60
+ });
61
+ });
62
+ }
63
+ function validate(file) {
64
+ return spawn(
65
+ "node",
66
+ [
67
+ "--import",
68
+ undefined("@mastra/deployer/loader"),
69
+ "--input-type=module",
70
+ "-e",
71
+ `import('file://${file.replaceAll("\\", "/")}')`
72
+ ],
73
+ {
74
+ cwd: path.dirname(file)
75
+ }
76
+ );
77
+ }
78
+ var globalExternals = ["pino", "pino-pretty", "@libsql/client", "pg", "libsql", "jsdom", "sqlite3"];
79
+ function findExternalImporter(module, external, allOutputs) {
80
+ const capturedFiles = /* @__PURE__ */ new Set();
81
+ for (const id of module.imports) {
82
+ if (id === external) {
83
+ return module;
84
+ } else {
85
+ if (id.endsWith(".mjs")) {
86
+ capturedFiles.add(id);
87
+ }
88
+ }
89
+ }
90
+ for (const file of capturedFiles) {
91
+ const nextModule = allOutputs.find((o) => o.fileName === file);
92
+ if (nextModule) {
93
+ const importer = findExternalImporter(nextModule, external, allOutputs);
94
+ if (importer) {
95
+ return importer;
96
+ }
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+ async function analyze(entry, mastraEntry, isVirtualFile, platform, logger) {
102
+ logger.info("Analyzing dependencies...");
103
+ let virtualPlugin = null;
104
+ if (isVirtualFile) {
105
+ virtualPlugin = virtual__default.default({
106
+ "#entry": entry
107
+ });
108
+ entry = "#entry";
109
+ }
110
+ const normalizedMastraEntry = mastraEntry.replaceAll("\\", "/");
111
+ const optimizerBundler = await rollup.rollup({
112
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
113
+ input: isVirtualFile ? "#entry" : entry,
114
+ treeshake: "smallest",
115
+ preserveSymlinks: true,
116
+ plugins: [
117
+ virtualPlugin,
118
+ chunk54KOF3NB_cjs.tsConfigPaths(),
119
+ {
120
+ name: "custom-alias-resolver",
121
+ resolveId(id) {
122
+ if (id === "#server") {
123
+ return url.fileURLToPath(undefined("@mastra/deployer/server")).replaceAll("\\", "/");
124
+ }
125
+ if (id === "#mastra") {
126
+ return normalizedMastraEntry;
127
+ }
128
+ if (id.startsWith("@mastra/server")) {
129
+ return url.fileURLToPath(undefined(id));
130
+ }
131
+ }
132
+ },
133
+ json__default.default(),
134
+ esbuild__default.default({
135
+ target: "node20",
136
+ platform,
137
+ minify: false
138
+ }),
139
+ commonjs__default.default({
140
+ strictRequires: "debug",
141
+ ignoreTryCatch: false,
142
+ transformMixedEsModules: true,
143
+ extensions: [".js", ".ts"]
144
+ }),
145
+ chunk54KOF3NB_cjs.removeDeployer(normalizedMastraEntry),
146
+ esbuild__default.default({
147
+ target: "node20",
148
+ platform,
149
+ minify: false
150
+ })
151
+ ].filter(Boolean)
152
+ });
153
+ const { output } = await optimizerBundler.generate({
154
+ format: "esm",
155
+ inlineDynamicImports: true
156
+ });
157
+ await optimizerBundler.close();
158
+ const depsToOptimize = new Map(Object.entries(output[0].importedBindings));
159
+ for (const dep of depsToOptimize.keys()) {
160
+ if (isNodeBuiltin(dep)) {
161
+ depsToOptimize.delete(dep);
162
+ }
163
+ }
164
+ return depsToOptimize;
165
+ }
166
+ async function bundleExternals(depsToOptimize, outputDir, logger) {
167
+ logger.info("Optimizing dependencies...");
168
+ logger.debug(
169
+ `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
170
+ );
171
+ const reverseVirtualReferenceMap = /* @__PURE__ */ new Map();
172
+ const virtualDependencies = /* @__PURE__ */ new Map();
173
+ for (const [dep, exports] of depsToOptimize.entries()) {
174
+ const name = dep.replaceAll("/", "-");
175
+ reverseVirtualReferenceMap.set(name, dep);
176
+ const virtualFile = [];
177
+ let exportStringBuilder = [];
178
+ for (const local of exports) {
179
+ if (local === "*") {
180
+ virtualFile.push(`export * from '${dep}';`);
181
+ } else if (local === "default") {
182
+ virtualFile.push(`export { default } from '${dep}';`);
183
+ } else {
184
+ exportStringBuilder.push(local);
185
+ }
186
+ }
187
+ if (exportStringBuilder.length > 0) {
188
+ virtualFile.push(`export { ${exportStringBuilder.join(", ")} } from '${dep}';`);
189
+ }
190
+ virtualDependencies.set(dep, {
191
+ name,
192
+ virtual: virtualFile.join("\n")
193
+ });
194
+ }
195
+ const bundler = await rollup.rollup({
196
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
197
+ input: Array.from(virtualDependencies.entries()).reduce(
198
+ (acc, [dep, virtualDep]) => {
199
+ acc[virtualDep.name] = `#virtual-${dep}`;
200
+ return acc;
201
+ },
202
+ {}
203
+ ),
204
+ // this dependency breaks the build, so we need to exclude it
205
+ // TODO actually fix this so we don't need to exclude it
206
+ external: globalExternals,
207
+ treeshake: "smallest",
208
+ plugins: [
209
+ virtual__default.default(
210
+ Array.from(virtualDependencies.entries()).reduce(
211
+ (acc, [dep, virtualDep]) => {
212
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
213
+ return acc;
214
+ },
215
+ {}
216
+ )
217
+ ),
218
+ commonjs__default.default({
219
+ strictRequires: "strict",
220
+ transformMixedEsModules: true,
221
+ ignoreTryCatch: false
222
+ }),
223
+ nodeResolve__default.default({
224
+ preferBuiltins: true,
225
+ exportConditions: ["node", "import", "require"],
226
+ mainFields: ["module", "main"]
227
+ }),
228
+ // hono is imported from deployer, so we need to resolve from here instead of the project root
229
+ aliasHono(),
230
+ json__default.default()
231
+ ].filter(Boolean)
232
+ });
233
+ const { output } = await bundler.write({
234
+ format: "esm",
235
+ dir: outputDir,
236
+ entryFileNames: "[name].mjs",
237
+ chunkFileNames: "[name].mjs",
238
+ hoistTransitiveImports: false
239
+ });
240
+ const moduleResolveMap = {};
241
+ const filteredChunks = output.filter((o) => o.type === "chunk");
242
+ for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
243
+ for (const external of globalExternals) {
244
+ const importer = findExternalImporter(o, external, filteredChunks);
245
+ if (importer) {
246
+ const fullPath = path.join(outputDir, importer.fileName);
247
+ moduleResolveMap[fullPath] = moduleResolveMap[fullPath] || {};
248
+ if (importer.moduleIds.length) {
249
+ moduleResolveMap[fullPath][external] = importer.moduleIds[importer.moduleIds.length - 1]?.startsWith(
250
+ "\0virtual:#virtual"
251
+ ) ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1];
252
+ }
253
+ }
254
+ }
255
+ }
256
+ await promises.writeFile(path.join(outputDir, "module-resolve-map.json"), JSON.stringify(moduleResolveMap, null, 2));
257
+ await bundler.close();
258
+ return { output, reverseVirtualReferenceMap, usedExternals: moduleResolveMap };
259
+ }
260
+ async function validateOutput({
261
+ output,
262
+ reverseVirtualReferenceMap,
263
+ usedExternals,
264
+ outputDir
265
+ }, logger) {
266
+ const result = {
267
+ invalidChunks: /* @__PURE__ */ new Set(),
268
+ dependencies: /* @__PURE__ */ new Map(),
269
+ externalDependencies: /* @__PURE__ */ new Set()
270
+ };
271
+ for (const deps of Object.values(usedExternals)) {
272
+ for (const dep of Object.keys(deps)) {
273
+ result.externalDependencies.add(dep);
274
+ }
275
+ }
276
+ for (const file of output) {
277
+ if (file.type === "asset") {
278
+ continue;
279
+ }
280
+ try {
281
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
282
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
283
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
284
+ }
285
+ if (!file.isDynamicEntry && file.isEntry) {
286
+ await validate(path.join(outputDir, file.fileName));
287
+ }
288
+ } catch (err) {
289
+ result.invalidChunks.add(file.fileName);
290
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
291
+ result.externalDependencies.add(reverseVirtualReferenceMap.get(file.name));
292
+ }
293
+ }
294
+ }
295
+ return result;
296
+ }
297
+ async function analyzeBundle(entry, mastraEntry, outputDir, platform, logger) {
298
+ const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry);
299
+ const depsToOptimize = await analyze(entry, mastraEntry, isVirtualFile, platform, logger);
300
+ const { output, reverseVirtualReferenceMap, usedExternals } = await bundleExternals(
301
+ depsToOptimize,
302
+ outputDir,
303
+ logger
304
+ );
305
+ const result = await validateOutput({ output, reverseVirtualReferenceMap, usedExternals, outputDir }, logger);
306
+ return result;
307
+ }
308
+
309
+ exports.aliasHono = aliasHono;
310
+ exports.analyzeBundle = analyzeBundle;
@@ -0,0 +1,144 @@
1
+ import { writeTelemetryConfig } from './chunk-4AYFLP6G.js';
2
+ import { analyzeBundle } from './chunk-BDTZS3JM.js';
3
+ import { createBundler, getInputOptions } from './chunk-IKPL4RGG.js';
4
+ import { DepsService } from './chunk-YQB677IB.js';
5
+ import { existsSync } from 'node:fs';
6
+ import { writeFile, stat } from 'node:fs/promises';
7
+ import { join, dirname } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { MastraBundler } from '@mastra/core/bundler';
10
+ import virtual from '@rollup/plugin-virtual';
11
+ import { emptyDir, ensureDir, copy, readJSON } from 'fs-extra/esm';
12
+ import resolveFrom from 'resolve-from';
13
+
14
+ var Bundler = class extends MastraBundler {
15
+ analyzeOutputDir = ".build";
16
+ outputDir = "output";
17
+ constructor(name, component = "BUNDLER") {
18
+ super({ name, component });
19
+ }
20
+ async prepare(outputDirectory) {
21
+ await emptyDir(outputDirectory);
22
+ await ensureDir(join(outputDirectory, this.analyzeOutputDir));
23
+ await ensureDir(join(outputDirectory, this.outputDir));
24
+ }
25
+ async writeInstrumentationFile(outputDirectory) {
26
+ const instrumentationFile = join(outputDirectory, "instrumentation.mjs");
27
+ const __dirname = dirname(fileURLToPath(import.meta.url));
28
+ await copy(join(__dirname, "templates", "instrumentation-template.js"), instrumentationFile);
29
+ }
30
+ async writePackageJson(outputDirectory, dependencies) {
31
+ this.logger.debug(`Writing project's package.json`);
32
+ await ensureDir(outputDirectory);
33
+ const pkgPath = join(outputDirectory, "package.json");
34
+ const dependenciesMap = /* @__PURE__ */ new Map();
35
+ for (const [key, value] of dependencies.entries()) {
36
+ if (key.startsWith("@")) {
37
+ const pkgChunks = key.split("/");
38
+ dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);
39
+ continue;
40
+ }
41
+ dependenciesMap.set(key, value);
42
+ }
43
+ dependenciesMap.set("@opentelemetry/instrumentation", "latest");
44
+ await writeFile(
45
+ pkgPath,
46
+ JSON.stringify(
47
+ {
48
+ name: "server",
49
+ version: "1.0.0",
50
+ description: "",
51
+ type: "module",
52
+ main: "index.mjs",
53
+ scripts: {
54
+ start: "node ./index.mjs"
55
+ },
56
+ author: "Mastra",
57
+ license: "ISC",
58
+ dependencies: Object.fromEntries(dependenciesMap.entries())
59
+ },
60
+ null,
61
+ 2
62
+ )
63
+ );
64
+ }
65
+ createBundler(inputOptions, outputOptions) {
66
+ return createBundler(inputOptions, outputOptions);
67
+ }
68
+ async analyze(entry, mastraFile, outputDirectory) {
69
+ return await analyzeBundle(entry, mastraFile, join(outputDirectory, this.analyzeOutputDir), "node", this.logger);
70
+ }
71
+ async installDependencies(outputDirectory, rootDir = process.cwd()) {
72
+ const deps = new DepsService(rootDir);
73
+ deps.__setLogger(this.logger);
74
+ await deps.install({ dir: join(outputDirectory, this.outputDir) });
75
+ }
76
+ async copyPublic(mastraDir, outputDirectory) {
77
+ const publicDir = join(mastraDir, "public");
78
+ try {
79
+ await stat(publicDir);
80
+ } catch {
81
+ return;
82
+ }
83
+ await copy(publicDir, join(outputDirectory, this.outputDir));
84
+ }
85
+ async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo) {
86
+ const inputOptions = await getInputOptions(mastraEntryFile, analyzedBundleInfo, "node");
87
+ const isVirtual = serverFile.includes("\n") || existsSync(serverFile);
88
+ if (isVirtual) {
89
+ inputOptions.input = { index: "#entry" };
90
+ if (Array.isArray(inputOptions.plugins)) {
91
+ inputOptions.plugins.unshift(virtual({ "#entry": serverFile }));
92
+ } else {
93
+ inputOptions.plugins = [virtual({ "#entry": serverFile })];
94
+ }
95
+ } else {
96
+ inputOptions.input = { index: serverFile };
97
+ }
98
+ return inputOptions;
99
+ }
100
+ async _bundle(serverFile, mastraEntryFile, outputDirectory, bundleLocation = join(outputDirectory, this.outputDir)) {
101
+ this.logger.info("Start bundling Mastra");
102
+ const analyzedBundleInfo = await analyzeBundle(
103
+ serverFile,
104
+ mastraEntryFile,
105
+ join(outputDirectory, this.analyzeOutputDir),
106
+ "node",
107
+ this.logger
108
+ );
109
+ await writeTelemetryConfig(mastraEntryFile, join(outputDirectory, this.outputDir));
110
+ const dependenciesToInstall = /* @__PURE__ */ new Map();
111
+ for (const dep of analyzedBundleInfo.externalDependencies) {
112
+ try {
113
+ const pkgPath = resolveFrom(mastraEntryFile, `${dep}/package.json`);
114
+ const pkg = await readJSON(pkgPath);
115
+ dependenciesToInstall.set(dep, pkg.version);
116
+ } catch {
117
+ dependenciesToInstall.set(dep, "latest");
118
+ }
119
+ }
120
+ if (analyzedBundleInfo.externalDependencies.has("@mastra/memory") || analyzedBundleInfo.dependencies.has("@mastra/memory")) {
121
+ dependenciesToInstall.set("fastembed", "latest");
122
+ }
123
+ await this.writePackageJson(join(outputDirectory, this.outputDir), dependenciesToInstall);
124
+ await this.writeInstrumentationFile(join(outputDirectory, this.outputDir));
125
+ this.logger.info("Bundling Mastra application");
126
+ const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo);
127
+ const bundler = await this.createBundler(inputOptions, {
128
+ dir: bundleLocation,
129
+ manualChunks: {
130
+ mastra: ["#mastra"]
131
+ }
132
+ });
133
+ await bundler.write();
134
+ this.logger.info("Bundling Mastra done");
135
+ this.logger.info("Copying public files");
136
+ await this.copyPublic(dirname(mastraEntryFile), outputDirectory);
137
+ this.logger.info("Done copying public files");
138
+ this.logger.info("Installing dependencies");
139
+ await this.installDependencies(outputDirectory);
140
+ this.logger.info("Done installing dependencies");
141
+ }
142
+ };
143
+
144
+ export { Bundler };