@mastra/deployer 0.10.13 → 0.10.15-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/_tsup-dts-rollup.d.cts +844 -0
  2. package/dist/_tsup-dts-rollup.d.ts +844 -0
  3. package/dist/build/analyze.cjs +10 -0
  4. package/dist/build/analyze.d.cts +1 -0
  5. package/dist/build/analyze.d.ts +1 -0
  6. package/dist/build/analyze.js +1 -0
  7. package/dist/build/bundler.cjs +14 -0
  8. package/dist/build/bundler.d.cts +2 -0
  9. package/dist/build/bundler.d.ts +2 -0
  10. package/dist/build/bundler.js +1 -0
  11. package/dist/build/index.cjs +50 -0
  12. package/dist/build/index.d.cts +10 -0
  13. package/dist/build/index.d.ts +10 -0
  14. package/dist/build/index.js +5 -0
  15. package/dist/bundler/index.cjs +10 -0
  16. package/dist/bundler/index.d.cts +1 -0
  17. package/dist/bundler/index.d.ts +1 -0
  18. package/dist/bundler/index.js +1 -0
  19. package/dist/chunk-54KOF3NB.cjs +137 -0
  20. package/dist/chunk-6QMONK4A.cjs +2 -0
  21. package/dist/chunk-C4JT7CIH.js +1 -0
  22. package/dist/chunk-D2DCFCLH.cjs +157 -0
  23. package/dist/chunk-D6736SJL.js +209 -0
  24. package/dist/chunk-ENT5RDOI.js +99 -0
  25. package/dist/chunk-FK2WUSEN.cjs +238 -0
  26. package/dist/chunk-GPD54HBC.js +380 -0
  27. package/dist/chunk-HJGC75ZR.js +490 -0
  28. package/dist/chunk-KCP5ITLV.cjs +412 -0
  29. package/dist/chunk-M2VZQFTW.cjs +125 -0
  30. package/dist/chunk-TIC2KT3M.js +146 -0
  31. package/dist/chunk-UYQZMNZL.js +572 -0
  32. package/dist/chunk-XKH6F4NE.cjs +604 -0
  33. package/dist/chunk-YFMAWUII.cjs +502 -0
  34. package/dist/chunk-Z544XXXK.js +111 -0
  35. package/dist/index.cjs +194 -0
  36. package/dist/index.d.cts +8 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +153 -0
  39. package/dist/server/index.cjs +8446 -0
  40. package/dist/server/index.d.cts +2 -0
  41. package/dist/server/index.d.ts +2 -0
  42. package/dist/server/index.js +8438 -0
  43. package/dist/services/index.cjs +18 -0
  44. package/dist/services/index.d.cts +3 -0
  45. package/dist/services/index.d.ts +3 -0
  46. package/dist/services/index.js +1 -0
  47. package/dist/templates/instrumentation-template.js +137 -0
  48. package/dist/validator/custom-resolver.cjs +52 -0
  49. package/dist/validator/custom-resolver.d.cts +1 -0
  50. package/dist/validator/custom-resolver.d.ts +1 -0
  51. package/dist/validator/custom-resolver.js +50 -0
  52. package/dist/validator/loader.cjs +7 -0
  53. package/dist/validator/loader.d.cts +1 -0
  54. package/dist/validator/loader.d.ts +1 -0
  55. package/dist/validator/loader.js +4 -0
  56. package/package.json +5 -5
