@mastra/deployer 1.0.0-beta.5 → 1.0.0-beta.7

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 (150) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/arktype-aI7TBD0R-JG4WETGU.js +8 -0
  3. package/dist/arktype-aI7TBD0R-JG4WETGU.js.map +1 -0
  4. package/dist/arktype-aI7TBD0R-RMRB5ZNY.cjs +10 -0
  5. package/dist/arktype-aI7TBD0R-RMRB5ZNY.cjs.map +1 -0
  6. package/dist/build/analyze/analyzeEntry.d.ts +4 -1
  7. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  8. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  9. package/dist/build/analyze.cjs +2 -2
  10. package/dist/build/analyze.d.ts +1 -1
  11. package/dist/build/analyze.d.ts.map +1 -1
  12. package/dist/build/analyze.js +1 -1
  13. package/dist/build/bundler.cjs +3 -3
  14. package/dist/build/bundler.d.ts.map +1 -1
  15. package/dist/build/bundler.js +1 -1
  16. package/dist/build/index.cjs +13 -13
  17. package/dist/build/index.js +4 -4
  18. package/dist/build/plugins/esm-shim.d.ts +14 -0
  19. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  20. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  21. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  22. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  23. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  24. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  25. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  26. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  27. package/dist/build/utils.d.ts +1 -0
  28. package/dist/build/utils.d.ts.map +1 -1
  29. package/dist/bundler/index.cjs +2 -2
  30. package/dist/bundler/index.d.ts +1 -1
  31. package/dist/bundler/index.js +1 -1
  32. package/dist/chunk-2NO5NO4J.js +93 -0
  33. package/dist/chunk-2NO5NO4J.js.map +1 -0
  34. package/dist/chunk-2OTEFUER.cjs +69 -0
  35. package/dist/chunk-2OTEFUER.cjs.map +1 -0
  36. package/dist/chunk-46SXOVGO.js +159 -0
  37. package/dist/chunk-46SXOVGO.js.map +1 -0
  38. package/dist/chunk-4YYZKC2P.cjs +4 -0
  39. package/dist/chunk-4YYZKC2P.cjs.map +1 -0
  40. package/dist/chunk-5CWPEG6R.js +62 -0
  41. package/dist/chunk-5CWPEG6R.js.map +1 -0
  42. package/dist/{chunk-QBQY35KA.js → chunk-7G2FA6KY.js} +6 -5
  43. package/dist/chunk-7G2FA6KY.js.map +1 -0
  44. package/dist/chunk-BJURVMEW.cjs +16 -0
  45. package/dist/chunk-BJURVMEW.cjs.map +1 -0
  46. package/dist/{chunk-5QFG6SCM.js → chunk-DPDWM7HQ.js} +2 -2
  47. package/dist/chunk-DPDWM7HQ.js.map +1 -0
  48. package/dist/chunk-HXYLK6CH.js +3 -0
  49. package/dist/chunk-HXYLK6CH.js.map +1 -0
  50. package/dist/chunk-IL36YSXF.cjs +8 -0
  51. package/dist/chunk-IL36YSXF.cjs.map +1 -0
  52. package/dist/chunk-IR2ZJ7CP.cjs +95 -0
  53. package/dist/chunk-IR2ZJ7CP.cjs.map +1 -0
  54. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  55. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  56. package/dist/chunk-L4SN27ZE.js +14 -0
  57. package/dist/chunk-L4SN27ZE.js.map +1 -0
  58. package/dist/{chunk-WFL4V5AW.cjs → chunk-MC37X2IH.cjs} +565 -192
  59. package/dist/chunk-MC37X2IH.cjs.map +1 -0
  60. package/dist/{chunk-Z7TBDRZ7.cjs → chunk-N6GC4R2P.cjs} +13 -23
  61. package/dist/chunk-N6GC4R2P.cjs.map +1 -0
  62. package/dist/chunk-NZ47MQSD.cjs +162 -0
  63. package/dist/chunk-NZ47MQSD.cjs.map +1 -0
  64. package/dist/{chunk-EM3VETMX.js → chunk-O2KU7J7Q.js} +5 -4
  65. package/dist/chunk-O2KU7J7Q.js.map +1 -0
  66. package/dist/{chunk-NVCHGD24.cjs → chunk-ORHTXAPI.cjs} +15 -14
  67. package/dist/chunk-ORHTXAPI.cjs.map +1 -0
  68. package/dist/chunk-PDVYEX76.js +6 -0
  69. package/dist/chunk-PDVYEX76.js.map +1 -0
  70. package/dist/{chunk-6S5GQUS6.cjs → chunk-PMRHMMAQ.cjs} +16 -15
  71. package/dist/chunk-PMRHMMAQ.cjs.map +1 -0
  72. package/dist/{chunk-Z7KK37HD.js → chunk-SRCHVFND.js} +6 -15
  73. package/dist/chunk-SRCHVFND.js.map +1 -0
  74. package/dist/{chunk-NK3AYZ6D.js → chunk-UEFVUIPU.js} +549 -175
  75. package/dist/chunk-UEFVUIPU.js.map +1 -0
  76. package/dist/default-u_dwuiYb-MRYQILW4.js +3 -0
  77. package/dist/default-u_dwuiYb-MRYQILW4.js.map +1 -0
  78. package/dist/default-u_dwuiYb-WPBHZH2R.cjs +9 -0
  79. package/dist/default-u_dwuiYb-WPBHZH2R.cjs.map +1 -0
  80. package/dist/deploy/log.d.ts +1 -1
  81. package/dist/deploy/log.d.ts.map +1 -1
  82. package/dist/effect-QlVUlMFu-N7VAYT2B.cjs +17 -0
  83. package/dist/effect-QlVUlMFu-N7VAYT2B.cjs.map +1 -0
  84. package/dist/effect-QlVUlMFu-NH625H3V.js +15 -0
  85. package/dist/effect-QlVUlMFu-NH625H3V.js.map +1 -0
  86. package/dist/esm-BZAOWJTI.cjs +1336 -0
  87. package/dist/esm-BZAOWJTI.cjs.map +1 -0
  88. package/dist/esm-T7FR74HN.js +1289 -0
  89. package/dist/esm-T7FR74HN.js.map +1 -0
  90. package/dist/index.cjs +12 -12
  91. package/dist/index.js +4 -4
  92. package/dist/server/index.cjs +1113 -1508
  93. package/dist/server/index.cjs.map +1 -1
  94. package/dist/server/index.d.ts.map +1 -1
  95. package/dist/server/index.js +1101 -1496
  96. package/dist/server/index.js.map +1 -1
  97. package/dist/services/index.cjs +4 -4
  98. package/dist/services/index.js +1 -1
  99. package/dist/sury-CWZTCd75-E5BDQIXB.cjs +17 -0
  100. package/dist/sury-CWZTCd75-E5BDQIXB.cjs.map +1 -0
  101. package/dist/sury-CWZTCd75-HWBNYVQW.js +15 -0
  102. package/dist/sury-CWZTCd75-HWBNYVQW.js.map +1 -0
  103. package/dist/typebox-Dei93FPO-42ICWLXF.cjs +10 -0
  104. package/dist/typebox-Dei93FPO-42ICWLXF.cjs.map +1 -0
  105. package/dist/typebox-Dei93FPO-XXPZXWWK.js +8 -0
  106. package/dist/typebox-Dei93FPO-XXPZXWWK.js.map +1 -0
  107. package/dist/valibot--1zFm7rT-ALWQ34TP.cjs +17 -0
  108. package/dist/valibot--1zFm7rT-ALWQ34TP.cjs.map +1 -0
  109. package/dist/valibot--1zFm7rT-W6DSEVCL.js +15 -0
  110. package/dist/valibot--1zFm7rT-W6DSEVCL.js.map +1 -0
  111. package/dist/valibot-D_HTw1Gn-LVFT5X5F.js +43 -0
  112. package/dist/valibot-D_HTw1Gn-LVFT5X5F.js.map +1 -0
  113. package/dist/valibot-D_HTw1Gn-PN7GEV4F.cjs +45 -0
  114. package/dist/valibot-D_HTw1Gn-PN7GEV4F.cjs.map +1 -0
  115. package/dist/validator/custom-resolver.cjs +20 -12
  116. package/dist/validator/custom-resolver.cjs.map +1 -1
  117. package/dist/validator/custom-resolver.d.ts.map +1 -1
  118. package/dist/validator/custom-resolver.js +18 -10
  119. package/dist/validator/custom-resolver.js.map +1 -1
  120. package/dist/validator/validate.d.ts +15 -1
  121. package/dist/validator/validate.d.ts.map +1 -1
  122. package/dist/zod-Bwrt9trS-C5ATNTZG.cjs +31 -0
  123. package/dist/zod-Bwrt9trS-C5ATNTZG.cjs.map +1 -0
  124. package/dist/zod-Bwrt9trS-UDAV5VDV.js +29 -0
  125. package/dist/zod-Bwrt9trS-UDAV5VDV.js.map +1 -0
  126. package/dist/zod-DSgpEGAE-AVWGGTUD.js +37 -0
  127. package/dist/zod-DSgpEGAE-AVWGGTUD.js.map +1 -0
  128. package/dist/zod-DSgpEGAE-EH7N2QK7.cjs +39 -0
  129. package/dist/zod-DSgpEGAE-EH7N2QK7.cjs.map +1 -0
  130. package/package.json +8 -6
  131. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  132. package/dist/chunk-5QFG6SCM.js.map +0 -1
  133. package/dist/chunk-6S5GQUS6.cjs.map +0 -1
  134. package/dist/chunk-EM3VETMX.js.map +0 -1
  135. package/dist/chunk-NK3AYZ6D.js.map +0 -1
  136. package/dist/chunk-NVCHGD24.cjs.map +0 -1
  137. package/dist/chunk-QBQY35KA.js.map +0 -1
  138. package/dist/chunk-WFL4V5AW.cjs.map +0 -1
  139. package/dist/chunk-Z7KK37HD.js.map +0 -1
  140. package/dist/chunk-Z7TBDRZ7.cjs.map +0 -1
  141. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  142. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  143. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  144. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  145. package/dist/server/handlers/auth/index.d.ts +0 -11
  146. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  147. package/dist/server/handlers/mcp.d.ts +0 -86
  148. package/dist/server/handlers/mcp.d.ts.map +0 -1
  149. package/dist/server/schemas/mcp.d.ts +0 -230
  150. package/dist/server/schemas/mcp.d.ts.map +0 -1
