@mastra/deployer 1.0.0-beta.1 → 1.0.0-beta.10

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 (193) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/dist/arktype-aI7TBD0R-4YXBEQBG.cjs +10 -0
  3. package/dist/arktype-aI7TBD0R-4YXBEQBG.cjs.map +1 -0
  4. package/dist/arktype-aI7TBD0R-OEPFT4G6.js +8 -0
  5. package/dist/arktype-aI7TBD0R-OEPFT4G6.js.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 +8 -0
  27. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  28. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  29. package/dist/build/utils.d.ts +1 -0
  30. package/dist/build/utils.d.ts.map +1 -1
  31. package/dist/bundler/index.cjs +2 -2
  32. package/dist/bundler/index.d.ts +1 -1
  33. package/dist/bundler/index.js +1 -1
  34. package/dist/chunk-2OTEFUER.cjs +69 -0
  35. package/dist/chunk-2OTEFUER.cjs.map +1 -0
  36. package/dist/chunk-5CWPEG6R.js +62 -0
  37. package/dist/chunk-5CWPEG6R.js.map +1 -0
  38. package/dist/chunk-7PLNIFGZ.cjs +8 -0
  39. package/dist/chunk-7PLNIFGZ.cjs.map +1 -0
  40. package/dist/{chunk-IL2VLNIJ.cjs → chunk-BFQ2S5UD.cjs} +13 -23
  41. package/dist/chunk-BFQ2S5UD.cjs.map +1 -0
  42. package/dist/chunk-BTNPI4Z7.cjs +4 -0
  43. package/dist/chunk-BTNPI4Z7.cjs.map +1 -0
  44. package/dist/{chunk-5QFG6SCM.js → chunk-DPDWM7HQ.js} +2 -2
  45. package/dist/chunk-DPDWM7HQ.js.map +1 -0
  46. package/dist/chunk-FBT6QP7J.js +3 -0
  47. package/dist/chunk-FBT6QP7J.js.map +1 -0
  48. package/dist/chunk-GD2TGMBP.cjs +95 -0
  49. package/dist/chunk-GD2TGMBP.cjs.map +1 -0
  50. package/dist/chunk-ID3HN3BH.cjs +16 -0
  51. package/dist/chunk-ID3HN3BH.cjs.map +1 -0
  52. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  53. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  54. package/dist/chunk-MMUE22EL.js +159 -0
  55. package/dist/chunk-MMUE22EL.js.map +1 -0
  56. package/dist/{chunk-C74EXQSL.cjs → chunk-MUWNMVNL.cjs} +570 -194
  57. package/dist/chunk-MUWNMVNL.cjs.map +1 -0
  58. package/dist/chunk-N5TMJUIR.js +14 -0
  59. package/dist/chunk-N5TMJUIR.js.map +1 -0
  60. package/dist/chunk-P4L6VIHY.js +93 -0
  61. package/dist/chunk-P4L6VIHY.js.map +1 -0
  62. package/dist/chunk-Q2YGWEXY.js +6 -0
  63. package/dist/chunk-Q2YGWEXY.js.map +1 -0
  64. package/dist/{chunk-WBAWUM7Z.js → chunk-RBPCXFN7.js} +6 -5
  65. package/dist/chunk-RBPCXFN7.js.map +1 -0
  66. package/dist/{chunk-AQAOWLJJ.cjs → chunk-SS22TD6R.cjs} +16 -15
  67. package/dist/chunk-SS22TD6R.cjs.map +1 -0
  68. package/dist/{chunk-H3LLQ2MW.js → chunk-TK2CCU7I.js} +553 -177
  69. package/dist/chunk-TK2CCU7I.js.map +1 -0
  70. package/dist/chunk-TXKETRIN.cjs +162 -0
  71. package/dist/chunk-TXKETRIN.cjs.map +1 -0
  72. package/dist/{chunk-OFUWEVGF.js → chunk-UQZGTSBF.js} +6 -15
  73. package/dist/chunk-UQZGTSBF.js.map +1 -0
  74. package/dist/{chunk-TDWIGFVF.cjs → chunk-X4TNUYQL.cjs} +15 -14
  75. package/dist/chunk-X4TNUYQL.cjs.map +1 -0
  76. package/dist/{chunk-HQJR52M7.js → chunk-X5QU7B2W.js} +5 -4
  77. package/dist/chunk-X5QU7B2W.js.map +1 -0
  78. package/dist/default-u_dwuiYb-65M4BHAA.js +3 -0
  79. package/dist/default-u_dwuiYb-65M4BHAA.js.map +1 -0
  80. package/dist/default-u_dwuiYb-PWN6FHC6.cjs +9 -0
  81. package/dist/default-u_dwuiYb-PWN6FHC6.cjs.map +1 -0
  82. package/dist/deploy/log.d.ts +1 -1
  83. package/dist/deploy/log.d.ts.map +1 -1
  84. package/dist/effect-QlVUlMFu-2ADPKIDF.cjs +17 -0
  85. package/dist/effect-QlVUlMFu-2ADPKIDF.cjs.map +1 -0
  86. package/dist/effect-QlVUlMFu-FD73M3OO.js +15 -0
  87. package/dist/effect-QlVUlMFu-FD73M3OO.js.map +1 -0
  88. package/dist/esm-BLVTLTJW.js +1289 -0
  89. package/dist/esm-BLVTLTJW.js.map +1 -0
  90. package/dist/esm-E3NUCNVN.cjs +1336 -0
  91. package/dist/esm-E3NUCNVN.cjs.map +1 -0
  92. package/dist/index.cjs +12 -12
  93. package/dist/index.js +4 -4
  94. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  95. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  96. package/dist/server/index.cjs +2336 -10512
  97. package/dist/server/index.cjs.map +1 -1
  98. package/dist/server/index.d.ts +3 -12
  99. package/dist/server/index.d.ts.map +1 -1
  100. package/dist/server/index.js +2327 -10503
  101. package/dist/server/index.js.map +1 -1
  102. package/dist/services/index.cjs +4 -4
  103. package/dist/services/index.js +1 -1
  104. package/dist/sury-CWZTCd75-K3FHMZF5.cjs +17 -0
  105. package/dist/sury-CWZTCd75-K3FHMZF5.cjs.map +1 -0
  106. package/dist/sury-CWZTCd75-Y2GURJ6K.js +15 -0
  107. package/dist/sury-CWZTCd75-Y2GURJ6K.js.map +1 -0
  108. package/dist/typebox-Dei93FPO-2WP4NOYD.js +8 -0
  109. package/dist/typebox-Dei93FPO-2WP4NOYD.js.map +1 -0
  110. package/dist/typebox-Dei93FPO-WTXAW2LA.cjs +10 -0
  111. package/dist/typebox-Dei93FPO-WTXAW2LA.cjs.map +1 -0
  112. package/dist/valibot--1zFm7rT-HMTCRBB3.cjs +17 -0
  113. package/dist/valibot--1zFm7rT-HMTCRBB3.cjs.map +1 -0
  114. package/dist/valibot--1zFm7rT-VGFBTDTW.js +15 -0
  115. package/dist/valibot--1zFm7rT-VGFBTDTW.js.map +1 -0
  116. package/dist/valibot-D_HTw1Gn-ILCWWLE4.cjs +45 -0
  117. package/dist/valibot-D_HTw1Gn-ILCWWLE4.cjs.map +1 -0
  118. package/dist/valibot-D_HTw1Gn-LLCGNU3W.js +43 -0
  119. package/dist/valibot-D_HTw1Gn-LLCGNU3W.js.map +1 -0
  120. package/dist/validator/custom-resolver.cjs +20 -12
  121. package/dist/validator/custom-resolver.cjs.map +1 -1
  122. package/dist/validator/custom-resolver.d.ts.map +1 -1
  123. package/dist/validator/custom-resolver.js +18 -10
  124. package/dist/validator/custom-resolver.js.map +1 -1
  125. package/dist/validator/validate.d.ts +15 -1
  126. package/dist/validator/validate.d.ts.map +1 -1
  127. package/dist/zod-Bwrt9trS-XCRGYQVE.js +29 -0
  128. package/dist/zod-Bwrt9trS-XCRGYQVE.js.map +1 -0
  129. package/dist/zod-Bwrt9trS-XDMWF3NW.cjs +31 -0
  130. package/dist/zod-Bwrt9trS-XDMWF3NW.cjs.map +1 -0
  131. package/dist/zod-DSgpEGAE-TKBHSSLS.js +37 -0
  132. package/dist/zod-DSgpEGAE-TKBHSSLS.js.map +1 -0
  133. package/dist/zod-DSgpEGAE-ZWQMF6SS.cjs +39 -0
  134. package/dist/zod-DSgpEGAE-ZWQMF6SS.cjs.map +1 -0
  135. package/package.json +18 -21
  136. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  137. package/dist/chunk-5QFG6SCM.js.map +0 -1
  138. package/dist/chunk-AQAOWLJJ.cjs.map +0 -1
  139. package/dist/chunk-C74EXQSL.cjs.map +0 -1
  140. package/dist/chunk-H3LLQ2MW.js.map +0 -1
  141. package/dist/chunk-HQJR52M7.js.map +0 -1
  142. package/dist/chunk-IL2VLNIJ.cjs.map +0 -1
  143. package/dist/chunk-OFUWEVGF.js.map +0 -1
  144. package/dist/chunk-TDWIGFVF.cjs.map +0 -1
  145. package/dist/chunk-WBAWUM7Z.js.map +0 -1
  146. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  147. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  148. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  149. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  150. package/dist/server/handlers/auth/index.d.ts +0 -11
  151. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  152. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -20
  153. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  154. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  155. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  156. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -232
  157. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  158. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  159. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  160. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  161. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  162. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  163. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  164. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  165. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  166. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  167. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  168. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  169. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  170. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -15
  171. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  172. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  173. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  174. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  175. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  176. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  177. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  178. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -302
  179. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  180. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  181. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  182. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  183. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  184. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  185. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  186. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  187. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  188. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  189. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  190. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  191. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  192. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  193. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