@@ -0,0 +1,502 @@
1
+ 'use strict';
2
+
3
+ var chunkM2VZQFTW_cjs = require('./chunk-M2VZQFTW.cjs');
4
+ var chunkXKH6F4NE_cjs = require('./chunk-XKH6F4NE.cjs');
5
+ var chunkD2DCFCLH_cjs = require('./chunk-D2DCFCLH.cjs');
6
+ var chunkKCP5ITLV_cjs = require('./chunk-KCP5ITLV.cjs');
7
+ var fs = require('fs');
8
+ var promises = require('fs/promises');
9
+ var path = require('path');
10
+ var url = require('url');
11
+ var bundler = require('@mastra/core/bundler');
12
+ var error = require('@mastra/core/error');
13
+ var virtual = require('@rollup/plugin-virtual');
14
+ var fsExtra = require('fs-extra/esm');
15
+ var globby = require('globby');
16
+ var resolveFrom = require('resolve-from');
17
+ var rollup = require('rollup');
18
+ var esbuild = require('rollup-plugin-esbuild');
19
+ var commonjs = require('@rollup/plugin-commonjs');
20
+ var slugify = require('@sindresorhus/slugify');
21
+ var findWorkspaces = require('find-workspaces');
22
+ var fsExtra$1 = require('fs-extra');
23
+
24
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
25
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
26
+
27
+ var virtual__default = /*#__PURE__*/_interopDefault(virtual);
28
+ var fsExtra__default = /*#__PURE__*/_interopDefault(fsExtra);
29
+ var resolveFrom__default = /*#__PURE__*/_interopDefault(resolveFrom);
30
+ var esbuild__default = /*#__PURE__*/_interopDefault(esbuild);
31
+ var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
32
+ var slugify__default = /*#__PURE__*/_interopDefault(slugify);
33
+
34
+ function getCustomInstrumentationBundler(entryFile, result) {
35
+ return rollup.rollup({
36
+ logLevel: "silent",
37
+ input: {
38
+ instrumentation: entryFile
39
+ },
40
+ treeshake: false,
41
+ plugins: [
42
+ // transpile typescript to something we understand
43
+ esbuild__default.default({
44
+ target: "node20",
45
+ platform: "node",
46
+ minify: false
47
+ }),
48
+ commonjs__default.default({
49
+ extensions: [".js", ".ts"],
50
+ strictRequires: "strict",
51
+ transformMixedEsModules: true,
52
+ ignoreTryCatch: false
53
+ })
54
+ ]
55
+ });
56
+ }
57
+ async function writeCustomInstrumentation(entryFile, outputDir) {
58
+ const result = {
59
+ hasCustomConfig: false
60
+ };
61
+ const bundle = await getCustomInstrumentationBundler(entryFile);
62
+ const { output } = await bundle.write({
63
+ dir: outputDir,
64
+ format: "es",
65
+ entryFileNames: "[name].mjs"
66
+ });
67
+ const externals = output[0].imports.filter((x) => !x.startsWith("./"));
68
+ return { ...result, externalDependencies: externals };
69
+ }
70
+ var createWorkspacePackageMap = async () => {
71
+ const workspaces = await findWorkspaces.findWorkspaces();
72
+ const workspaceMap = new Map(
73
+ workspaces?.map((workspace) => [
74
+ workspace.package.name,
75
+ {
76
+ location: workspace.location,
77
+ dependencies: workspace.package.dependencies,
78
+ version: workspace.package.version
79
+ }
80
+ ]) ?? []
81
+ );
82
+ return workspaceMap;
83
+ };
84
+ var collectTransitiveWorkspaceDependencies = ({
85
+ workspaceMap,
86
+ initialDependencies,
87
+ logger
88
+ }) => {
89
+ const usedWorkspacePackages = /* @__PURE__ */ new Set();
90
+ const queue = Array.from(initialDependencies);
91
+ const resolutions = {};
92
+ while (queue.length > 0) {
93
+ const len = queue.length;
94
+ for (let i = 0; i < len; i += 1) {
95
+ const pkgName = queue.shift();
96
+ if (!pkgName || usedWorkspacePackages.has(pkgName)) {
97
+ continue;
98
+ }
99
+ const dep = workspaceMap.get(pkgName);
100
+ if (!dep) continue;
101
+ const root = findWorkspaces.findWorkspacesRoot();
102
+ if (!root) {
103
+ throw new Error("Could not find workspace root");
104
+ }
105
+ const depsService = new chunkKCP5ITLV_cjs.DepsService(root.location);
106
+ depsService.__setLogger(logger);
107
+ const sanitizedName = slugify__default.default(pkgName);
108
+ const tgzPath = depsService.getWorkspaceDependencyPath({
109
+ pkgName: sanitizedName,
110
+ version: dep.version
111
+ });
112
+ resolutions[pkgName] = tgzPath;
113
+ usedWorkspacePackages.add(pkgName);
114
+ for (const [depName, _depVersion] of Object.entries(dep?.dependencies ?? {})) {
115
+ if (!usedWorkspacePackages.has(depName) && workspaceMap.has(depName)) {
116
+ queue.push(depName);
117
+ }
118
+ }
119
+ }
120
+ }
121
+ return { resolutions, usedWorkspacePackages };
122
+ };
123
+ var packWorkspaceDependencies = async ({
124
+ workspaceMap,
125
+ usedWorkspacePackages,
126
+ bundleOutputDir,
127
+ logger
128
+ }) => {
129
+ const root = findWorkspaces.findWorkspacesRoot();
130
+ if (!root) {
131
+ throw new Error("Could not find workspace root");
132
+ }
133
+ const depsService = new chunkKCP5ITLV_cjs.DepsService(root.location);
134
+ depsService.__setLogger(logger);
135
+ if (usedWorkspacePackages.size > 0) {
136
+ const workspaceDirPath = path.join(bundleOutputDir, "workspace-module");
137
+ await fsExtra$1.ensureDir(workspaceDirPath);
138
+ logger.info(`Packaging ${usedWorkspacePackages.size} workspace dependencies...`);
139
+ const batchSize = 5;
140
+ const packages = Array.from(usedWorkspacePackages.values());
141
+ for (let i = 0; i < packages.length; i += batchSize) {
142
+ const batch = packages.slice(i, i + batchSize);
143
+ logger.info(
144
+ `Packaging batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(packages.length / batchSize)}: ${batch.join(", ")}`
145
+ );
146
+ await Promise.all(
147
+ batch.map(async (pkgName) => {
148
+ const dep = workspaceMap.get(pkgName);
149
+ if (!dep) return;
150
+ await depsService.pack({ dir: dep.location, destination: workspaceDirPath });
151
+ })
152
+ );
153
+ }
154
+ logger.info(`Successfully packaged ${usedWorkspacePackages.size} workspace dependencies`);
155
+ }
156
+ };
157
+
158
+ // src/bundler/index.ts
159
+ var Bundler = class extends bundler.MastraBundler {
160
+ analyzeOutputDir = ".build";
161
+ outputDir = "output";
162
+ constructor(name, component = "BUNDLER") {
163
+ super({ name, component });
164
+ }
165
+ async prepare(outputDirectory) {
166
+ await fsExtra.emptyDir(outputDirectory);
167
+ await fsExtra.ensureDir(path.join(outputDirectory, this.analyzeOutputDir));
168
+ await fsExtra.ensureDir(path.join(outputDirectory, this.outputDir));
169
+ }
170
+ async writeInstrumentationFile(outputDirectory, customInstrumentationFile) {
171
+ const instrumentationFile = path.join(outputDirectory, "instrumentation.mjs");
172
+ const __dirname = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-YFMAWUII.cjs', document.baseURI).href))));
173
+ if (customInstrumentationFile) {
174
+ await fsExtra.copy(customInstrumentationFile, instrumentationFile);
175
+ } else {
176
+ await fsExtra.copy(path.join(__dirname, "templates", "instrumentation-template.js"), instrumentationFile);
177
+ }
178
+ }
179
+ async writePackageJson(outputDirectory, dependencies, resolutions) {
180
+ this.logger.debug(`Writing project's package.json`);
181
+ await fsExtra.ensureDir(outputDirectory);
182
+ const pkgPath = path.join(outputDirectory, "package.json");
183
+ const dependenciesMap = /* @__PURE__ */ new Map();
184
+ for (const [key, value] of dependencies.entries()) {
185
+ if (key.startsWith("@")) {
186
+ const pkgChunks = key.split("/");
187
+ dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);
188
+ } else {
189
+ const pkgName = key.split("/")[0] || key;
190
+ dependenciesMap.set(pkgName, value);
191
+ }
192
+ }
193
+ dependenciesMap.set("@opentelemetry/core", "^2.0.1");
194
+ dependenciesMap.set("@opentelemetry/auto-instrumentations-node", "^0.59.0");
195
+ dependenciesMap.set("@opentelemetry/exporter-trace-otlp-grpc", "^0.201.0");
196
+ dependenciesMap.set("@opentelemetry/exporter-trace-otlp-http", "^0.201.0");
197
+ dependenciesMap.set("@opentelemetry/resources", "^2.0.1");
198
+ dependenciesMap.set("@opentelemetry/sdk-node", "^0.201.0");
199
+ dependenciesMap.set("@opentelemetry/sdk-trace-base", "^2.0.1");
200
+ dependenciesMap.set("@opentelemetry/semantic-conventions", "^1.33.0");
201
+ dependenciesMap.set("@opentelemetry/instrumentation", "^0.202.0");
202
+ await promises.writeFile(
203
+ pkgPath,
204
+ JSON.stringify(
205
+ {
206
+ name: "server",
207
+ version: "1.0.0",
208
+ description: "",
209
+ type: "module",
210
+ main: "index.mjs",
211
+ scripts: {
212
+ start: "node --import=./instrumentation.mjs --import=@opentelemetry/instrumentation/hook.mjs ./index.mjs"
213
+ },
214
+ author: "Mastra",
215
+ license: "ISC",
216
+ dependencies: Object.fromEntries(dependenciesMap.entries()),
217
+ ...Object.keys(resolutions ?? {}).length > 0 && { resolutions },
218
+ pnpm: {
219
+ neverBuiltDependencies: []
220
+ }
221
+ },
222
+ null,
223
+ 2
224
+ )
225
+ );
226
+ }
227
+ createBundler(inputOptions, outputOptions) {
228
+ return chunkD2DCFCLH_cjs.createBundler(inputOptions, outputOptions);
229
+ }
230
+ async analyze(entry, mastraFile, outputDirectory) {
231
+ return await chunkXKH6F4NE_cjs.analyzeBundle(
232
+ [].concat(entry),
233
+ mastraFile,
234
+ path.join(outputDirectory, this.analyzeOutputDir),
235
+ "node",
236
+ this.logger
237
+ );
238
+ }
239
+ async installDependencies(outputDirectory, rootDir = process.cwd()) {
240
+ const deps = new chunkKCP5ITLV_cjs.DepsService(rootDir);
241
+ deps.__setLogger(this.logger);
242
+ await deps.install({ dir: path.join(outputDirectory, this.outputDir) });
243
+ }
244
+ async copyPublic(mastraDir, outputDirectory) {
245
+ const publicDir = path.join(mastraDir, "public");
246
+ try {
247
+ await promises.stat(publicDir);
248
+ } catch {
249
+ return;
250
+ }
251
+ await fsExtra.copy(publicDir, path.join(outputDirectory, this.outputDir));
252
+ }
253
+ async copyDOTNPMRC({
254
+ rootDir = process.cwd(),
255
+ outputDirectory
256
+ }) {
257
+ const sourceDotNpmRcPath = path.join(rootDir, ".npmrc");
258
+ const targetDotNpmRcPath = path.join(outputDirectory, this.outputDir, ".npmrc");
259
+ try {
260
+ await promises.stat(sourceDotNpmRcPath);
261
+ await fsExtra.copy(sourceDotNpmRcPath, targetDotNpmRcPath);
262
+ } catch {
263
+ return;
264
+ }
265
+ }
266
+ async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths) {
267
+ const inputOptions = await chunkD2DCFCLH_cjs.getInputOptions(mastraEntryFile, analyzedBundleInfo, "node", {
268
+ "process.env.NODE_ENV": JSON.stringify("production")
269
+ });
270
+ const isVirtual = serverFile.includes("\n") || fs.existsSync(serverFile);
271
+ const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
272
+ if (isVirtual) {
273
+ inputOptions.input = { index: "#entry", ...toolsInputOptions };
274
+ if (Array.isArray(inputOptions.plugins)) {
275
+ inputOptions.plugins.unshift(virtual__default.default({ "#entry": serverFile }));
276
+ } else {
277
+ inputOptions.plugins = [virtual__default.default({ "#entry": serverFile })];
278
+ }
279
+ } else {
280
+ inputOptions.input = { index: serverFile, ...toolsInputOptions };
281
+ }
282
+ return inputOptions;
283
+ }
284
+ async getToolsInputOptions(toolsPaths) {
285
+ const inputs = {};
286
+ for (const toolPath of toolsPaths) {
287
+ const expandedPaths = await globby.globby(toolPath, {});
288
+ for (const path$1 of expandedPaths) {
289
+ if (await fsExtra__default.default.pathExists(path$1)) {
290
+ const fileService = new chunkKCP5ITLV_cjs.FileService();
291
+ const entryFile = fileService.getFirstExistingFile([
292
+ path.join(path$1, "index.ts"),
293
+ path.join(path$1, "index.js"),
294
+ path$1
295
+ // if path itself is a file
296
+ ]);
297
+ if (!entryFile || (await promises.stat(entryFile)).isDirectory()) {
298
+ this.logger.warn(`No entry file found in ${path$1}, skipping...`);
299
+ continue;
300
+ }
301
+ const uniqueToolID = crypto.randomUUID();
302
+ inputs[`tools/${uniqueToolID}`] = entryFile;
303
+ } else {
304
+ this.logger.warn(`Tool path ${path$1} does not exist, skipping...`);
305
+ }
306
+ }
307
+ }
308
+ return inputs;
309
+ }
310
+ async _bundle(serverFile, mastraEntryFile, outputDirectory, toolsPaths = [], bundleLocation = path.join(outputDirectory, this.outputDir)) {
311
+ this.logger.info("Start bundling Mastra");
312
+ let analyzedBundleInfo;
313
+ try {
314
+ const resolvedToolsPaths = await this.getToolsInputOptions(toolsPaths);
315
+ analyzedBundleInfo = await chunkXKH6F4NE_cjs.analyzeBundle(
316
+ [serverFile, ...Object.values(resolvedToolsPaths)],
317
+ mastraEntryFile,
318
+ path.join(outputDirectory, this.analyzeOutputDir),
319
+ "node",
320
+ this.logger
321
+ );
322
+ } catch (error$1) {
323
+ const message = error$1 instanceof Error ? error$1.message : String(error$1);
324
+ throw new error.MastraError(
325
+ {
326
+ id: "DEPLOYER_BUNDLER_ANALYZE_FAILED",
327
+ text: `Failed to analyze Mastra application: ${message}`,
328
+ domain: error.ErrorDomain.DEPLOYER,
329
+ category: error.ErrorCategory.SYSTEM
330
+ },
331
+ error$1
332
+ );
333
+ }
334
+ let externalDependencies;
335
+ try {
336
+ const result = await chunkM2VZQFTW_cjs.writeTelemetryConfig(mastraEntryFile, path.join(outputDirectory, this.outputDir));
337
+ externalDependencies = result.externalDependencies;
338
+ } catch (error$1) {
339
+ const message = error$1 instanceof Error ? error$1.message : String(error$1);
340
+ throw new error.MastraError(
341
+ {
342
+ id: "DEPLOYER_BUNDLER_TELEMETRY_FAILED",
343
+ text: `Failed to write telemetry config: ${message}`,
344
+ domain: error.ErrorDomain.DEPLOYER,
345
+ category: error.ErrorCategory.SYSTEM
346
+ },
347
+ error$1
348
+ );
349
+ }
350
+ const mastraFolder = path.dirname(mastraEntryFile);
351
+ const fileService = new chunkKCP5ITLV_cjs.FileService();
352
+ const customInstrumentation = fileService.getFirstExistingFileOrUndefined([
353
+ path.join(mastraFolder, "instrumentation.js"),
354
+ path.join(mastraFolder, "instrumentation.ts"),
355
+ path.join(mastraFolder, "instrumentation.mjs")
356
+ ]);
357
+ try {
358
+ if (customInstrumentation) {
359
+ const result = await writeCustomInstrumentation(customInstrumentation, path.join(outputDirectory, this.outputDir));
360
+ externalDependencies = [...externalDependencies, ...result.externalDependencies];
361
+ await this.writeInstrumentationFile(path.join(outputDirectory, this.outputDir), customInstrumentation);
362
+ } else {
363
+ await this.writeInstrumentationFile(path.join(outputDirectory, this.outputDir));
364
+ }
365
+ } catch (error$1) {
366
+ const message = error$1 instanceof Error ? error$1.message : String(error$1);
367
+ throw new error.MastraError(
368
+ {
369
+ id: "DEPLOYER_BUNDLER_INSTRUMENTATION_FILE_FAILED",
370
+ text: `Failed to write instrumentation file: ${message}, ${customInstrumentation ? ` Found custom instrumentation file: ${customInstrumentation}` : ""}`,
371
+ domain: error.ErrorDomain.DEPLOYER,
372
+ category: error.ErrorCategory.SYSTEM
373
+ },
374
+ error$1
375
+ );
376
+ }
377
+ const dependenciesToInstall = /* @__PURE__ */ new Map();
378
+ for (const external of externalDependencies) {
379
+ dependenciesToInstall.set(external, "latest");
380
+ }
381
+ const workspaceMap = await createWorkspacePackageMap();
382
+ const workspaceDependencies = /* @__PURE__ */ new Set();
383
+ for (const dep of analyzedBundleInfo.externalDependencies) {
384
+ try {
385
+ const pkgPath = resolveFrom__default.default(mastraEntryFile, `${dep}/package.json`);
386
+ const pkg = await fsExtra.readJSON(pkgPath);
387
+ if (workspaceMap.has(pkg.name)) {
388
+ workspaceDependencies.add(pkg.name);
389
+ continue;
390
+ }
391
+ dependenciesToInstall.set(dep, pkg.version);
392
+ } catch {
393
+ dependenciesToInstall.set(dep, "latest");
394
+ }
395
+ }
396
+ let resolutions = {};
397
+ if (workspaceDependencies.size > 0) {
398
+ try {
399
+ const result = collectTransitiveWorkspaceDependencies({
400
+ workspaceMap,
401
+ initialDependencies: workspaceDependencies,
402
+ logger: this.logger
403
+ });
404
+ resolutions = result.resolutions;
405
+ Object.entries(resolutions).forEach(([pkgName, tgzPath]) => {
406
+ dependenciesToInstall.set(pkgName, tgzPath);
407
+ });
408
+ await packWorkspaceDependencies({
409
+ workspaceMap,
410
+ usedWorkspacePackages: result.usedWorkspacePackages,
411
+ bundleOutputDir: path.join(outputDirectory, this.outputDir),
412
+ logger: this.logger
413
+ });
414
+ } catch (error$1) {
415
+ throw new error.MastraError(
416
+ {
417
+ id: "DEPLOYER_BUNDLER_WORKSPACE_DEPS_FAILED",
418
+ text: `Failed to collect and pack workspace dependencies.`,
419
+ domain: error.ErrorDomain.DEPLOYER,
420
+ category: error.ErrorCategory.USER
421
+ },
422
+ error$1
423
+ );
424
+ }
425
+ }
426
+ try {
427
+ await this.writePackageJson(path.join(outputDirectory, this.outputDir), dependenciesToInstall, resolutions);
428
+ this.logger.info("Bundling Mastra application");
429
+ const inputOptions = await this.getBundlerOptions(
430
+ serverFile,
431
+ mastraEntryFile,
432
+ analyzedBundleInfo,
433
+ toolsPaths
434
+ );
435
+ const bundler = await this.createBundler(
436
+ {
437
+ ...inputOptions,
438
+ logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
439
+ onwarn: (warning) => {
440
+ if (warning.code === "CIRCULAR_DEPENDENCY") {
441
+ if (warning.ids?.[0]?.includes("node_modules")) {
442
+ return;
443
+ }
444
+ this.logger.warn(`Circular dependency found:
445
+ ${warning.message.replace("Circular dependency: ", "")}`);
446
+ }
447
+ }
448
+ },
449
+ {
450
+ dir: bundleLocation,
451
+ manualChunks: {
452
+ mastra: ["#mastra"]
453
+ }
454
+ }
455
+ );
456
+ await bundler.write();
457
+ const toolImports = [];
458
+ const toolsExports = [];
459
+ Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
460
+ const toolExport = `tool${index}`;
461
+ toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);
462
+ toolsExports.push(toolExport);
463
+ });
464
+ await promises.writeFile(
465
+ path.join(bundleLocation, "tools.mjs"),
466
+ `${toolImports.join("\n")}
467
+
468
+ export const tools = [${toolsExports.join(", ")}]`
469
+ );
470
+ this.logger.info("Bundling Mastra done");
471
+ this.logger.info("Copying public files");
472
+ await this.copyPublic(path.dirname(mastraEntryFile), outputDirectory);
473
+ this.logger.info("Done copying public files");
474
+ this.logger.info("Copying .npmrc file");
475
+ await this.copyDOTNPMRC({ outputDirectory });
476
+ this.logger.info("Done copying .npmrc file");
477
+ this.logger.info("Installing dependencies");
478
+ await this.installDependencies(outputDirectory);
479
+ this.logger.info("Done installing dependencies");
480
+ } catch (error$1) {
481
+ const message = error$1 instanceof Error ? error$1.message : String(error$1);
482
+ throw new error.MastraError(
483
+ {
484
+ id: "DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED",
485
+ text: `Failed during bundler bundle stage: ${message}`,
486
+ domain: error.ErrorDomain.DEPLOYER,
487
+ category: error.ErrorCategory.SYSTEM
488
+ },
489
+ error$1
490
+ );
491
+ }
492
+ }
493
+ async lint(_entryFile, _outputDirectory, toolsPaths) {
494
+ const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
495
+ const toolsLength = Object.keys(toolsInputOptions).length;
496
+ if (toolsLength > 0) {
497
+ this.logger.info(`Found ${toolsLength} ${toolsLength === 1 ? "tool" : "tools"}`);
498
+ }
499
+ }
500
+ };
501
+
502
+ exports.Bundler = Bundler;
@@ -0,0 +1,111 @@
1
+ import * as babel from '@babel/core';
2
+ import babel__default from '@babel/core';
3
+ import fs from 'fs';
4
+ import path, { normalize } from 'path';
5
+ import { createHandler } from 'typescript-paths';
6
+
7
+ // src/build/plugins/remove-deployer.ts
8
+ function removeDeployer() {
9
+ const t = babel__default.types;
10
+ return {
11
+ name: "remove-deployer",
12
+ visitor: {
13
+ NewExpression(path2, state) {
14
+ const varDeclaratorPath = path2.findParent((path3) => t.isVariableDeclarator(path3.node));
15
+ if (!varDeclaratorPath) {
16
+ return;
17
+ }
18
+ const parentNode = path2.parentPath.node;
19
+ if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
20
+ return;
21
+ }
22
+ if (!state.hasReplaced) {
23
+ state.hasReplaced = true;
24
+ const newMastraObj = t.cloneNode(path2.node);
25
+ if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.[0]) {
26
+ const deployer = newMastraObj.arguments[0].properties.find(
27
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
28
+ );
29
+ if (!deployer) {
30
+ return;
31
+ }
32
+ newMastraObj.arguments[0].properties = newMastraObj.arguments[0].properties.filter(
33
+ (prop) => prop !== deployer
34
+ );
35
+ if (t.isObjectProperty(deployer) && t.isIdentifier(deployer.value)) {
36
+ const deployerBinding = state.file.scope.getBinding(deployer.value.name);
37
+ if (deployerBinding) {
38
+ deployerBinding?.path?.parentPath?.remove();
39
+ }
40
+ }
41
+ path2.replaceWith(newMastraObj);
42
+ }
43
+ }
44
+ }
45
+ }
46
+ };
47
+ }
48
+
49
+ // src/build/plugins/remove-deployer.ts
50
+ function removeDeployer2(mastraEntry) {
51
+ return {
52
+ name: "remove-deployer",
53
+ transform(code, id) {
54
+ if (id !== mastraEntry) {
55
+ return;
56
+ }
57
+ return new Promise((resolve, reject) => {
58
+ babel.transform(
59
+ code,
60
+ {
61
+ babelrc: false,
62
+ configFile: false,
63
+ filename: id,
64
+ plugins: [removeDeployer]
65
+ },
66
+ (err, result) => {
67
+ if (err) {
68
+ return reject(err);
69
+ }
70
+ resolve({
71
+ code: result.code,
72
+ map: result.map
73
+ });
74
+ }
75
+ );
76
+ });
77
+ }
78
+ };
79
+ }
80
+ var PLUGIN_NAME = "tsconfig-paths";
81
+ function tsConfigPaths({ tsConfigPath, respectCoreModule } = {}) {
82
+ let handler;
83
+ return {
84
+ name: PLUGIN_NAME,
85
+ buildStart() {
86
+ handler = createHandler({
87
+ log: () => {
88
+ },
89
+ tsConfigPath,
90
+ respectCoreModule,
91
+ falllback: (moduleName) => fs.existsSync(moduleName)
92
+ });
93
+ return;
94
+ },
95
+ async resolveId(request, importer, options) {
96
+ if (!importer || request.startsWith("\0")) {
97
+ return null;
98
+ }
99
+ const moduleName = handler?.(request, normalize(importer));
100
+ if (!moduleName) {
101
+ return this.resolve(request, importer, { skipSelf: true, ...options });
102
+ }
103
+ if (!path.extname(moduleName)) {
104
+ return this.resolve(moduleName, importer, { skipSelf: true, ...options });
105
+ }
106
+ return moduleName;
107
+ }
108
+ };
109
+ }
110
+
111
+ export { removeDeployer2 as removeDeployer, tsConfigPaths };