@mastra/deployer 0.10.12-alpha.1 → 0.10.13

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/package.json +6 -6
  2. package/dist/_tsup-dts-rollup.d.cts +0 -836
  3. package/dist/_tsup-dts-rollup.d.ts +0 -836
  4. package/dist/build/analyze.cjs +0 -10
  5. package/dist/build/analyze.d.cts +0 -1
  6. package/dist/build/analyze.d.ts +0 -1
  7. package/dist/build/analyze.js +0 -1
  8. package/dist/build/bundler.cjs +0 -14
  9. package/dist/build/bundler.d.cts +0 -2
  10. package/dist/build/bundler.d.ts +0 -2
  11. package/dist/build/bundler.js +0 -1
  12. package/dist/build/index.cjs +0 -50
  13. package/dist/build/index.d.cts +0 -10
  14. package/dist/build/index.d.ts +0 -10
  15. package/dist/build/index.js +0 -5
  16. package/dist/bundler/index.cjs +0 -10
  17. package/dist/bundler/index.d.cts +0 -1
  18. package/dist/bundler/index.d.ts +0 -1
  19. package/dist/bundler/index.js +0 -1
  20. package/dist/chunk-2C7ENC5E.js +0 -474
  21. package/dist/chunk-54KOF3NB.cjs +0 -137
  22. package/dist/chunk-6QMONK4A.cjs +0 -2
  23. package/dist/chunk-C4JT7CIH.js +0 -1
  24. package/dist/chunk-D2DCFCLH.cjs +0 -157
  25. package/dist/chunk-D6736SJL.js +0 -209
  26. package/dist/chunk-ENT5RDOI.js +0 -99
  27. package/dist/chunk-FK2WUSEN.cjs +0 -238
  28. package/dist/chunk-GPD54HBC.js +0 -380
  29. package/dist/chunk-KCP5ITLV.cjs +0 -412
  30. package/dist/chunk-M2VZQFTW.cjs +0 -125
  31. package/dist/chunk-MKB7NDY3.cjs +0 -486
  32. package/dist/chunk-TIC2KT3M.js +0 -146
  33. package/dist/chunk-UYQZMNZL.js +0 -572
  34. package/dist/chunk-XKH6F4NE.cjs +0 -604
  35. package/dist/chunk-Z544XXXK.js +0 -111
  36. package/dist/index.cjs +0 -194
  37. package/dist/index.d.cts +0 -8
  38. package/dist/index.d.ts +0 -8
  39. package/dist/index.js +0 -153
  40. package/dist/server/index.cjs +0 -8326
  41. package/dist/server/index.d.cts +0 -2
  42. package/dist/server/index.d.ts +0 -2
  43. package/dist/server/index.js +0 -8318
  44. package/dist/services/index.cjs +0 -18
  45. package/dist/services/index.d.cts +0 -3
  46. package/dist/services/index.d.ts +0 -3
  47. package/dist/services/index.js +0 -1
  48. package/dist/templates/instrumentation-template.js +0 -137
  49. package/dist/validator/custom-resolver.cjs +0 -52
  50. package/dist/validator/custom-resolver.d.cts +0 -1
  51. package/dist/validator/custom-resolver.d.ts +0 -1
  52. package/dist/validator/custom-resolver.js +0 -50
  53. package/dist/validator/loader.cjs +0 -7
  54. package/dist/validator/loader.d.cts +0 -1
  55. package/dist/validator/loader.d.ts +0 -1
  56. package/dist/validator/loader.js +0 -4