@@ -1,28 +1,30 @@
1
1
  'use strict';
2
2
 
3
+ var chunk2OTEFUER_cjs = require('./chunk-2OTEFUER.cjs');
3
4
  var babel = require('@babel/core');
4
5
  var fs = require('fs');
5
6
  var promises = require('fs/promises');
6
7
  var path2 = require('path');
7
8
  var child_process = require('child_process');
8
- var localPkg = require('local-pkg');
9
- var url = require('url');
10
9
  var rollup = require('rollup');
11
10
  var originalEsbuild = require('rollup-plugin-esbuild');
12
11
  var commonjs = require('@rollup/plugin-commonjs');
13
12
  var resolveFrom2 = require('resolve-from');
13
+ var stripJsonComments = require('strip-json-comments');
14
14
  var typescriptPaths = require('typescript-paths');
15
15
  var rollupPlugin = require('@optimize-lodash/rollup-plugin');
16
16
  var json = require('@rollup/plugin-json');
17
+ var url = require('url');
17
18
  var pkg = require('empathic/package');
18
19
  var findWorkspaces = require('find-workspaces');
19
20
  var logger = require('@mastra/core/logger');
20
21
  var virtual = require('@rollup/plugin-virtual');
21
22
  var module$1 = require('module');
22
23
  var nodeResolve = require('@rollup/plugin-node-resolve');
23
- var esmShim = require('@rollup/plugin-esm-shim');
24
+ var originalEsmShim = require('@rollup/plugin-esm-shim');
24
25
  var posix = require('path/posix');
25
26
  var resolve = require('resolve.exports');
27
+ var localPkg = require('local-pkg');
26
28
  var error = require('@mastra/core/error');
27
29
 
28
30
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -51,90 +53,26 @@ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
51
53
  var originalEsbuild__default = /*#__PURE__*/_interopDefault(originalEsbuild);
52
54
  var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
53
55
  var resolveFrom2__default = /*#__PURE__*/_interopDefault(resolveFrom2);
56
+ var stripJsonComments__default = /*#__PURE__*/_interopDefault(stripJsonComments);
54
57
  var json__default = /*#__PURE__*/_interopDefault(json);
55
58
  var pkg__namespace = /*#__PURE__*/_interopNamespace(pkg);
56
59
  var virtual__default = /*#__PURE__*/_interopDefault(virtual);
57
60
  var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve);
58
- var esmShim__default = /*#__PURE__*/_interopDefault(esmShim);
61
+ var originalEsmShim__default = /*#__PURE__*/_interopDefault(originalEsmShim);
59
62
  var resolve__namespace = /*#__PURE__*/_interopNamespace(resolve);
60
63
 