@@ -1,12 +1,11 @@
1
+ import { slash, isDependencyPartOfPackage, getPackageRootPath, getPackageName, getCompiledDepCachePath, rollupSafeName } from './chunk-5CWPEG6R.js';
1
2
  import * as babel from '@babel/core';
2
3
  import babel__default from '@babel/core';
3
4
  import fs, { existsSync } from 'fs';
4
5
  import { readFile, writeFile } from 'fs/promises';
5
6
  import * as path2 from 'path';
6
- import path2__default, { dirname, join, normalize, relative, basename as basename$1 } from 'path';
7
+ import path2__default, { dirname, join, normalize, basename as basename$1 } from 'path';
7
8
  import { spawn as spawn$1 } from 'child_process';
8
- import { getPackageInfo } from 'local-pkg';
9
- import { pathToFileURL, fileURLToPath } from 'url';
10
9
  import { rollup } from 'rollup';
11
10
  import originalEsbuild from 'rollup-plugin-esbuild';
12
11
  import commonjs from '@rollup/plugin-commonjs';
@@ -18,90 +17,27 @@ import * as pkg from 'empathic/package';
18
17
  import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
19
18
  import { noopLogger } from '@mastra/core/logger';
20
19
  import virtual from '@rollup/plugin-virtual';
20
+ import { fileURLToPath, pathToFileURL } from 'url';
21
21
  import { builtinModules } from 'module';