@@ -1,486 +0,0 @@
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-MKB7NDY3.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 getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths) {
254
- const inputOptions = await chunkD2DCFCLH_cjs.getInputOptions(mastraEntryFile, analyzedBundleInfo, "node", {
255
- "process.env.NODE_ENV": JSON.stringify("production")
256
- });
257
- const isVirtual = serverFile.includes("\n") || fs.existsSync(serverFile);
258
- const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
259
- if (isVirtual) {
260
- inputOptions.input = { index: "#entry", ...toolsInputOptions };
261
- if (Array.isArray(inputOptions.plugins)) {
262
- inputOptions.plugins.unshift(virtual__default.default({ "#entry": serverFile }));
263
- } else {
264
- inputOptions.plugins = [virtual__default.default({ "#entry": serverFile })];
265
- }
266
- } else {
267
- inputOptions.input = { index: serverFile, ...toolsInputOptions };
268
- }
269
- return inputOptions;
270
- }
271
- async getToolsInputOptions(toolsPaths) {
272
- const inputs = {};
273
- for (const toolPath of toolsPaths) {
274
- const expandedPaths = await globby.globby(toolPath, {});
275
- for (const path$1 of expandedPaths) {
276
- if (await fsExtra__default.default.pathExists(path$1)) {
277
- const fileService = new chunkKCP5ITLV_cjs.FileService();
278
- const entryFile = fileService.getFirstExistingFile([
279
- path.join(path$1, "index.ts"),
280
- path.join(path$1, "index.js"),
281
- path$1
282
- // if path itself is a file
283
- ]);
284
- if (!entryFile || (await promises.stat(entryFile)).isDirectory()) {
285
- this.logger.warn(`No entry file found in ${path$1}, skipping...`);
286
- continue;
287
- }
288
- const uniqueToolID = crypto.randomUUID();
289
- inputs[`tools/${uniqueToolID}`] = entryFile;
290
- } else {
291
- this.logger.warn(`Tool path ${path$1} does not exist, skipping...`);
292
- }
293
- }
294
- }
295
- return inputs;
296
- }
297
- async _bundle(serverFile, mastraEntryFile, outputDirectory, toolsPaths = [], bundleLocation = path.join(outputDirectory, this.outputDir)) {
298
- this.logger.info("Start bundling Mastra");
299
- let analyzedBundleInfo;
300
- try {
301
- const resolvedToolsPaths = await this.getToolsInputOptions(toolsPaths);
302
- analyzedBundleInfo = await chunkXKH6F4NE_cjs.analyzeBundle(
303
- [serverFile, ...Object.values(resolvedToolsPaths)],
304
- mastraEntryFile,
305
- path.join(outputDirectory, this.analyzeOutputDir),
306
- "node",
307
- this.logger
308
- );
309
- } catch (error$1) {
310
- const message = error$1 instanceof Error ? error$1.message : String(error$1);
311
- throw new error.MastraError(
312
- {
313
- id: "DEPLOYER_BUNDLER_ANALYZE_FAILED",
314
- text: `Failed to analyze Mastra application: ${message}`,
315
- domain: error.ErrorDomain.DEPLOYER,
316
- category: error.ErrorCategory.SYSTEM
317
- },
318
- error$1
319
- );
320
- }
321
- let externalDependencies;
322
- try {
323
- const result = await chunkM2VZQFTW_cjs.writeTelemetryConfig(mastraEntryFile, path.join(outputDirectory, this.outputDir));
324
- externalDependencies = result.externalDependencies;
325
- } catch (error$1) {
326
- const message = error$1 instanceof Error ? error$1.message : String(error$1);
327
- throw new error.MastraError(
328
- {
329
- id: "DEPLOYER_BUNDLER_TELEMETRY_FAILED",
330
- text: `Failed to write telemetry config: ${message}`,
331
- domain: error.ErrorDomain.DEPLOYER,
332
- category: error.ErrorCategory.SYSTEM
333
- },
334
- error$1
335
- );
336
- }
337
- const mastraFolder = path.dirname(mastraEntryFile);
338
- const fileService = new chunkKCP5ITLV_cjs.FileService();
339
- const customInstrumentation = fileService.getFirstExistingFileOrUndefined([
340
- path.join(mastraFolder, "instrumentation.js"),
341
- path.join(mastraFolder, "instrumentation.ts"),
342
- path.join(mastraFolder, "instrumentation.mjs")
343
- ]);
344
- try {
345
- if (customInstrumentation) {
346
- const result = await writeCustomInstrumentation(customInstrumentation, path.join(outputDirectory, this.outputDir));
347
- externalDependencies = [...externalDependencies, ...result.externalDependencies];
348
- await this.writeInstrumentationFile(path.join(outputDirectory, this.outputDir), customInstrumentation);
349
- } else {
350
- await this.writeInstrumentationFile(path.join(outputDirectory, this.outputDir));
351
- }
352
- } catch (error$1) {
353
- const message = error$1 instanceof Error ? error$1.message : String(error$1);
354
- throw new error.MastraError(
355
- {
356
- id: "DEPLOYER_BUNDLER_INSTRUMENTATION_FILE_FAILED",
357
- text: `Failed to write instrumentation file: ${message}, ${customInstrumentation ? ` Found custom instrumentation file: ${customInstrumentation}` : ""}`,
358
- domain: error.ErrorDomain.DEPLOYER,
359
- category: error.ErrorCategory.SYSTEM
360
- },
361
- error$1
362
- );
363
- }
364
- const dependenciesToInstall = /* @__PURE__ */ new Map();
365
- for (const external of externalDependencies) {
366
- dependenciesToInstall.set(external, "latest");
367
- }
368
- const workspaceMap = await createWorkspacePackageMap();
369
- const workspaceDependencies = /* @__PURE__ */ new Set();
370
- for (const dep of analyzedBundleInfo.externalDependencies) {
371
- try {
372
- const pkgPath = resolveFrom__default.default(mastraEntryFile, `${dep}/package.json`);
373
- const pkg = await fsExtra.readJSON(pkgPath);
374
- if (workspaceMap.has(pkg.name)) {
375
- workspaceDependencies.add(pkg.name);
376
- continue;
377
- }
378
- dependenciesToInstall.set(dep, pkg.version);
379
- } catch {
380
- dependenciesToInstall.set(dep, "latest");
381
- }
382
- }
383
- let resolutions = {};
384
- if (workspaceDependencies.size > 0) {
385
- try {
386
- const result = collectTransitiveWorkspaceDependencies({
387
- workspaceMap,
388
- initialDependencies: workspaceDependencies,
389
- logger: this.logger
390
- });
391
- resolutions = result.resolutions;
392
- Object.entries(resolutions).forEach(([pkgName, tgzPath]) => {
393
- dependenciesToInstall.set(pkgName, tgzPath);
394
- });
395
- await packWorkspaceDependencies({
396
- workspaceMap,
397
- usedWorkspacePackages: result.usedWorkspacePackages,
398
- bundleOutputDir: path.join(outputDirectory, this.outputDir),
399
- logger: this.logger
400
- });
401
- } catch (error$1) {
402
- throw new error.MastraError(
403
- {
404
- id: "DEPLOYER_BUNDLER_WORKSPACE_DEPS_FAILED",
405
- text: `Failed to collect and pack workspace dependencies.`,
406
- domain: error.ErrorDomain.DEPLOYER,
407
- category: error.ErrorCategory.USER
408
- },
409
- error$1
410
- );
411
- }
412
- }
413
- try {
414
- await this.writePackageJson(path.join(outputDirectory, this.outputDir), dependenciesToInstall, resolutions);
415
- this.logger.info("Bundling Mastra application");
416
- const inputOptions = await this.getBundlerOptions(
417
- serverFile,
418
- mastraEntryFile,
419
- analyzedBundleInfo,
420
- toolsPaths
421
- );
422
- const bundler = await this.createBundler(
423
- {
424
- ...inputOptions,
425
- logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
426
- onwarn: (warning) => {
427
- if (warning.code === "CIRCULAR_DEPENDENCY") {
428
- if (warning.ids?.[0]?.includes("node_modules")) {
429
- return;
430
- }
431
- this.logger.warn(`Circular dependency found:
432
- ${warning.message.replace("Circular dependency: ", "")}`);
433
- }
434
- }
435
- },
436
- {
437
- dir: bundleLocation,
438
- manualChunks: {
439
- mastra: ["#mastra"]
440
- }
441
- }
442
- );
443
- await bundler.write();
444
- const toolImports = [];
445
- const toolsExports = [];
446
- Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
447
- const toolExport = `tool${index}`;
448
- toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);
449
- toolsExports.push(toolExport);
450
- });
451
- await promises.writeFile(
452
- path.join(bundleLocation, "tools.mjs"),
453
- `${toolImports.join("\n")}
454
-
455
- export const tools = [${toolsExports.join(", ")}]`
456
- );
457
- this.logger.info("Bundling Mastra done");
458
- this.logger.info("Copying public files");
459
- await this.copyPublic(path.dirname(mastraEntryFile), outputDirectory);
460
- this.logger.info("Done copying public files");
461
- this.logger.info("Installing dependencies");
462
- await this.installDependencies(outputDirectory);
463
- this.logger.info("Done installing dependencies");
464
- } catch (error$1) {
465
- const message = error$1 instanceof Error ? error$1.message : String(error$1);
466
- throw new error.MastraError(
467
- {
468
- id: "DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED",
469
- text: `Failed during bundler bundle stage: ${message}`,
470
- domain: error.ErrorDomain.DEPLOYER,
471
- category: error.ErrorCategory.SYSTEM
472
- },
473
- error$1
474
- );
475
- }
476
- }
477
- async lint(_entryFile, _outputDirectory, toolsPaths) {
478
- const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
479
- const toolsLength = Object.keys(toolsInputOptions).length;
480
- if (toolsLength > 0) {
481
- this.logger.info(`Found ${toolsLength} ${toolsLength === 1 ? "tool" : "tools"}`);
482
- }
483
- }
484
- };
485
-
486
- exports.Bundler = Bundler;
@@ -1,146 +0,0 @@
1
- import { tsConfigPaths, removeDeployer } from './chunk-Z544XXXK.js';
2
- import alias from '@rollup/plugin-alias';
3
- import commonjs from '@rollup/plugin-commonjs';
4
- import json from '@rollup/plugin-json';
5
- import nodeResolve from '@rollup/plugin-node-resolve';
6
- import { fileURLToPath } from 'url';
7
- import { rollup } from 'rollup';
8
- import esbuild from 'rollup-plugin-esbuild';
9
-
10
- async function getInputOptions(entryFile, analyzedBundleInfo, platform, env = { "process.env.NODE_ENV": JSON.stringify("production") }) {
11
- let nodeResolvePlugin = platform === "node" ? nodeResolve({
12
- preferBuiltins: true,
13
- exportConditions: ["node"]
14
- }) : nodeResolve({
15
- preferBuiltins: false,
16
- browser: true
17
- });
18
- const externalsCopy = /* @__PURE__ */ new Set();
19
- for (const external of analyzedBundleInfo.externalDependencies) {
20
- if (external.startsWith("@")) {
21
- const [scope, name] = external.split("/", 3);
22
- externalsCopy.add(`${scope}/${name}`);
23
- externalsCopy.add(`${scope}/${name}/*`);
24
- } else {
25
- externalsCopy.add(external);
26
- externalsCopy.add(`${external}/*`);
27
- }
28
- }
29
- const externals = Array.from(externalsCopy);
30
- const normalizedEntryFile = entryFile.replaceAll("\\", "/");
31
- return {
32
- logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
33
- treeshake: "smallest",
34
- preserveSymlinks: true,
35
- external: externals,
36
- plugins: [
37
- tsConfigPaths(),
38
- {
39
- name: "alias-optimized-deps",
40
- // @ts-ignore
41
- resolveId(id) {
42
- if (!analyzedBundleInfo.dependencies.has(id)) {
43
- return null;
44
- }
45
- const isInvalidChunk = analyzedBundleInfo.invalidChunks.has(analyzedBundleInfo.dependencies.get(id));
46
- if (isInvalidChunk) {
47
- return {
48
- id,
49
- external: true
50
- };
51
- }
52
- return {
53
- id: ".mastra/.build/" + analyzedBundleInfo.dependencies.get(id),
54
- external: false
55
- };
56
- }
57
- },
58
- alias({
59
- entries: [
60
- {
61
- find: /^\#server$/,
62
- replacement: fileURLToPath(import.meta.resolve("@mastra/deployer/server")).replaceAll("\\", "/")
63
- },
64
- {
65
- find: /^\@mastra\/server\/(.*)/,
66
- replacement: `@mastra/server/$1`,
67
- customResolver: (id) => {
68
- if (id.startsWith("@mastra/server")) {
69
- return {
70
- id: fileURLToPath(import.meta.resolve(id))
71
- };
72
- }
73
- }
74
- },
75
- { find: /^\#mastra$/, replacement: normalizedEntryFile }
76
- ]
77
- }),
78
- {
79
- name: "tools-rewriter",
80
- resolveId(id) {
81
- if (id === "#tools") {
82
- return {
83
- id: "./tools.mjs",
84
- external: true
85
- };
86
- }
87
- }
88
- },
89
- esbuild({
90
- target: "node20",
91
- platform,
92
- minify: false,
93
- define: env
94
- }),
95
- commonjs({
96
- extensions: [".js", ".ts"],
97
- transformMixedEsModules: true,
98
- esmExternals(id) {
99
- return externals.includes(id);
100
- }
101
- }),
102
- nodeResolvePlugin,
103
- // for debugging
104
- // {
105
- // name: 'logger',
106
- // //@ts-ignore
107
- // resolveId(id, ...args) {
108
- // console.log({ id, args });
109
- // },
110
- // // @ts-ignore
111
- // transform(code, id) {
112
- // if (code.includes('class Duplexify ')) {
113
- // console.log({ duplex: id });
114
- // }
115
- // },
116
- // },
117
- json(),
118
- removeDeployer(entryFile),
119
- // treeshake unused imports
120
- esbuild({
121
- include: entryFile,
122
- target: "node20",
123
- platform,
124
- minify: false
125
- })
126
- ].filter(Boolean)
127
- };
128
- }
129
- async function createBundler(inputOptions, outputOptions) {
130
- const bundler = await rollup(inputOptions);
131
- return {
132
- write: () => {
133
- return bundler.write({
134
- ...outputOptions,
135
- format: "esm",
136
- entryFileNames: "[name].mjs",
137
- chunkFileNames: "[name].mjs"
138
- });
139
- },
140
- close: () => {
141
- return bundler.close();
142
- }
143
- };
144
- }
145
-
146
- export { createBundler, getInputOptions };