61
- // src/build/analyze.ts
62
- function getPackageName(id) {
63
- const parts = id.split("/");
64
- if (id.startsWith("@")) {
65
- return parts.slice(0, 2).join("/");
64
+ var ValidationError = class extends Error {
65
+ type;
66
+ stack;
67
+ constructor(args) {
68
+ super(args.message);
69
+ this.type = args.type;
70
+ this.stack = args.stack;
66
71
  }
67
- return parts[0];
68
- }
69
- async function getPackageRootPath(packageName, parentPath) {
70
- let rootPath;
71
- try {
72
- let options = void 0;
73
- if (parentPath) {
74
- if (!parentPath.startsWith("file://")) {
75
- parentPath = url.pathToFileURL(parentPath).href;
76
- }
77
- options = {
78
- paths: [parentPath]
79
- };
80
- }
81
- const pkg2 = await localPkg.getPackageInfo(packageName, options);
82
- rootPath = pkg2?.rootPath ?? null;
83
- } catch (e) {
84
- rootPath = null;
85
- }
86
- return rootPath;
87
- }
88
- function getCompiledDepCachePath(rootPath, packageName) {
89
- return slash(path2.join(rootPath, "node_modules", ".cache", packageName));
90
- }
91
- function slash(path3) {
92
- const isExtendedLengthPath = path3.startsWith("\\\\?\\");
93
- if (isExtendedLengthPath) {
94
- return path3;
95
- }
96
- return path3.replaceAll("\\", "/");
97
- }
98
- function rollupSafeName(name, rootDir) {
99
- const rel = path2.relative(rootDir, name);
100
- let entry = slash(rel);
101
- entry = entry.replace(/^(\.\.\/)+/, "");
102
- entry = entry.replace(/^\/+/, "");
103
- entry = entry.replace(/^[A-Za-z]:\//, "");
104
- if (!entry) {
105
- entry = slash(path2.basename(name));
106
- }
107
- return entry;
108
- }
109
- var NATIVE_BINDING_LOADERS = [
110
- "node-gyp-build",
111
- "prebuild-install",
112
- "bindings",
113
- "node-addon-api",
114
- "node-pre-gyp",
115
- "nan"
116
- // Native Abstractions for Node.js
117
- ];
118
- function findNativePackageModule(moduleIds) {
119
- return moduleIds.find((id) => {
120
- if (id.startsWith("\0")) {
121
- return false;
122
- }
123
- if (!id.includes("/node_modules/")) {
124
- return false;
125
- }
126
- for (const loader of NATIVE_BINDING_LOADERS) {
127
- if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {
128
- return false;
129
- }
130
- }
131
- return true;
132
- });
133
- }
134
-
135
- // src/validator/validate.ts
72
+ };
136
73
  function spawn(command, args = [], options = {}) {
137
74
  return new Promise((resolve2, reject) => {
75
+ let validationError = null;
138
76
  const childProcess = child_process.spawn(command, args, {
139
77
  // stdio: 'inherit',
140
78
  ...options
@@ -144,28 +82,63 @@ function spawn(command, args = [], options = {}) {
144
82
  });
145
83
  let stderr = "";
146
84
  childProcess.stderr?.on("data", (message) => {
147
- stderr += message;
85
+ try {
86
+ validationError = JSON.parse(message.toString());
87
+ } catch {
88
+ stderr += message;
89
+ }
148
90
  });
149
91
  childProcess.on("close", (code) => {
150
92
  if (code === 0) {
151
93
  resolve2();
152
94
  } else {
153
- reject(new Error(stderr));
95
+ if (validationError) {
96
+ reject(new ValidationError(validationError));
97
+ } else {
98
+ reject(new Error(stderr));
99
+ }
154
100
  }
155
101
  });
156
102
  });
157
103
  }
158
- function validate(file) {
104
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation }) {
105
+ let prefixCode = "";
106
+ if (injectESMShim) {
107
+ prefixCode = `import { fileURLToPath } from 'url';
108
+ import { dirname } from 'path';
109
+
110
+ globalThis.__filename = fileURLToPath(import.meta.url);
111
+ globalThis.__dirname = dirname(__filename);
112
+ `;
113
+ }
114
+ function errorHandler(err) {
115
+ console.error(
116
+ JSON.stringify({
117
+ type: err.name,
118
+ message: err.message,
119
+ stack: err.stack
120
+ })
121
+ );
122
+ process.exit(1);
123
+ }
159
124
  return spawn(
160
- "node",
125
+ process.execPath,
161
126
  [
162
127
  "--import",
163
128
  undefined("@mastra/deployer/loader"),
164
129
  "--input-type=module",
130
+ "--enable-source-maps",
165
131
  "-e",
166
- `import('file://${slash(file)}')`
132
+ `${prefixCode};import('file://${chunk2OTEFUER_cjs.slash(file)}').catch(err => {
133
+ ${errorHandler.toString()}
134
+ errorHandler(err);
135
+ })`.replaceAll(/\n/g, "")
167
136
  ],
168
137
  {
138
+ env: {
139
+ ...process.env,
140
+ MODULE_MAP: `${moduleResolveMapLocation}`
141
+ },
169
142
  cwd: path2.dirname(file)
170
143
  }
171
144
  );
@@ -260,29 +233,90 @@ function esbuild(options = {}) {
260
233
  });
261
234
  }
262
235
  var PLUGIN_NAME = "tsconfig-paths";
236
+ function hasPaths(tsConfigPath) {
237
+ try {
238
+ const content = fs__default.default.readFileSync(tsConfigPath, "utf8");
239
+ const config = JSON.parse(stripJsonComments__default.default(content));
240
+ return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
241
+ } catch {
242
+ return false;
243
+ }
244
+ }
263
245
  function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
264
- let handler;
246
+ const handlerCache = /* @__PURE__ */ new Map();
247
+ function findTsConfigForFile(filePath) {
248
+ let currentDir = path2__namespace.default.dirname(filePath);
249
+ const root = path2__namespace.default.parse(currentDir).root;
250
+ while (currentDir !== root) {
251
+ const tsConfigPath2 = path2__namespace.default.join(currentDir, "tsconfig.json");
252
+ if (fs__default.default.existsSync(tsConfigPath2)) {
253
+ if (hasPaths(tsConfigPath2)) {
254
+ return tsConfigPath2;
255
+ }
256
+ }
257
+ const tsConfigBasePath = path2__namespace.default.join(currentDir, "tsconfig.base.json");
258
+ if (fs__default.default.existsSync(tsConfigBasePath)) {
259
+ if (hasPaths(tsConfigBasePath)) {
260
+ return tsConfigBasePath;
261
+ }
262
+ }
263
+ currentDir = path2__namespace.default.dirname(currentDir);
264
+ }
265
+ return null;
266
+ }
267
+ function getHandlerForFile(filePath) {
268
+ if (tsConfigPath && typeof tsConfigPath === "string") {
269
+ if (!handlerCache.has(tsConfigPath)) {
270
+ handlerCache.set(
271
+ tsConfigPath,
272
+ typescriptPaths.createHandler({
273
+ log: () => {
274
+ },
275
+ tsConfigPath,
276
+ respectCoreModule,
277
+ falllback: (moduleName) => fs__default.default.existsSync(moduleName)
278
+ })
279
+ );
280
+ }
281
+ return handlerCache.get(tsConfigPath);
282
+ }
283
+ const configPath = findTsConfigForFile(filePath);
284
+ if (!configPath) {
285
+ return null;
286
+ }
287
+ if (!handlerCache.has(configPath)) {
288
+ handlerCache.set(
289
+ configPath,
290
+ typescriptPaths.createHandler({
291
+ log: () => {
292
+ },
293
+ tsConfigPath: configPath,
294
+ respectCoreModule,
295
+ falllback: (moduleName) => fs__default.default.existsSync(moduleName)
296
+ })
297
+ );
298
+ }
299
+ return handlerCache.get(configPath);
300
+ }
301
+ function resolveAlias(request, importer) {
302
+ const dynamicHandler = getHandlerForFile(importer);
303
+ if (!dynamicHandler) {
304
+ return null;
305
+ }
306
+ const resolved = dynamicHandler(request, path2.normalize(importer));
307
+ return resolved;
308
+ }
265
309
  return {
266
310
  name: PLUGIN_NAME,
267
- buildStart() {
268
- handler = typescriptPaths.createHandler({
269
- log: () => {
270
- },
271
- tsConfigPath,
272
- respectCoreModule,
273
- falllback: (moduleName) => fs__default.default.existsSync(moduleName)
274
- });
275
- return;
276
- },
277
311
  async resolveId(request, importer, options) {
278
- if (!importer || request.startsWith("\0")) {
312
+ if (!importer || request.startsWith("\0") || importer.charCodeAt(0) === 0) {
279
313
  return null;
280
314
  }
281
- const moduleName = handler?.(request, path2.normalize(importer));
315
+ const moduleName = resolveAlias(request, importer);
282
316
  if (!moduleName) {
283
317
  let importerMeta = {};
284
- const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
285
- if (!resolved) {
318
+ const resolved2 = await this.resolve(request, importer, { skipSelf: true, ...options });
319
+ if (!resolved2) {
286
320
  return null;
287
321
  }
288
322
  if (localResolve) {
@@ -290,37 +324,42 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
290
324
  importerMeta = importerInfo?.meta || {};
291
325
  if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
292
326
  return {
293
- ...resolved,
327
+ ...resolved2,
294
328
  external: !request.startsWith("hono/") && request !== "hono"
295
329
  };
296
330
  }
297
331
  }
298
332
  return {
299
- ...resolved,
333
+ ...resolved2,
300
334
  meta: {
301
- ...resolved.meta || {},
335
+ ...resolved2.meta || {},
302
336
  ...importerMeta
303
337
  }
304
338
  };
305
339
  }
306
340
  if (!path2__namespace.default.extname(moduleName)) {
307
- const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
308
- if (!resolved) {
341
+ const resolved2 = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
342
+ if (!resolved2) {
309
343
  return null;
310
344
  }
311
345
  return {
312
- ...resolved,
346
+ ...resolved2,
313
347
  meta: {
314
- ...resolved.meta,
348
+ ...resolved2.meta,
315
349
  [PLUGIN_NAME]: {
316
350
  resolved: true
317
351
  }
318
352
  }
319
353
  };
320
354
  }
355
+ const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
356
+ if (!resolved) {
357
+ return null;
358
+ }
321
359
  return {
322
- id: moduleName,
360
+ ...resolved,
323
361
  meta: {
362
+ ...resolved.meta,
324
363
  [PLUGIN_NAME]: {
325
364
  resolved: true
326
365
  }
@@ -481,7 +520,7 @@ async function extractMastraOption(name, entryFile, transformer, outputDir, logg
481
520
  const configPath = `${outputDir}/${name}-config.mjs`;
482
521
  return {
483
522
  bundleOutput: output,
484
- getConfig: () => import(`file:${configPath}`).then((m) => m[name])
523
+ getConfig: () => import(url.pathToFileURL(configPath).href).then((m) => m[name])
485
524
  };
486
525
  }
487
526
  return null;
@@ -539,7 +578,7 @@ async function getWorkspaceInformation({
539
578
  mastraEntryFile
540
579
  }) {
541
580
  const closestPkgJson = pkg__namespace.up({ cwd: path2.dirname(mastraEntryFile) });
542
- const location = closestPkgJson ? path2.dirname(slash(closestPkgJson)) : slash(process.cwd());
581
+ const location = closestPkgJson ? path2.dirname(chunk2OTEFUER_cjs.slash(closestPkgJson)) : chunk2OTEFUER_cjs.slash(process.cwd());
543
582
  const workspaces = await findWorkspaces.findWorkspaces(dir, { cache: workspacesCache });
544
583
  const _workspaceMap = new Map(
545
584
  workspaces?.map((workspace) => [
@@ -655,7 +694,7 @@ var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
655
694
 
656
695
  // src/build/analyze/analyzeEntry.ts
657
696
  function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
658
- const normalizedMastraEntry = slash(mastraEntry);
697
+ const normalizedMastraEntry = chunk2OTEFUER_cjs.slash(mastraEntry);
659
698
  let virtualPlugin = null;
660
699
  if (isVirtualFile) {
661
700
  virtualPlugin = virtual__default.default({
@@ -674,7 +713,7 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
674
713
  name: "custom-alias-resolver",
675
714
  resolveId(id) {
676
715
  if (id === "#server") {
677
- return slash(url.fileURLToPath(undefined("@mastra/deployer/server")));
716
+ return chunk2OTEFUER_cjs.slash(url.fileURLToPath(undefined("@mastra/deployer/server")));
678
717
  }
679
718
  if (id === "#mastra") {
680
719
  return normalizedMastraEntry;
@@ -699,7 +738,8 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
699
738
  return plugins;
700
739
  }
701
740
  async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
702
- logger: logger$1
741
+ logger: logger$1,
742
+ shouldCheckTransitiveDependencies
703
743
  }) {
704
744
  const depsToOptimize = /* @__PURE__ */ new Map();
705
745
  if (!output.facadeModuleId) {
@@ -709,21 +749,25 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
709
749
  }
710
750
  let entryRootPath = projectRoot;
711
751
  if (!output.facadeModuleId.startsWith("\0virtual:")) {
712
- entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
752
+ entryRootPath = await chunk2OTEFUER_cjs.getPackageRootPath(output.facadeModuleId) || projectRoot;
713
753
  }
714
754
  for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
715
- if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
755
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
716
756
  continue;
717
757
  }
718
- const pkgName = getPackageName(dependency);
758
+ const pkgName = chunk2OTEFUER_cjs.getPackageName(dependency);
719
759
  let rootPath = null;
720
760
  let isWorkspace = false;
721
761
  if (pkgName) {
722
- rootPath = await getPackageRootPath(dependency, entryRootPath);
762
+ rootPath = await chunk2OTEFUER_cjs.getPackageRootPath(dependency, entryRootPath);
723
763
  isWorkspace = workspaceMap.has(pkgName);
724
764
  }
725
- const normalizedRootPath = rootPath ? slash(rootPath) : null;
726
- depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace });
765
+ const normalizedRootPath = rootPath ? chunk2OTEFUER_cjs.slash(rootPath) : null;
766
+ depsToOptimize.set(dependency, {
767
+ exports: bindings,
768
+ rootPath: normalizedRootPath,
769
+ isWorkspace
770
+ });
727
771
  }
728
772
  async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
729
773
  if (currentDepth >= maxDepth) {
@@ -767,12 +811,18 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
767
811
  await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
768
812
  }
769
813
  }
770
- await checkTransitiveDependencies(initialDepsToOptimize);
814
+ if (shouldCheckTransitiveDependencies) {
815
+ await checkTransitiveDependencies(initialDepsToOptimize);
816
+ }
771
817
  const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
772
818
  if (dynamicImports.length) {
773
819
  for (const dynamicImport of dynamicImports) {
774
820
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
775
- depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
821
+ depsToOptimize.set(dynamicImport, {
822
+ exports: ["*"],
823
+ rootPath: null,
824
+ isWorkspace: false
825
+ });
776
826
  }
777
827
  }
778
828
  }
@@ -786,13 +836,14 @@ async function analyzeEntry({
786
836
  sourcemapEnabled,
787
837
  workspaceMap,
788
838
  projectRoot,
789
- initialDepsToOptimize = /* @__PURE__ */ new Map()
839
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
790
840
  // used to avoid infinite recursion
841
+ shouldCheckTransitiveDependencies = false
791
842
  }) {
792
843
  const optimizerBundler = await rollup.rollup({
793
844
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
794
845
  input: isVirtualFile ? "#entry" : entry,
795
- treeshake: "smallest",
846
+ treeshake: false,
796
847
  preserveSymlinks: true,
797
848
  plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
798
849
  external: DEPS_TO_IGNORE
@@ -808,7 +859,8 @@ async function analyzeEntry({
808
859
  projectRoot,
809
860
  initialDepsToOptimize,
810
861
  {
811
- logger
862
+ logger,
863
+ shouldCheckTransitiveDependencies
812
864
  }
813
865
  );
814
866
  return {
@@ -819,6 +871,27 @@ async function analyzeEntry({
819
871
  }
820
872
  };
821
873
  }
874
+ var FilenameDeclarationRegex = /(?:const|let|var)\s+__filename/;
875
+ var DirnameDeclarationRegex = /(?:const|let|var)\s+__dirname/;
876
+ function esmShim() {
877
+ const original = originalEsmShim__default.default();
878
+ return {
879
+ name: "esm-shim",
880
+ renderChunk(code, chunk, opts, meta) {
881
+ const hasFilename = code.includes("__filename");
882
+ const hasDirname = code.includes("__dirname");
883
+ const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);
884
+ const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);
885
+ if (userDeclaredFilename || userDeclaredDirname) {
886
+ return null;
887
+ }
888
+ if (typeof original.renderChunk === "function") {
889
+ return original.renderChunk.call(this, code, chunk, opts, meta);
890
+ }
891
+ return null;
892
+ }
893
+ };
894
+ }
822
895
  function aliasHono() {
823
896
  return {
824
897
  name: "hono-alias",
@@ -831,8 +904,116 @@ function aliasHono() {
831
904
  }
832
905
  };
833
906
  }
907
+ function nodeGypDetector() {
908
+ const modulesToTrack = /* @__PURE__ */ new Set();
909
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
910
+ return {
911
+ name: "node-gyp-build-detector",
912
+ moduleParsed(info) {
913
+ if (!info.meta?.commonjs?.requires?.length) {
914
+ return;
915
+ }
916
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
917
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
918
+ );
919
+ if (!hasNodeGypBuild) {
920
+ return;
921
+ }
922
+ modulesToTrack.add(info.id);
923
+ modulesToTrackPackageInfo.set(info.id, localPkg.getPackageInfo(info.id));
924
+ },
925
+ async generateBundle(options, bundle) {
926
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
927
+ for (const [fileName, chunk] of Object.entries(bundle)) {
928
+ if (chunk.type === "chunk") {
929
+ for (const moduleId of chunk.moduleIds) {
930
+ if (modulesToTrackPackageInfo.has(moduleId)) {
931
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
932
+ if (!binaryMapByChunk.has(fileName)) {
933
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
934
+ }
935
+ if (pkgInfo?.packageJson?.name) {
936
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
937
+ }
938
+ }
939
+ }
940
+ }
941
+ }
942
+ const binaryMapJson = Object.fromEntries(
943
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
944
+ );
945
+ this.emitFile({
946
+ type: "asset",
947
+ name: "binary-map.json",
948
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
949
+ });
950
+ }
951
+ };
952
+ }
953
+
954
+ // src/build/plugins/subpath-externals-resolver.ts
955
+ function subpathExternalsResolver(externals) {
956
+ return {
957
+ name: "subpath-externals-resolver",
958
+ resolveId(id) {
959
+ if (id.startsWith(".") || id.startsWith("/")) {
960
+ return null;
961
+ }
962
+ const isPartOfExternals = externals.some((external) => chunk2OTEFUER_cjs.isDependencyPartOfPackage(id, external));
963
+ if (isPartOfExternals) {
964
+ return {
965
+ id,
966
+ external: true
967
+ };
968
+ }
969
+ }
970
+ };
971
+ }
972
+ function moduleResolveMap(externals, projectRoot) {
973
+ const importMap = /* @__PURE__ */ new Map();
974
+ return {
975
+ name: "module-resolve-map",
976
+ moduleParsed(info) {
977
+ if (info.importedIds.length === 0 || !info.id) {
978
+ return;
979
+ }
980
+ for (const importedId of info.importedIds) {
981
+ for (const external of externals) {
982
+ if (chunk2OTEFUER_cjs.isDependencyPartOfPackage(importedId, external)) {
983
+ importMap.set(external, info.id);
984
+ }
985
+ }
986
+ }
987
+ },
988
+ async generateBundle(options, bundle) {
989
+ const resolveMap = /* @__PURE__ */ new Map();
990
+ for (const [fileName, chunk] of Object.entries(bundle)) {
991
+ if (chunk.type === "chunk") {
992
+ for (const [external, resolvedFrom] of importMap) {
993
+ if (chunk.moduleIds.includes(resolvedFrom)) {
994
+ const fullPath = url.pathToFileURL(chunk2OTEFUER_cjs.slash(path2.join(projectRoot, fileName))).toString();
995
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
996
+ innerMap.set(external, url.pathToFileURL(chunk2OTEFUER_cjs.slash(resolvedFrom)).toString());
997
+ resolveMap.set(fullPath, innerMap);
998
+ }
999
+ }
1000
+ }
1001
+ }
1002
+ const resolveMapJson = Object.fromEntries(
1003
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
1004
+ );
1005
+ this.emitFile({
1006
+ type: "asset",
1007
+ name: "module-resolve-map.json",
1008
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
1009
+ });
1010
+ }
1011
+ };
1012
+ }
1013
+
1014
+ // src/build/analyze/bundleExternals.ts
834
1015
  function prepareEntryFileName(name, rootDir) {
835
- return rollupSafeName(name, rootDir);
1016
+ return chunk2OTEFUER_cjs.rollupSafeName(name, rootDir);
836
1017
  }
837
1018
  function createVirtualDependencies(depsToOptimize, {
838
1019
  projectRoot,
@@ -882,7 +1063,7 @@ function createVirtualDependencies(depsToOptimize, {
882
1063
  continue;
883
1064
  }
884
1065
  const fileName = posix.basename(currentDepPath.name);
885
- const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir);
1066
+ const entryName = prepareEntryFileName(chunk2OTEFUER_cjs.getCompiledDepCachePath(rootPath, fileName), rootDir);
886
1067
  fileNameToDependencyMap.set(entryName, dep);
887
1068
  optimizedDependencyEntries.set(dep, {
888
1069
  ...currentDepPath,
@@ -896,13 +1077,14 @@ async function getInputPlugins2(virtualDependencies, {
896
1077
  transpilePackages,
897
1078
  workspaceMap,
898
1079
  bundlerOptions,
899
- rootDir
1080
+ rootDir,
1081
+ externals
900
1082
  }) {
901
1083
  const transpilePackagesMap = /* @__PURE__ */ new Map();
902
1084
  for (const pkg2 of transpilePackages) {
903
- const dir = await getPackageRootPath(pkg2);
1085
+ const dir = await chunk2OTEFUER_cjs.getPackageRootPath(pkg2);
904
1086
  if (dir) {
905
- transpilePackagesMap.set(pkg2, slash(dir));
1087
+ transpilePackagesMap.set(pkg2, chunk2OTEFUER_cjs.slash(dir));
906
1088
  } else {
907
1089
  transpilePackagesMap.set(pkg2, workspaceMap.get(pkg2)?.location ?? pkg2);
908
1090
  }
@@ -917,6 +1099,7 @@ async function getInputPlugins2(virtualDependencies, {
917
1099
  {}
918
1100
  )
919
1101
  ),
1102
+ subpathExternalsResolver(externals),
920
1103
  transpilePackagesMap.size ? esbuild({
921
1104
  format: "esm",
922
1105
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -945,7 +1128,8 @@ async function getInputPlugins2(virtualDependencies, {
945
1128
  if (!resolvedPath) {
946
1129
  resolvedPath = pkgJson.main ?? "index.js";
947
1130
  }
948
- return await this.resolve(path2__namespace.posix.join(packageRootPath, resolvedPath), importer, options);
1131
+ const resolved = await this.resolve(path2__namespace.posix.join(packageRootPath, resolvedPath), importer, options);
1132
+ return resolved;
949
1133
  }
950
1134
  } : null,
951
1135
  rollupPlugin.optimizeLodashImports({
@@ -960,10 +1144,12 @@ async function getInputPlugins2(virtualDependencies, {
960
1144
  preferBuiltins: true,
961
1145
  exportConditions: ["node"]
962
1146
  }),
963
- bundlerOptions.isDev ? esmShim__default.default() : null,
1147
+ bundlerOptions.isDev ? esmShim() : null,
964
1148
  // hono is imported from deployer, so we need to resolve from here instead of the project root
965
1149
  aliasHono(),
966
1150
  json__default.default(),
1151
+ nodeGypDetector(),
1152
+ moduleResolveMap(externals, rootDir),
967
1153
  {
968
1154
  name: "not-found-resolver",
969
1155
  resolveId: {
@@ -1021,12 +1207,13 @@ async function buildExternalDependencies(virtualDependencies, {
1021
1207
  {}
1022
1208
  ),
1023
1209
  external: externals,
1024
- treeshake: "safest",
1210
+ treeshake: bundlerOptions.isDev ? false : "safest",
1025
1211
  plugins: getInputPlugins2(virtualDependencies, {
1026
1212
  transpilePackages: packagesToTranspile,
1027
1213
  workspaceMap,
1028
1214
  bundlerOptions,
1029
- rootDir
1215
+ rootDir,
1216
+ externals
1030
1217
  })
1031
1218
  });
1032
1219
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
@@ -1034,6 +1221,8 @@ async function buildExternalDependencies(virtualDependencies, {
1034
1221
  format: "esm",
1035
1222
  dir: rootDir,
1036
1223
  entryFileNames: "[name].mjs",
1224
+ // used to get the filename of the actual error
1225
+ sourcemap: true,
1037
1226
  /**
1038
1227
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1039
1228
  * So we want to write them to the `.mastra/output` folder as well.
@@ -1042,9 +1231,9 @@ async function buildExternalDependencies(virtualDependencies, {
1042
1231
  if (bundlerOptions.isDev) {
1043
1232
  const importedFromPackages = /* @__PURE__ */ new Set();
1044
1233
  for (const moduleId of chunkInfo.moduleIds) {
1045
- const normalized = slash(moduleId);
1234
+ const normalized = chunk2OTEFUER_cjs.slash(moduleId);
1046
1235
  for (const [pkgName, pkgInfo] of workspaceMap.entries()) {
1047
- const location = slash(pkgInfo.location);
1236
+ const location = chunk2OTEFUER_cjs.slash(pkgInfo.location);
1048
1237
  if (normalized.startsWith(location)) {
1049
1238
  importedFromPackages.add(pkgName);
1050
1239
  break;
@@ -1066,11 +1255,12 @@ async function buildExternalDependencies(virtualDependencies, {
1066
1255
  if (importedFromPackages.size === 1) {
1067
1256
  const [pkgName] = importedFromPackages;
1068
1257
  const workspaceLocation = workspaceMap.get(pkgName).location;
1069
- return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
1258
+ return prepareEntryFileName(chunk2OTEFUER_cjs.getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
1070
1259
  }
1071
1260
  }
1072
1261
  return `${outputDirRelative}/[name].mjs`;
1073
1262
  },
1263
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1074
1264
  hoistTransitiveImports: false
1075
1265
  });
1076
1266
  await bundler.close();
@@ -1079,7 +1269,7 @@ async function buildExternalDependencies(virtualDependencies, {
1079
1269
  function findExternalImporter(module, external, allOutputs) {
1080
1270
  const capturedFiles = /* @__PURE__ */ new Set();
1081
1271
  for (const id of module.imports) {
1082
- if (id === external) {
1272
+ if (chunk2OTEFUER_cjs.isDependencyPartOfPackage(id, external)) {
1083
1273
  return module;
1084
1274
  } else {
1085
1275
  if (id.endsWith(".mjs")) {
@@ -1125,7 +1315,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1125
1315
  isDev
1126
1316
  }
1127
1317
  });
1128
- const moduleResolveMap = /* @__PURE__ */ new Map();
1318
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1129
1319
  const filteredChunks = output.filter((o) => o.type === "chunk");
1130
1320
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1131
1321
  for (const external of allExternals) {
@@ -1135,10 +1325,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1135
1325
  const importer = findExternalImporter(o, external, filteredChunks);
1136
1326
  if (importer) {
1137
1327
  const fullPath = path2__namespace.join(workspaceRoot || projectRoot, importer.fileName);
1138
- let innerMap = moduleResolveMap.get(fullPath);
1328
+ let innerMap = moduleResolveMap2.get(fullPath);
1139
1329
  if (!innerMap) {
1140
1330
  innerMap = /* @__PURE__ */ new Map();
1141
- moduleResolveMap.set(fullPath, innerMap);
1331
+ moduleResolveMap2.set(fullPath, innerMap);
1142
1332
  }
1143
1333
  if (importer.moduleIds.length) {
1144
1334
  innerMap.set(
@@ -1150,7 +1340,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1150
1340
  }
1151
1341
  }
1152
1342
  const usedExternals = /* @__PURE__ */ Object.create(null);
1153
- for (const [fullPath, innerMap] of moduleResolveMap) {
1343
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1154
1344
  const innerObj = /* @__PURE__ */ Object.create(null);
1155
1345
  for (const [external, value] of innerMap) {
1156
1346
  innerObj[external] = value;
@@ -1159,6 +1349,108 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1159
1349
  }
1160
1350
  return { output, fileNameToDependencyMap, usedExternals };
1161
1351
  }
1352
+
1353
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1354
+ var UNKNOWN_FUNCTION = "<unknown>";
1355
+ function parse(stackString) {
1356
+ var lines = stackString.split("\n");
1357
+ return lines.reduce(function(stack, line) {
1358
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1359
+ if (parseResult) {
1360
+ stack.push(parseResult);
1361
+ }
1362
+ return stack;
1363
+ }, []);
1364
+ }
1365
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1366
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1367
+ function parseChrome(line) {
1368
+ var parts = chromeRe.exec(line);
1369
+ if (!parts) {
1370
+ return null;
1371
+ }
1372
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1373
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1374
+ var submatch = chromeEvalRe.exec(parts[2]);
1375
+ if (isEval && submatch != null) {
1376
+ parts[2] = submatch[1];
1377
+ parts[3] = submatch[2];
1378
+ parts[4] = submatch[3];
1379
+ }
1380
+ return {
1381
+ file: !isNative ? parts[2] : null,
1382
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1383
+ arguments: isNative ? [parts[2]] : [],
1384
+ lineNumber: parts[3] ? +parts[3] : null,
1385
+ column: parts[4] ? +parts[4] : null
1386
+ };
1387
+ }
1388
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1389
+ function parseWinjs(line) {
1390
+ var parts = winjsRe.exec(line);
1391
+ if (!parts) {
1392
+ return null;
1393
+ }
1394
+ return {
1395
+ file: parts[2],
1396
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1397
+ arguments: [],
1398
+ lineNumber: +parts[3],
1399
+ column: parts[4] ? +parts[4] : null
1400
+ };
1401
+ }
1402
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1403
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1404
+ function parseGecko(line) {
1405
+ var parts = geckoRe.exec(line);
1406
+ if (!parts) {
1407
+ return null;
1408
+ }
1409
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1410
+ var submatch = geckoEvalRe.exec(parts[3]);
1411
+ if (isEval && submatch != null) {
1412
+ parts[3] = submatch[1];
1413
+ parts[4] = submatch[2];
1414
+ parts[5] = null;
1415
+ }
1416
+ return {
1417
+ file: parts[3],
1418
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1419
+ arguments: parts[2] ? parts[2].split(",") : [],
1420
+ lineNumber: parts[4] ? +parts[4] : null,
1421
+ column: parts[5] ? +parts[5] : null
1422
+ };
1423
+ }
1424
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1425
+ function parseJSC(line) {
1426
+ var parts = javaScriptCoreRe.exec(line);
1427
+ if (!parts) {
1428
+ return null;
1429
+ }
1430
+ return {
1431
+ file: parts[3],
1432
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1433
+ arguments: [],
1434
+ lineNumber: +parts[4],
1435
+ column: parts[5] ? +parts[5] : null
1436
+ };
1437
+ }
1438
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1439
+ function parseNode(line) {
1440
+ var parts = nodeRe.exec(line);
1441
+ if (!parts) {
1442
+ return null;
1443
+ }
1444
+ return {
1445
+ file: parts[2],
1446
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1447
+ arguments: [],
1448
+ lineNumber: +parts[3],
1449
+ column: parts[4] ? +parts[4] : null
1450
+ };
1451
+ }
1452
+
1453
+ // src/build/analyze.ts
1162
1454
  function throwExternalDependencyError({
1163
1455
  errorId,
1164
1456
  moduleName,
@@ -1182,6 +1474,110 @@ export const mastra = new Mastra({
1182
1474
  })`
1183
1475
  });
1184
1476
  }
1477
+ function getPackageNameFromBundledModuleName(moduleName) {
1478
+ const chunks = moduleName.split("-");
1479
+ if (!chunks.length) {
1480
+ return moduleName;
1481
+ }
1482
+ if (chunks[0]?.startsWith("@")) {
1483
+ return chunks.slice(0, 2).join("/");
1484
+ }
1485
+ return chunks[0];
1486
+ }
1487
+ function validateError(err, file, {
1488
+ binaryMapData,
1489
+ workspaceMap
1490
+ }) {
1491
+ let moduleName = null;
1492
+ let errorConfig = null;
1493
+ if (err instanceof ValidationError) {
1494
+ const parsedStack = parse(err.stack);
1495
+ if (err.type === "TypeError") {
1496
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1497
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1498
+ if (stacktraceFrame) {
1499
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1500
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(path2.basename(file.name));
1501
+ } else {
1502
+ moduleName = getPackageNameFromBundledModuleName(path2.basename(file.name));
1503
+ }
1504
+ errorConfig = {
1505
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1506
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1507
+ };
1508
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1509
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1510
+ const parentModuleName = getPackageNameFromBundledModuleName(path2.basename(file.name));
1511
+ errorConfig = {
1512
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1513
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1514
+ };
1515
+ if (moduleName === parentModuleName) {
1516
+ return;
1517
+ }
1518
+ }
1519
+ }
1520
+ if (err.message.includes("No native build was found")) {
1521
+ const pkgName = getPackageNameFromBundledModuleName(path2.basename(file.name));
1522
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1523
+ errorConfig = {
1524
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1525
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1526
+ };
1527
+ }
1528
+ if (moduleName && workspaceMap.has(moduleName)) {
1529
+ throw new error.MastraError({
1530
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1531
+ domain: error.ErrorDomain.DEPLOYER,
1532
+ category: error.ErrorCategory.USER,
1533
+ details: {
1534
+ // importFile: moduleName,
1535
+ packageName: moduleName
1536
+ },
1537
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1538
+ Error: ${err.stack}`
1539
+ });
1540
+ }
1541
+ if (errorConfig && moduleName) {
1542
+ throwExternalDependencyError({
1543
+ errorId: errorConfig.id,
1544
+ moduleName,
1545
+ packageName: moduleName,
1546
+ messagePrefix: errorConfig.messagePrefix
1547
+ });
1548
+ }
1549
+ }
1550
+ async function validateFile(root, file, {
1551
+ binaryMapData,
1552
+ moduleResolveMapLocation,
1553
+ logger,
1554
+ workspaceMap
1555
+ }) {
1556
+ try {
1557
+ if (!file.isDynamicEntry && file.isEntry) {
1558
+ await validate(path2.join(root, file.fileName), {
1559
+ moduleResolveMapLocation,
1560
+ injectESMShim: false
1561
+ });
1562
+ }
1563
+ } catch (err) {
1564
+ let errorToHandle = err;
1565
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1566
+ try {
1567
+ await validate(path2.join(root, file.fileName), {
1568
+ moduleResolveMapLocation,
1569
+ injectESMShim: true
1570
+ });
1571
+ errorToHandle = null;
1572
+ } catch (err2) {
1573
+ errorToHandle = err2;
1574
+ }
1575
+ }
1576
+ if (errorToHandle instanceof Error) {
1577
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1578
+ }
1579
+ }
1580
+ }
1185
1581
  async function validateOutput({
1186
1582
  output,
1187
1583
  reverseVirtualReferenceMap,
@@ -1195,60 +1591,30 @@ async function validateOutput({
1195
1591
  externalDependencies: /* @__PURE__ */ new Set(),
1196
1592
  workspaceMap
1197
1593
  };
1198
- await promises.writeFile(path2.join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1199
1594
  for (const deps of Object.values(usedExternals)) {
1200
1595
  for (const dep of Object.keys(deps)) {
1201
1596
  result.externalDependencies.add(dep);
1202
1597
  }
1203
1598
  }
1599
+ let binaryMapData = {};
1600
+ if (fs.existsSync(path2.join(outputDir, "binary-map.json"))) {
1601
+ const binaryMap = await promises.readFile(path2.join(outputDir, "binary-map.json"), "utf-8");
1602
+ binaryMapData = JSON.parse(binaryMap);
1603
+ }
1204
1604
  for (const file of output) {
1205
1605
  if (file.type === "asset") {
1206
1606
  continue;
1207
1607
  }
1208
- try {
1209
- logger.debug(`Validating if ${file.fileName} is a valid module.`);
1210
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1211
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1212
- }
1213
- if (!file.isDynamicEntry && file.isEntry) {
1214
- await validate(path2.join(projectRoot, file.fileName));
1215
- }
1216
- } catch (err) {
1217
- if (err instanceof Error) {
1218
- let moduleName = null;
1219
- let errorConfig = null;
1220
- if (err.message.includes("[ERR_MODULE_NOT_FOUND]")) {
1221
- const moduleIdName = file.moduleIds.length >= 2 ? file.moduleIds[file.moduleIds.length - 2] : void 0;
1222
- const fallbackName = file.name.split("/").pop();
1223
- moduleName = moduleIdName ?? fallbackName;
1224
- errorConfig = {
1225
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1226
- messagePrefix: "Mastra wasn't able to build your project. Please add"
1227
- };
1228
- } else if (err.message.includes("Error: No native build was found for ")) {
1229
- moduleName = findNativePackageModule(file.moduleIds);
1230
- errorConfig = {
1231
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1232
- messagePrefix: "We found a binary dependency in your bundle. Please add"
1233
- };
1234
- }
1235
- if (moduleName && errorConfig) {
1236
- const pkgInfo = await localPkg.getPackageInfo(moduleName);
1237
- const packageName = pkgInfo?.packageJson?.name;
1238
- if (packageName) {
1239
- throwExternalDependencyError({
1240
- errorId: errorConfig.id,
1241
- moduleName,
1242
- packageName,
1243
- messagePrefix: errorConfig.messagePrefix
1244
- });
1245
- } else {
1246
- logger.debug(`Could not determine the module name for file ${file.fileName}`);
1247
- }
1248
- }
1249
- logger.debug(`Error while validating module ${file.fileName}: ${err.message}`);
1250
- }
1608
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1609
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1610
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1251
1611
  }
1612
+ await validateFile(projectRoot, file, {
1613
+ binaryMapData,
1614
+ moduleResolveMapLocation: path2.join(outputDir, "module-resolve-map.json"),
1615
+ logger,
1616
+ workspaceMap
1617
+ });
1252
1618
  }
1253
1619
  return result;
1254
1620
  }
@@ -1280,17 +1646,26 @@ If you think your configuration is valid, please open an issue.`);
1280
1646
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1281
1647
  let index = 0;
1282
1648
  const depsToOptimize = /* @__PURE__ */ new Map();
1649
+ const { externals: customExternals = [] } = bundlerOptions || {};
1650
+ const allExternals = [...GLOBAL_EXTERNALS, ...customExternals];
1283
1651
  logger.info("Analyzing dependencies...");
1652
+ const allUsedExternals = /* @__PURE__ */ new Set();
1284
1653
  for (const entry of entries) {
1285
1654
  const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry);
1286
1655
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1287
1656
  logger,
1288
1657
  sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1289
1658
  workspaceMap,
1290
- projectRoot
1659
+ projectRoot,
1660
+ shouldCheckTransitiveDependencies: isDev
1291
1661
  });
1292
1662
  await promises.writeFile(path2.join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1293
1663
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1664
+ const isPartOfExternals = allExternals.some((external) => chunk2OTEFUER_cjs.isDependencyPartOfPackage(dep, external));
1665
+ if (isPartOfExternals) {
1666
+ allUsedExternals.add(dep);
1667
+ continue;
1668
+ }
1294
1669
  if (depsToOptimize.has(dep)) {
1295
1670
  const existingEntry = depsToOptimize.get(dep);
1296
1671
  depsToOptimize.set(dep, {
@@ -1309,14 +1684,13 @@ If you think your configuration is valid, please open an issue.`);
1309
1684
  }
1310
1685
  }
1311
1686
  }
1312
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1687
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1313
1688
  logger.info("Optimizing dependencies...");
1314
- logger.debug(
1315
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1316
- );
1689
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1317
1690
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1318
1691
  bundlerOptions: {
1319
1692
  ...bundlerOptions,
1693
+ externals: allExternals,
1320
1694
  enableEsmShim,
1321
1695
  isDev
1322
1696
  },
@@ -1335,20 +1709,22 @@ If you think your configuration is valid, please open an issue.`);
1335
1709
  },
1336
1710
  logger
1337
1711
  );
1338
- return result;
1712
+ return {
1713
+ ...result,
1714
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1715
+ };
1339
1716
  }
1340
1717
 
1341
1718
  exports.aliasHono = aliasHono;
1342
1719
  exports.analyzeBundle = analyzeBundle;
1343
1720
  exports.esbuild = esbuild;
1721
+ exports.esmShim = esmShim;
1344
1722
  exports.extractMastraOption = extractMastraOption;
1345
1723
  exports.getBundlerOptions = getBundlerOptions;
1346
- exports.getPackageName = getPackageName;
1347
- exports.getPackageRootPath = getPackageRootPath;
1348
1724
  exports.getWorkspaceInformation = getWorkspaceInformation;
1349
1725
  exports.removeAllOptionsFromMastraExcept = removeAllOptionsFromMastraExcept;
1350
1726
  exports.removeDeployer = removeDeployer2;
1351
- exports.slash = slash;
1727
+ exports.subpathExternalsResolver = subpathExternalsResolver;
1352
1728
  exports.tsConfigPaths = tsConfigPaths;
1353
- //# sourceMappingURL=chunk-C74EXQSL.cjs.map
1354
- //# sourceMappingURL=chunk-C74EXQSL.cjs.map
1729
+ //# sourceMappingURL=chunk-MUWNMVNL.cjs.map
1730
+ //# sourceMappingURL=chunk-MUWNMVNL.cjs.map