22
22
  import nodeResolve from '@rollup/plugin-node-resolve';
23
- import esmShim from '@rollup/plugin-esm-shim';
23
+ import originalEsmShim from '@rollup/plugin-esm-shim';
24
24
  import { basename } from 'path/posix';
25
25
  import * as resolve from 'resolve.exports';
26
+ import { getPackageInfo } from 'local-pkg';
26
27
  import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
27
28
 
28
- // src/build/analyze.ts
29
- function getPackageName(id) {
30
- const parts = id.split("/");
31
- if (id.startsWith("@")) {
32
- return parts.slice(0, 2).join("/");
33
- }
34
- return parts[0];
35
- }
36
- async function getPackageRootPath(packageName, parentPath) {
37
- let rootPath;
38
- try {
39
- let options = void 0;
40
- if (parentPath) {
41
- if (!parentPath.startsWith("file://")) {
42
- parentPath = pathToFileURL(parentPath).href;
43
- }
44
- options = {
45
- paths: [parentPath]
46
- };
47
- }
48
- const pkg2 = await getPackageInfo(packageName, options);
49
- rootPath = pkg2?.rootPath ?? null;
50
- } catch (e) {
51
- rootPath = null;
52
- }
53
- return rootPath;
54
- }
55
- function getCompiledDepCachePath(rootPath, packageName) {
56
- return slash(join(rootPath, "node_modules", ".cache", packageName));
57
- }
58
- function slash(path3) {
59
- const isExtendedLengthPath = path3.startsWith("\\\\?\\");
60
- if (isExtendedLengthPath) {
61
- return path3;
62
- }
63
- return path3.replaceAll("\\", "/");
64
- }
65
- function rollupSafeName(name, rootDir) {
66
- const rel = relative(rootDir, name);
67
- let entry = slash(rel);
68
- entry = entry.replace(/^(\.\.\/)+/, "");
69
- entry = entry.replace(/^\/+/, "");
70
- entry = entry.replace(/^[A-Za-z]:\//, "");
71
- if (!entry) {
72
- entry = slash(basename$1(name));
29
+ var ValidationError = class extends Error {
30
+ type;
31
+ stack;
32
+ constructor(args) {
33
+ super(args.message);
34
+ this.type = args.type;
35
+ this.stack = args.stack;
73
36
  }
74
- return entry;
75
- }
76
- var NATIVE_BINDING_LOADERS = [
77
- "node-gyp-build",
78
- "prebuild-install",
79
- "bindings",
80
- "node-addon-api",
81
- "node-pre-gyp",
82
- "nan"
83
- // Native Abstractions for Node.js
84
- ];
85
- function findNativePackageModule(moduleIds) {
86
- return moduleIds.find((id) => {
87
- if (id.startsWith("\0")) {
88
- return false;
89
- }
90
- if (!id.includes("/node_modules/")) {
91
- return false;
92
- }
93
- for (const loader of NATIVE_BINDING_LOADERS) {
94
- if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {
95
- return false;
96
- }
97
- }
98
- return true;
99
- });
100
- }
101
-
102
- // src/validator/validate.ts
37
+ };
103
38
  function spawn(command, args = [], options = {}) {
104
39
  return new Promise((resolve2, reject) => {
40
+ let validationError = null;
105
41
  const childProcess = spawn$1(command, args, {
106
42
  // stdio: 'inherit',
107
43
  ...options
@@ -111,28 +47,63 @@ function spawn(command, args = [], options = {}) {
111
47
  });
112
48
  let stderr = "";
113
49
  childProcess.stderr?.on("data", (message) => {
114
- stderr += message;
50
+ try {
51
+ validationError = JSON.parse(message.toString());
52
+ } catch {
53
+ stderr += message;
54
+ }
115
55
  });
116
56
  childProcess.on("close", (code) => {
117
57
  if (code === 0) {
118
58
  resolve2();
119
59
  } else {
120
- reject(new Error(stderr));
60
+ if (validationError) {
61
+ reject(new ValidationError(validationError));
62
+ } else {
63
+ reject(new Error(stderr));
64
+ }
121
65
  }
122
66
  });
123
67
  });
124
68
  }
125
- function validate(file) {
69
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation }) {
70
+ let prefixCode = "";
71
+ if (injectESMShim) {
72
+ prefixCode = `import { fileURLToPath } from 'url';
73
+ import { dirname } from 'path';
74
+
75
+ globalThis.__filename = fileURLToPath(import.meta.url);
76
+ globalThis.__dirname = dirname(__filename);
77
+ `;
78
+ }
79
+ function errorHandler(err) {
80
+ console.error(
81
+ JSON.stringify({
82
+ type: err.name,
83
+ message: err.message,
84
+ stack: err.stack
85
+ })
86
+ );
87
+ process.exit(1);
88
+ }
126
89
  return spawn(
127
- "node",
90
+ process.execPath,
128
91
  [
129
92
  "--import",
130
93
  import.meta.resolve("@mastra/deployer/loader"),
131
94
  "--input-type=module",
95
+ "--enable-source-maps",
132
96
  "-e",
133
- `import('file://${slash(file)}')`
97
+ `${prefixCode};import('file://${slash(file)}').catch(err => {
98
+ ${errorHandler.toString()}
99
+ errorHandler(err);
100
+ })`.replaceAll(/\n/g, "")
134
101
  ],
135
102
  {
103
+ env: {
104
+ ...process.env,
105
+ MODULE_MAP: `${moduleResolveMapLocation}`
106
+ },
136
107
  cwd: dirname(file)
137
108
  }
138
109
  );
@@ -228,28 +199,88 @@ function esbuild(options = {}) {
228
199
  }
229
200
  var PLUGIN_NAME = "tsconfig-paths";
230
201
  function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
231
- let handler;
202
+ const handlerCache = /* @__PURE__ */ new Map();
203
+ function findTsConfigForFile(filePath) {
204
+ let currentDir = path2__default.dirname(filePath);
205
+ const root = path2__default.parse(currentDir).root;
206
+ while (currentDir !== root) {
207
+ const tsConfigPath2 = path2__default.join(currentDir, "tsconfig.json");
208
+ if (fs.existsSync(tsConfigPath2)) {
209
+ if (hasPaths(tsConfigPath2)) {
210
+ return tsConfigPath2;
211
+ }
212
+ }
213
+ const tsConfigBasePath = path2__default.join(currentDir, "tsconfig.base.json");
214
+ if (fs.existsSync(tsConfigBasePath)) {
215
+ if (hasPaths(tsConfigBasePath)) {
216
+ return tsConfigBasePath;
217
+ }
218
+ }
219
+ currentDir = path2__default.dirname(currentDir);
220
+ }
221
+ return null;
222
+ }
223
+ function hasPaths(tsConfigPath2) {
224
+ try {
225
+ const config = JSON.parse(fs.readFileSync(tsConfigPath2, "utf8"));
226
+ return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
227
+ } catch {
228
+ return false;
229
+ }
230
+ }
231
+ function getHandlerForFile(filePath) {
232
+ if (tsConfigPath && typeof tsConfigPath === "string") {
233
+ if (!handlerCache.has(tsConfigPath)) {
234
+ handlerCache.set(
235
+ tsConfigPath,
236
+ createHandler({
237
+ log: () => {
238
+ },
239
+ tsConfigPath,
240
+ respectCoreModule,
241
+ falllback: (moduleName) => fs.existsSync(moduleName)
242
+ })
243
+ );
244
+ }
245
+ return handlerCache.get(tsConfigPath);
246
+ }
247
+ const configPath = findTsConfigForFile(filePath);
248
+ if (!configPath) {
249
+ return null;
250
+ }
251
+ if (!handlerCache.has(configPath)) {
252
+ handlerCache.set(
253
+ configPath,
254
+ createHandler({
255
+ log: () => {
256
+ },
257
+ tsConfigPath: configPath,
258
+ respectCoreModule,
259
+ falllback: (moduleName) => fs.existsSync(moduleName)
260
+ })
261
+ );
262
+ }
263
+ return handlerCache.get(configPath);
264
+ }
265
+ function resolveAlias(request, importer) {
266
+ const dynamicHandler = getHandlerForFile(importer);
267
+ if (!dynamicHandler) {
268
+ return null;
269
+ }
270
+ const resolved = dynamicHandler(request, normalize(importer));
271
+ return resolved;
272
+ }
232
273
  return {
233
274
  name: PLUGIN_NAME,
234
- buildStart() {
235
- handler = createHandler({
236
- log: () => {
237
- },
238
- tsConfigPath,
239
- respectCoreModule,
240
- falllback: (moduleName) => fs.existsSync(moduleName)
241
- });
242
- return;
243
- },
244
275
  async resolveId(request, importer, options) {
245
- if (!importer || request.startsWith("\0")) {
276
+ if (!importer || request.startsWith("\0") || importer.charCodeAt(0) === 0) {
246
277
  return null;
247
278
  }
248
- const moduleName = handler?.(request, normalize(importer));
279
+ const moduleName = resolveAlias(request, importer);
249
280
  if (!moduleName) {
250
281
  let importerMeta = {};
251
- const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
252
- if (!resolved) {
282
+ const resolved2 = await this.resolve(request, importer, { skipSelf: true, ...options });
283
+ if (!resolved2) {
253
284
  return null;
254
285
  }
255
286
  if (localResolve) {
@@ -257,37 +288,42 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
257
288
  importerMeta = importerInfo?.meta || {};
258
289
  if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
259
290
  return {
260
- ...resolved,
291
+ ...resolved2,
261
292
  external: !request.startsWith("hono/") && request !== "hono"
262
293
  };
263
294
  }
264
295
  }
265
296
  return {
266
- ...resolved,
297
+ ...resolved2,
267
298
  meta: {
268
- ...resolved.meta || {},
299
+ ...resolved2.meta || {},
269
300
  ...importerMeta
270
301
  }
271
302
  };
272
303
  }
273
304
  if (!path2__default.extname(moduleName)) {
274
- const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
275
- if (!resolved) {
305
+ const resolved2 = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
306
+ if (!resolved2) {
276
307
  return null;
277
308
  }
278
309
  return {
279
- ...resolved,
310
+ ...resolved2,
280
311
  meta: {
281
- ...resolved.meta,
312
+ ...resolved2.meta,
282
313
  [PLUGIN_NAME]: {
283
314
  resolved: true
284
315
  }
285
316
  }
286
317
  };
287
318
  }
319
+ const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
320
+ if (!resolved) {
321
+ return null;
322
+ }
288
323
  return {
289
- id: moduleName,
324
+ ...resolved,
290
325
  meta: {
326
+ ...resolved.meta,
291
327
  [PLUGIN_NAME]: {
292
328
  resolved: true
293
329
  }
@@ -666,7 +702,8 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
666
702
  return plugins;
667
703
  }
668
704
  async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
669
- logger
705
+ logger,
706
+ shouldCheckTransitiveDependencies
670
707
  }) {
671
708
  const depsToOptimize = /* @__PURE__ */ new Map();
672
709
  if (!output.facadeModuleId) {
@@ -679,7 +716,7 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
679
716
  entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
680
717
  }
681
718
  for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
682
- if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
719
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
683
720
  continue;
684
721
  }
685
722
  const pkgName = getPackageName(dependency);
@@ -690,7 +727,11 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
690
727
  isWorkspace = workspaceMap.has(pkgName);
691
728
  }
692
729
  const normalizedRootPath = rootPath ? slash(rootPath) : null;
693
- depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace });
730
+ depsToOptimize.set(dependency, {
731
+ exports: bindings,
732
+ rootPath: normalizedRootPath,
733
+ isWorkspace
734
+ });
694
735
  }
695
736
  async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
696
737
  if (currentDepth >= maxDepth) {
@@ -734,12 +775,18 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
734
775
  await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
735
776
  }
736
777
  }
737
- await checkTransitiveDependencies(initialDepsToOptimize);
778
+ if (shouldCheckTransitiveDependencies) {
779
+ await checkTransitiveDependencies(initialDepsToOptimize);
780
+ }
738
781
  const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
739
782
  if (dynamicImports.length) {
740
783
  for (const dynamicImport of dynamicImports) {
741
784
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
742
- depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
785
+ depsToOptimize.set(dynamicImport, {
786
+ exports: ["*"],
787
+ rootPath: null,
788
+ isWorkspace: false
789
+ });
743
790
  }
744
791
  }
745
792
  }
@@ -753,8 +800,9 @@ async function analyzeEntry({
753
800
  sourcemapEnabled,
754
801
  workspaceMap,
755
802
  projectRoot,
756
- initialDepsToOptimize = /* @__PURE__ */ new Map()
803
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
757
804
  // used to avoid infinite recursion
805
+ shouldCheckTransitiveDependencies = false
758
806
  }) {
759
807
  const optimizerBundler = await rollup({
760
808
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
@@ -775,7 +823,8 @@ async function analyzeEntry({
775
823
  projectRoot,
776
824
  initialDepsToOptimize,
777
825
  {
778
- logger
826
+ logger,
827
+ shouldCheckTransitiveDependencies
779
828
  }
780
829
  );
781
830
  return {
@@ -786,6 +835,27 @@ async function analyzeEntry({
786
835
  }
787
836
  };
788
837
  }
838
+ var FilenameDeclarationRegex = /(?:const|let|var)\s+__filename/;
839
+ var DirnameDeclarationRegex = /(?:const|let|var)\s+__dirname/;
840
+ function esmShim() {
841
+ const original = originalEsmShim();
842
+ return {
843
+ name: "esm-shim",
844
+ renderChunk(code, chunk, opts, meta) {
845
+ const hasFilename = code.includes("__filename");
846
+ const hasDirname = code.includes("__dirname");
847
+ const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);
848
+ const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);
849
+ if (userDeclaredFilename || userDeclaredDirname) {
850
+ return null;
851
+ }
852
+ if (typeof original.renderChunk === "function") {
853
+ return original.renderChunk.call(this, code, chunk, opts, meta);
854
+ }
855
+ return null;
856
+ }
857
+ };
858
+ }
789
859
  function aliasHono() {
790
860
  return {
791
861
  name: "hono-alias",
@@ -798,6 +868,114 @@ function aliasHono() {
798
868
  }
799
869
  };
800
870
  }
871
+ function nodeGypDetector() {
872
+ const modulesToTrack = /* @__PURE__ */ new Set();
873
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
874
+ return {
875
+ name: "node-gyp-build-detector",
876
+ moduleParsed(info) {
877
+ if (!info.meta?.commonjs?.requires?.length) {
878
+ return;
879
+ }
880
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
881
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
882
+ );
883
+ if (!hasNodeGypBuild) {
884
+ return;
885
+ }
886
+ modulesToTrack.add(info.id);
887
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
888
+ },
889
+ async generateBundle(options, bundle) {
890
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
891
+ for (const [fileName, chunk] of Object.entries(bundle)) {
892
+ if (chunk.type === "chunk") {
893
+ for (const moduleId of chunk.moduleIds) {
894
+ if (modulesToTrackPackageInfo.has(moduleId)) {
895
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
896
+ if (!binaryMapByChunk.has(fileName)) {
897
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
898
+ }
899
+ if (pkgInfo?.packageJson?.name) {
900
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
901
+ }
902
+ }
903
+ }
904
+ }
905
+ }
906
+ const binaryMapJson = Object.fromEntries(
907
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
908
+ );
909
+ this.emitFile({
910
+ type: "asset",
911
+ name: "binary-map.json",
912
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
913
+ });
914
+ }
915
+ };
916
+ }
917
+
918
+ // src/build/plugins/subpath-externals-resolver.ts
919
+ function subpathExternalsResolver(externals) {
920
+ return {
921
+ name: "subpath-externals-resolver",
922
+ resolveId(id) {
923
+ if (id.startsWith(".") || id.startsWith("/")) {
924
+ return null;
925
+ }
926
+ const isPartOfExternals = externals.some((external) => isDependencyPartOfPackage(id, external));
927
+ if (isPartOfExternals) {
928
+ return {
929
+ id,
930
+ external: true
931
+ };
932
+ }
933
+ }
934
+ };
935
+ }
936
+ function moduleResolveMap(externals, projectRoot) {
937
+ const importMap = /* @__PURE__ */ new Map();
938
+ return {
939
+ name: "module-resolve-map",
940
+ moduleParsed(info) {
941
+ if (info.importedIds.length === 0 || !info.id) {
942
+ return;
943
+ }
944
+ for (const importedId of info.importedIds) {
945
+ for (const external of externals) {
946
+ if (isDependencyPartOfPackage(importedId, external)) {
947
+ importMap.set(external, info.id);
948
+ }
949
+ }
950
+ }
951
+ },
952
+ async generateBundle(options, bundle) {
953
+ const resolveMap = /* @__PURE__ */ new Map();
954
+ for (const [fileName, chunk] of Object.entries(bundle)) {
955
+ if (chunk.type === "chunk") {
956
+ for (const [external, resolvedFrom] of importMap) {
957
+ if (chunk.moduleIds.includes(resolvedFrom)) {
958
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
959
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
960
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
961
+ resolveMap.set(fullPath, innerMap);
962
+ }
963
+ }
964
+ }
965
+ }
966
+ const resolveMapJson = Object.fromEntries(
967
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
968
+ );
969
+ this.emitFile({
970
+ type: "asset",
971
+ name: "module-resolve-map.json",
972
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
973
+ });
974
+ }
975
+ };
976
+ }
977
+
978
+ // src/build/analyze/bundleExternals.ts
801
979
  function prepareEntryFileName(name, rootDir) {
802
980
  return rollupSafeName(name, rootDir);
803
981
  }
@@ -863,7 +1041,8 @@ async function getInputPlugins2(virtualDependencies, {
863
1041
  transpilePackages,
864
1042
  workspaceMap,
865
1043
  bundlerOptions,
866
- rootDir
1044
+ rootDir,
1045
+ externals
867
1046
  }) {
868
1047
  const transpilePackagesMap = /* @__PURE__ */ new Map();
869
1048
  for (const pkg2 of transpilePackages) {
@@ -884,6 +1063,7 @@ async function getInputPlugins2(virtualDependencies, {
884
1063
  {}
885
1064
  )
886
1065
  ),
1066
+ subpathExternalsResolver(externals),
887
1067
  transpilePackagesMap.size ? esbuild({
888
1068
  format: "esm",
889
1069
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -912,7 +1092,8 @@ async function getInputPlugins2(virtualDependencies, {
912
1092
  if (!resolvedPath) {
913
1093
  resolvedPath = pkgJson.main ?? "index.js";
914
1094
  }
915
- return await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1095
+ const resolved = await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1096
+ return resolved;
916
1097
  }
917
1098
  } : null,
918
1099
  optimizeLodashImports({
@@ -931,6 +1112,8 @@ async function getInputPlugins2(virtualDependencies, {
931
1112
  // hono is imported from deployer, so we need to resolve from here instead of the project root
932
1113
  aliasHono(),
933
1114
  json(),
1115
+ nodeGypDetector(),
1116
+ moduleResolveMap(externals, rootDir),
934
1117
  {
935
1118
  name: "not-found-resolver",
936
1119
  resolveId: {
@@ -988,12 +1171,13 @@ async function buildExternalDependencies(virtualDependencies, {
988
1171
  {}
989
1172
  ),
990
1173
  external: externals,
991
- treeshake: "safest",
1174
+ treeshake: bundlerOptions.isDev ? false : "safest",
992
1175
  plugins: getInputPlugins2(virtualDependencies, {
993
1176
  transpilePackages: packagesToTranspile,
994
1177
  workspaceMap,
995
1178
  bundlerOptions,
996
- rootDir
1179
+ rootDir,
1180
+ externals
997
1181
  })
998
1182
  });
999
1183
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
@@ -1001,6 +1185,8 @@ async function buildExternalDependencies(virtualDependencies, {
1001
1185
  format: "esm",
1002
1186
  dir: rootDir,
1003
1187
  entryFileNames: "[name].mjs",
1188
+ // used to get the filename of the actual error
1189
+ sourcemap: true,
1004
1190
  /**
1005
1191
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1006
1192
  * So we want to write them to the `.mastra/output` folder as well.
@@ -1038,6 +1224,7 @@ async function buildExternalDependencies(virtualDependencies, {
1038
1224
  }
1039
1225
  return `${outputDirRelative}/[name].mjs`;
1040
1226
  },
1227
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1041
1228
  hoistTransitiveImports: false
1042
1229
  });
1043
1230
  await bundler.close();
@@ -1046,7 +1233,7 @@ async function buildExternalDependencies(virtualDependencies, {
1046
1233
  function findExternalImporter(module, external, allOutputs) {
1047
1234
  const capturedFiles = /* @__PURE__ */ new Set();
1048
1235
  for (const id of module.imports) {
1049
- if (id === external) {
1236
+ if (isDependencyPartOfPackage(id, external)) {
1050
1237
  return module;
1051
1238
  } else {
1052
1239
  if (id.endsWith(".mjs")) {
@@ -1092,7 +1279,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1092
1279
  isDev
1093
1280
  }
1094
1281
  });
1095
- const moduleResolveMap = /* @__PURE__ */ new Map();
1282
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1096
1283
  const filteredChunks = output.filter((o) => o.type === "chunk");
1097
1284
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1098
1285
  for (const external of allExternals) {
@@ -1102,10 +1289,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1102
1289
  const importer = findExternalImporter(o, external, filteredChunks);
1103
1290
  if (importer) {
1104
1291
  const fullPath = path2.join(workspaceRoot || projectRoot, importer.fileName);
1105
- let innerMap = moduleResolveMap.get(fullPath);
1292
+ let innerMap = moduleResolveMap2.get(fullPath);
1106
1293
  if (!innerMap) {
1107
1294
  innerMap = /* @__PURE__ */ new Map();
1108
- moduleResolveMap.set(fullPath, innerMap);
1295
+ moduleResolveMap2.set(fullPath, innerMap);
1109
1296
  }
1110
1297
  if (importer.moduleIds.length) {
1111
1298
  innerMap.set(
@@ -1117,7 +1304,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1117
1304
  }
1118
1305
  }
1119
1306
  const usedExternals = /* @__PURE__ */ Object.create(null);
1120
- for (const [fullPath, innerMap] of moduleResolveMap) {
1307
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1121
1308
  const innerObj = /* @__PURE__ */ Object.create(null);
1122
1309
  for (const [external, value] of innerMap) {
1123
1310
  innerObj[external] = value;
@@ -1126,6 +1313,108 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1126
1313
  }
1127
1314
  return { output, fileNameToDependencyMap, usedExternals };
1128
1315
  }
1316
+
1317
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1318
+ var UNKNOWN_FUNCTION = "<unknown>";
1319
+ function parse(stackString) {
1320
+ var lines = stackString.split("\n");
1321
+ return lines.reduce(function(stack, line) {
1322
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1323
+ if (parseResult) {
1324
+ stack.push(parseResult);
1325
+ }
1326
+ return stack;
1327
+ }, []);
1328
+ }
1329
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1330
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1331
+ function parseChrome(line) {
1332
+ var parts = chromeRe.exec(line);
1333
+ if (!parts) {
1334
+ return null;
1335
+ }
1336
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1337
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1338
+ var submatch = chromeEvalRe.exec(parts[2]);
1339
+ if (isEval && submatch != null) {
1340
+ parts[2] = submatch[1];
1341
+ parts[3] = submatch[2];
1342
+ parts[4] = submatch[3];
1343
+ }
1344
+ return {
1345
+ file: !isNative ? parts[2] : null,
1346
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1347
+ arguments: isNative ? [parts[2]] : [],
1348
+ lineNumber: parts[3] ? +parts[3] : null,
1349
+ column: parts[4] ? +parts[4] : null
1350
+ };
1351
+ }
1352
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1353
+ function parseWinjs(line) {
1354
+ var parts = winjsRe.exec(line);
1355
+ if (!parts) {
1356
+ return null;
1357
+ }
1358
+ return {
1359
+ file: parts[2],
1360
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1361
+ arguments: [],
1362
+ lineNumber: +parts[3],
1363
+ column: parts[4] ? +parts[4] : null
1364
+ };
1365
+ }
1366
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1367
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1368
+ function parseGecko(line) {
1369
+ var parts = geckoRe.exec(line);
1370
+ if (!parts) {
1371
+ return null;
1372
+ }
1373
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1374
+ var submatch = geckoEvalRe.exec(parts[3]);
1375
+ if (isEval && submatch != null) {
1376
+ parts[3] = submatch[1];
1377
+ parts[4] = submatch[2];
1378
+ parts[5] = null;
1379
+ }
1380
+ return {
1381
+ file: parts[3],
1382
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1383
+ arguments: parts[2] ? parts[2].split(",") : [],
1384
+ lineNumber: parts[4] ? +parts[4] : null,
1385
+ column: parts[5] ? +parts[5] : null
1386
+ };
1387
+ }
1388
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1389
+ function parseJSC(line) {
1390
+ var parts = javaScriptCoreRe.exec(line);
1391
+ if (!parts) {
1392
+ return null;
1393
+ }
1394
+ return {
1395
+ file: parts[3],
1396
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1397
+ arguments: [],
1398
+ lineNumber: +parts[4],
1399
+ column: parts[5] ? +parts[5] : null
1400
+ };
1401
+ }
1402
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1403
+ function parseNode(line) {
1404
+ var parts = nodeRe.exec(line);
1405
+ if (!parts) {
1406
+ return null;
1407
+ }
1408
+ return {
1409
+ file: parts[2],
1410
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1411
+ arguments: [],
1412
+ lineNumber: +parts[3],
1413
+ column: parts[4] ? +parts[4] : null
1414
+ };
1415
+ }
1416
+
1417
+ // src/build/analyze.ts
1129
1418
  function throwExternalDependencyError({
1130
1419
  errorId,
1131
1420
  moduleName,
@@ -1149,6 +1438,110 @@ export const mastra = new Mastra({
1149
1438
  })`
1150
1439
  });
1151
1440
  }
1441
+ function getPackageNameFromBundledModuleName(moduleName) {
1442
+ const chunks = moduleName.split("-");
1443
+ if (!chunks.length) {
1444
+ return moduleName;
1445
+ }
1446
+ if (chunks[0]?.startsWith("@")) {
1447
+ return chunks.slice(0, 2).join("/");
1448
+ }
1449
+ return chunks[0];
1450
+ }
1451
+ function validateError(err, file, {
1452
+ binaryMapData,
1453
+ workspaceMap
1454
+ }) {
1455
+ let moduleName = null;
1456
+ let errorConfig = null;
1457
+ if (err instanceof ValidationError) {
1458
+ const parsedStack = parse(err.stack);
1459
+ if (err.type === "TypeError") {
1460
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1461
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1462
+ if (stacktraceFrame) {
1463
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1464
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1465
+ } else {
1466
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1467
+ }
1468
+ errorConfig = {
1469
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1470
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1471
+ };
1472
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1473
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1474
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1475
+ errorConfig = {
1476
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1477
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1478
+ };
1479
+ if (moduleName === parentModuleName) {
1480
+ return;
1481
+ }
1482
+ }
1483
+ }
1484
+ if (err.message.includes("No native build was found")) {
1485
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1486
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1487
+ errorConfig = {
1488
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1489
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1490
+ };
1491
+ }
1492
+ if (moduleName && workspaceMap.has(moduleName)) {
1493
+ throw new MastraError({
1494
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1495
+ domain: ErrorDomain.DEPLOYER,
1496
+ category: ErrorCategory.USER,
1497
+ details: {
1498
+ // importFile: moduleName,
1499
+ packageName: moduleName
1500
+ },
1501
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1502
+ Error: ${err.stack}`
1503
+ });
1504
+ }
1505
+ if (errorConfig && moduleName) {
1506
+ throwExternalDependencyError({
1507
+ errorId: errorConfig.id,
1508
+ moduleName,
1509
+ packageName: moduleName,
1510
+ messagePrefix: errorConfig.messagePrefix
1511
+ });
1512
+ }
1513
+ }
1514
+ async function validateFile(root, file, {
1515
+ binaryMapData,
1516
+ moduleResolveMapLocation,
1517
+ logger,
1518
+ workspaceMap
1519
+ }) {
1520
+ try {
1521
+ if (!file.isDynamicEntry && file.isEntry) {
1522
+ await validate(join(root, file.fileName), {
1523
+ moduleResolveMapLocation,
1524
+ injectESMShim: false
1525
+ });
1526
+ }
1527
+ } catch (err) {
1528
+ let errorToHandle = err;
1529
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1530
+ try {
1531
+ await validate(join(root, file.fileName), {
1532
+ moduleResolveMapLocation,
1533
+ injectESMShim: true
1534
+ });
1535
+ errorToHandle = null;
1536
+ } catch (err2) {
1537
+ errorToHandle = err2;
1538
+ }
1539
+ }
1540
+ if (errorToHandle instanceof Error) {
1541
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1542
+ }
1543
+ }
1544
+ }
1152
1545
  async function validateOutput({
1153
1546
  output,
1154
1547
  reverseVirtualReferenceMap,
@@ -1162,60 +1555,30 @@ async function validateOutput({
1162
1555
  externalDependencies: /* @__PURE__ */ new Set(),
1163
1556
  workspaceMap
1164
1557
  };
1165
- await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1166
1558
  for (const deps of Object.values(usedExternals)) {
1167
1559
  for (const dep of Object.keys(deps)) {
1168
1560
  result.externalDependencies.add(dep);
1169
1561
  }
1170
1562
  }
1563
+ let binaryMapData = {};
1564
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1565
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1566
+ binaryMapData = JSON.parse(binaryMap);
1567
+ }
1171
1568
  for (const file of output) {
1172
1569
  if (file.type === "asset") {
1173
1570
  continue;
1174
1571
  }
1175
- try {
1176
- logger.debug(`Validating if ${file.fileName} is a valid module.`);
1177
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1178
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1179
- }
1180
- if (!file.isDynamicEntry && file.isEntry) {
1181
- await validate(join(projectRoot, file.fileName));
1182
- }
1183
- } catch (err) {
1184
- if (err instanceof Error) {
1185
- let moduleName = null;
1186
- let errorConfig = null;
1187
- if (err.message.includes("[ERR_MODULE_NOT_FOUND]")) {
1188
- const moduleIdName = file.moduleIds.length >= 2 ? file.moduleIds[file.moduleIds.length - 2] : void 0;
1189
- const fallbackName = file.name.split("/").pop();
1190
- moduleName = moduleIdName ?? fallbackName;
1191
- errorConfig = {
1192
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1193
- messagePrefix: "Mastra wasn't able to build your project. Please add"
1194
- };
1195
- } else if (err.message.includes("Error: No native build was found for ")) {
1196
- moduleName = findNativePackageModule(file.moduleIds);
1197
- errorConfig = {
1198
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1199
- messagePrefix: "We found a binary dependency in your bundle. Please add"
1200
- };
1201
- }
1202
- if (moduleName && errorConfig) {
1203
- const pkgInfo = await getPackageInfo(moduleName);
1204
- const packageName = pkgInfo?.packageJson?.name;
1205
- if (packageName) {
1206
- throwExternalDependencyError({
1207
- errorId: errorConfig.id,
1208
- moduleName,
1209
- packageName,
1210
- messagePrefix: errorConfig.messagePrefix
1211
- });
1212
- } else {
1213
- logger.debug(`Could not determine the module name for file ${file.fileName}`);
1214
- }
1215
- }
1216
- logger.debug(`Error while validating module ${file.fileName}: ${err.message}`);
1217
- }
1572
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1573
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1574
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1218
1575
  }
1576
+ await validateFile(projectRoot, file, {
1577
+ binaryMapData,
1578
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1579
+ logger,
1580
+ workspaceMap
1581
+ });
1219
1582
  }
1220
1583
  return result;
1221
1584
  }
@@ -1247,17 +1610,26 @@ If you think your configuration is valid, please open an issue.`);
1247
1610
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1248
1611
  let index = 0;
1249
1612
  const depsToOptimize = /* @__PURE__ */ new Map();
1613
+ const { externals: customExternals = [] } = bundlerOptions || {};
1614
+ const allExternals = [...GLOBAL_EXTERNALS, ...customExternals];
1250
1615
  logger.info("Analyzing dependencies...");
1616
+ const allUsedExternals = /* @__PURE__ */ new Set();
1251
1617
  for (const entry of entries) {
1252
1618
  const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1253
1619
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1254
1620
  logger,
1255
1621
  sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1256
1622
  workspaceMap,
1257
- projectRoot
1623
+ projectRoot,
1624
+ shouldCheckTransitiveDependencies: isDev
1258
1625
  });
1259
1626
  await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1260
1627
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1628
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1629
+ if (isPartOfExternals) {
1630
+ allUsedExternals.add(dep);
1631
+ continue;
1632
+ }
1261
1633
  if (depsToOptimize.has(dep)) {
1262
1634
  const existingEntry = depsToOptimize.get(dep);
1263
1635
  depsToOptimize.set(dep, {
@@ -1276,14 +1648,13 @@ If you think your configuration is valid, please open an issue.`);
1276
1648
  }
1277
1649
  }
1278
1650
  }
1279
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1651
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1280
1652
  logger.info("Optimizing dependencies...");
1281
- logger.debug(
1282
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1283
- );
1653
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1284
1654
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1285
1655
  bundlerOptions: {
1286
1656
  ...bundlerOptions,
1657
+ externals: allExternals,
1287
1658
  enableEsmShim,
1288
1659
  isDev
1289
1660
  },
@@ -1302,9 +1673,12 @@ If you think your configuration is valid, please open an issue.`);
1302
1673
  },
1303
1674
  logger
1304
1675
  );
1305
- return result;
1676
+ return {
1677
+ ...result,
1678
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1679
+ };
1306
1680
  }
1307
1681
 
1308
- export { aliasHono, analyzeBundle, esbuild, extractMastraOption, getBundlerOptions, getPackageName, getPackageRootPath, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, slash, tsConfigPaths };
1309
- //# sourceMappingURL=chunk-NK3AYZ6D.js.map
1310
- //# sourceMappingURL=chunk-NK3AYZ6D.js.map
1682
+ export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, subpathExternalsResolver, tsConfigPaths };
1683
+ //# sourceMappingURL=chunk-UEFVUIPU.js.map
1684
+ //# sourceMappingURL=chunk-UEFVUIPU.js.map