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

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 (198) hide show
  1. package/CHANGELOG.md +200 -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 +18 -13
  17. package/dist/build/index.d.ts +1 -0
  18. package/dist/build/index.d.ts.map +1 -1
  19. package/dist/build/index.js +5 -4
  20. package/dist/build/package-info.d.ts +9 -0
  21. package/dist/build/package-info.d.ts.map +1 -0
  22. package/dist/build/plugins/esm-shim.d.ts +14 -0
  23. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  24. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  25. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  26. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  27. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  28. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  29. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  30. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  31. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  32. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  33. package/dist/build/utils.d.ts +13 -4
  34. package/dist/build/utils.d.ts.map +1 -1
  35. package/dist/bundler/index.cjs +2 -2
  36. package/dist/bundler/index.d.ts +1 -1
  37. package/dist/bundler/index.d.ts.map +1 -1
  38. package/dist/bundler/index.js +1 -1
  39. package/dist/{chunk-H3LLQ2MW.js → chunk-3KATYU33.js} +572 -177
  40. package/dist/chunk-3KATYU33.js.map +1 -0
  41. package/dist/{chunk-WBAWUM7Z.js → chunk-5OGQ7IFB.js} +6 -5
  42. package/dist/chunk-5OGQ7IFB.js.map +1 -0
  43. package/dist/chunk-7PLNIFGZ.cjs +8 -0
  44. package/dist/chunk-7PLNIFGZ.cjs.map +1 -0
  45. package/dist/chunk-BTNPI4Z7.cjs +4 -0
  46. package/dist/chunk-BTNPI4Z7.cjs.map +1 -0
  47. package/dist/{chunk-5QFG6SCM.js → chunk-DPDWM7HQ.js} +2 -2
  48. package/dist/chunk-DPDWM7HQ.js.map +1 -0
  49. package/dist/{chunk-C74EXQSL.cjs → chunk-EHZKDGGA.cjs} +586 -190
  50. package/dist/chunk-EHZKDGGA.cjs.map +1 -0
  51. package/dist/chunk-F2LCS2DV.cjs +64 -0
  52. package/dist/chunk-F2LCS2DV.cjs.map +1 -0
  53. package/dist/chunk-FBT6QP7J.js +3 -0
  54. package/dist/chunk-FBT6QP7J.js.map +1 -0
  55. package/dist/chunk-GD2TGMBP.cjs +95 -0
  56. package/dist/chunk-GD2TGMBP.cjs.map +1 -0
  57. package/dist/{chunk-HQJR52M7.js → chunk-HFP6WWM5.js} +5 -4
  58. package/dist/chunk-HFP6WWM5.js.map +1 -0
  59. package/dist/chunk-ID3HN3BH.cjs +16 -0
  60. package/dist/chunk-ID3HN3BH.cjs.map +1 -0
  61. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  62. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  63. package/dist/chunk-MMUE22EL.js +159 -0
  64. package/dist/chunk-MMUE22EL.js.map +1 -0
  65. package/dist/chunk-N5TMJUIR.js +14 -0
  66. package/dist/chunk-N5TMJUIR.js.map +1 -0
  67. package/dist/chunk-NM6R77PX.js +57 -0
  68. package/dist/chunk-NM6R77PX.js.map +1 -0
  69. package/dist/chunk-P4L6VIHY.js +93 -0
  70. package/dist/chunk-P4L6VIHY.js.map +1 -0
  71. package/dist/{chunk-AQAOWLJJ.cjs → chunk-PK3AX3KO.cjs} +16 -15
  72. package/dist/chunk-PK3AX3KO.cjs.map +1 -0
  73. package/dist/chunk-Q2YGWEXY.js +6 -0
  74. package/dist/chunk-Q2YGWEXY.js.map +1 -0
  75. package/dist/chunk-TXKETRIN.cjs +162 -0
  76. package/dist/chunk-TXKETRIN.cjs.map +1 -0
  77. package/dist/{chunk-OFUWEVGF.js → chunk-UG72ONP7.js} +6 -15
  78. package/dist/chunk-UG72ONP7.js.map +1 -0
  79. package/dist/{chunk-TDWIGFVF.cjs → chunk-Z33LQHGJ.cjs} +15 -14
  80. package/dist/chunk-Z33LQHGJ.cjs.map +1 -0
  81. package/dist/{chunk-IL2VLNIJ.cjs → chunk-ZPUTJSEC.cjs} +13 -23
  82. package/dist/chunk-ZPUTJSEC.cjs.map +1 -0
  83. package/dist/default-u_dwuiYb-65M4BHAA.js +3 -0
  84. package/dist/default-u_dwuiYb-65M4BHAA.js.map +1 -0
  85. package/dist/default-u_dwuiYb-PWN6FHC6.cjs +9 -0
  86. package/dist/default-u_dwuiYb-PWN6FHC6.cjs.map +1 -0
  87. package/dist/deploy/log.d.ts +1 -1
  88. package/dist/deploy/log.d.ts.map +1 -1
  89. package/dist/effect-QlVUlMFu-2ADPKIDF.cjs +17 -0
  90. package/dist/effect-QlVUlMFu-2ADPKIDF.cjs.map +1 -0
  91. package/dist/effect-QlVUlMFu-FD73M3OO.js +15 -0
  92. package/dist/effect-QlVUlMFu-FD73M3OO.js.map +1 -0
  93. package/dist/esm-BLVTLTJW.js +1289 -0
  94. package/dist/esm-BLVTLTJW.js.map +1 -0
  95. package/dist/esm-E3NUCNVN.cjs +1336 -0
  96. package/dist/esm-E3NUCNVN.cjs.map +1 -0
  97. package/dist/index.cjs +12 -12
  98. package/dist/index.js +4 -4
  99. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  100. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  101. package/dist/server/index.cjs +2365 -10524
  102. package/dist/server/index.cjs.map +1 -1
  103. package/dist/server/index.d.ts +3 -12
  104. package/dist/server/index.d.ts.map +1 -1
  105. package/dist/server/index.js +2363 -10522
  106. package/dist/server/index.js.map +1 -1
  107. package/dist/services/index.cjs +4 -4
  108. package/dist/services/index.js +1 -1
  109. package/dist/sury-CWZTCd75-K3FHMZF5.cjs +17 -0
  110. package/dist/sury-CWZTCd75-K3FHMZF5.cjs.map +1 -0
  111. package/dist/sury-CWZTCd75-Y2GURJ6K.js +15 -0
  112. package/dist/sury-CWZTCd75-Y2GURJ6K.js.map +1 -0
  113. package/dist/typebox-Dei93FPO-2WP4NOYD.js +8 -0
  114. package/dist/typebox-Dei93FPO-2WP4NOYD.js.map +1 -0
  115. package/dist/typebox-Dei93FPO-WTXAW2LA.cjs +10 -0
  116. package/dist/typebox-Dei93FPO-WTXAW2LA.cjs.map +1 -0
  117. package/dist/valibot--1zFm7rT-HMTCRBB3.cjs +17 -0
  118. package/dist/valibot--1zFm7rT-HMTCRBB3.cjs.map +1 -0
  119. package/dist/valibot--1zFm7rT-VGFBTDTW.js +15 -0
  120. package/dist/valibot--1zFm7rT-VGFBTDTW.js.map +1 -0
  121. package/dist/valibot-D_HTw1Gn-ILCWWLE4.cjs +45 -0
  122. package/dist/valibot-D_HTw1Gn-ILCWWLE4.cjs.map +1 -0
  123. package/dist/valibot-D_HTw1Gn-LLCGNU3W.js +43 -0
  124. package/dist/valibot-D_HTw1Gn-LLCGNU3W.js.map +1 -0
  125. package/dist/validator/custom-resolver.cjs +20 -12
  126. package/dist/validator/custom-resolver.cjs.map +1 -1
  127. package/dist/validator/custom-resolver.d.ts.map +1 -1
  128. package/dist/validator/custom-resolver.js +18 -10
  129. package/dist/validator/custom-resolver.js.map +1 -1
  130. package/dist/validator/validate.d.ts +15 -1
  131. package/dist/validator/validate.d.ts.map +1 -1
  132. package/dist/zod-Bwrt9trS-XCRGYQVE.js +29 -0
  133. package/dist/zod-Bwrt9trS-XCRGYQVE.js.map +1 -0
  134. package/dist/zod-Bwrt9trS-XDMWF3NW.cjs +31 -0
  135. package/dist/zod-Bwrt9trS-XDMWF3NW.cjs.map +1 -0
  136. package/dist/zod-DSgpEGAE-TKBHSSLS.js +37 -0
  137. package/dist/zod-DSgpEGAE-TKBHSSLS.js.map +1 -0
  138. package/dist/zod-DSgpEGAE-ZWQMF6SS.cjs +39 -0
  139. package/dist/zod-DSgpEGAE-ZWQMF6SS.cjs.map +1 -0
  140. package/package.json +18 -21
  141. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  142. package/dist/chunk-5QFG6SCM.js.map +0 -1
  143. package/dist/chunk-AQAOWLJJ.cjs.map +0 -1
  144. package/dist/chunk-C74EXQSL.cjs.map +0 -1
  145. package/dist/chunk-H3LLQ2MW.js.map +0 -1
  146. package/dist/chunk-HQJR52M7.js.map +0 -1
  147. package/dist/chunk-IL2VLNIJ.cjs.map +0 -1
  148. package/dist/chunk-OFUWEVGF.js.map +0 -1
  149. package/dist/chunk-TDWIGFVF.cjs.map +0 -1
  150. package/dist/chunk-WBAWUM7Z.js.map +0 -1
  151. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  152. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  153. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  154. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  155. package/dist/server/handlers/auth/index.d.ts +0 -11
  156. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  157. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -20
  158. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  159. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  160. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  161. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -232
  162. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  163. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  164. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  165. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  166. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  167. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  168. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  169. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  170. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  171. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  172. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  173. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  174. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  175. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -15
  176. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  177. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  178. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  179. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  180. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  181. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  182. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  183. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -302
  184. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  185. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  186. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  187. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  188. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  189. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  190. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  191. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  192. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  193. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  194. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  195. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  196. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  197. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  198. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
@@ -1,26 +1,28 @@
1
1
  'use strict';
2
2
 
3
+ var chunkF2LCS2DV_cjs = require('./chunk-F2LCS2DV.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');
23
+ var localPkg = require('local-pkg');
22
24
  var nodeResolve = require('@rollup/plugin-node-resolve');
23
- var esmShim = require('@rollup/plugin-esm-shim');
25
+ var originalEsmShim = require('@rollup/plugin-esm-shim');
24
26
  var posix = require('path/posix');
25
27
  var resolve = require('resolve.exports');
26
28
  var error = require('@mastra/core/error');
@@ -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("/");
66
- }
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));
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;
106
71
  }
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://${chunkF2LCS2DV_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(chunkF2LCS2DV_cjs.slash(closestPkgJson)) : chunkF2LCS2DV_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) => [
@@ -637,6 +676,25 @@ function removeDeployer2(mastraEntry, options) {
637
676
  }
638
677
  };
639
678
  }
679
+ async function getPackageRootPath(packageName, parentPath) {
680
+ let rootPath;
681
+ try {
682
+ let options = void 0;
683
+ if (parentPath) {
684
+ if (!parentPath.startsWith("file://")) {
685
+ parentPath = url.pathToFileURL(parentPath).href;
686
+ }
687
+ options = {
688
+ paths: [parentPath]
689
+ };
690
+ }
691
+ const pkg2 = await localPkg.getPackageInfo(packageName, options);
692
+ rootPath = pkg2?.rootPath ?? null;
693
+ } catch (e) {
694
+ rootPath = null;
695
+ }
696
+ return rootPath;
697
+ }
640
698
 
641
699
  // src/build/analyze/constants.ts
642
700
  var DEPS_TO_IGNORE = ["#tools"];
@@ -655,7 +713,7 @@ var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
655
713
 
656
714
  // src/build/analyze/analyzeEntry.ts
657
715
  function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
658
- const normalizedMastraEntry = slash(mastraEntry);
716
+ const normalizedMastraEntry = chunkF2LCS2DV_cjs.slash(mastraEntry);
659
717
  let virtualPlugin = null;
660
718
  if (isVirtualFile) {
661
719
  virtualPlugin = virtual__default.default({
@@ -674,7 +732,7 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
674
732
  name: "custom-alias-resolver",
675
733
  resolveId(id) {
676
734
  if (id === "#server") {
677
- return slash(url.fileURLToPath(undefined("@mastra/deployer/server")));
735
+ return chunkF2LCS2DV_cjs.slash(url.fileURLToPath(undefined("@mastra/deployer/server")));
678
736
  }
679
737
  if (id === "#mastra") {
680
738
  return normalizedMastraEntry;
@@ -699,7 +757,8 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
699
757
  return plugins;
700
758
  }
701
759
  async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
702
- logger: logger$1
760
+ logger: logger$1,
761
+ shouldCheckTransitiveDependencies
703
762
  }) {
704
763
  const depsToOptimize = /* @__PURE__ */ new Map();
705
764
  if (!output.facadeModuleId) {
@@ -712,18 +771,22 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
712
771
  entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
713
772
  }
714
773
  for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
715
- if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
774
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
716
775
  continue;
717
776
  }
718
- const pkgName = getPackageName(dependency);
777
+ const pkgName = chunkF2LCS2DV_cjs.getPackageName(dependency);
719
778
  let rootPath = null;
720
779
  let isWorkspace = false;
721
780
  if (pkgName) {
722
781
  rootPath = await getPackageRootPath(dependency, entryRootPath);
723
782
  isWorkspace = workspaceMap.has(pkgName);
724
783
  }
725
- const normalizedRootPath = rootPath ? slash(rootPath) : null;
726
- depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace });
784
+ const normalizedRootPath = rootPath ? chunkF2LCS2DV_cjs.slash(rootPath) : null;
785
+ depsToOptimize.set(dependency, {
786
+ exports: bindings,
787
+ rootPath: normalizedRootPath,
788
+ isWorkspace
789
+ });
727
790
  }
728
791
  async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
729
792
  if (currentDepth >= maxDepth) {
@@ -767,12 +830,18 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
767
830
  await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
768
831
  }
769
832
  }
770
- await checkTransitiveDependencies(initialDepsToOptimize);
833
+ if (shouldCheckTransitiveDependencies) {
834
+ await checkTransitiveDependencies(initialDepsToOptimize);
835
+ }
771
836
  const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
772
837
  if (dynamicImports.length) {
773
838
  for (const dynamicImport of dynamicImports) {
774
839
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
775
- depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
840
+ depsToOptimize.set(dynamicImport, {
841
+ exports: ["*"],
842
+ rootPath: null,
843
+ isWorkspace: false
844
+ });
776
845
  }
777
846
  }
778
847
  }
@@ -786,13 +855,14 @@ async function analyzeEntry({
786
855
  sourcemapEnabled,
787
856
  workspaceMap,
788
857
  projectRoot,
789
- initialDepsToOptimize = /* @__PURE__ */ new Map()
858
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
790
859
  // used to avoid infinite recursion
860
+ shouldCheckTransitiveDependencies = false
791
861
  }) {
792
862
  const optimizerBundler = await rollup.rollup({
793
863
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
794
864
  input: isVirtualFile ? "#entry" : entry,
795
- treeshake: "smallest",
865
+ treeshake: false,
796
866
  preserveSymlinks: true,
797
867
  plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
798
868
  external: DEPS_TO_IGNORE
@@ -808,7 +878,8 @@ async function analyzeEntry({
808
878
  projectRoot,
809
879
  initialDepsToOptimize,
810
880
  {
811
- logger
881
+ logger,
882
+ shouldCheckTransitiveDependencies
812
883
  }
813
884
  );
814
885
  return {
@@ -819,6 +890,27 @@ async function analyzeEntry({
819
890
  }
820
891
  };
821
892
  }
893
+ var FilenameDeclarationRegex = /(?:const|let|var)\s+__filename/;
894
+ var DirnameDeclarationRegex = /(?:const|let|var)\s+__dirname/;
895
+ function esmShim() {
896
+ const original = originalEsmShim__default.default();
897
+ return {
898
+ name: "esm-shim",
899
+ renderChunk(code, chunk, opts, meta) {
900
+ const hasFilename = code.includes("__filename");
901
+ const hasDirname = code.includes("__dirname");
902
+ const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);
903
+ const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);
904
+ if (userDeclaredFilename || userDeclaredDirname) {
905
+ return null;
906
+ }
907
+ if (typeof original.renderChunk === "function") {
908
+ return original.renderChunk.call(this, code, chunk, opts, meta);
909
+ }
910
+ return null;
911
+ }
912
+ };
913
+ }
822
914
  function aliasHono() {
823
915
  return {
824
916
  name: "hono-alias",
@@ -831,8 +923,116 @@ function aliasHono() {
831
923
  }
832
924
  };
833
925
  }
926
+ function nodeGypDetector() {
927
+ const modulesToTrack = /* @__PURE__ */ new Set();
928
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
929
+ return {
930
+ name: "node-gyp-build-detector",
931
+ moduleParsed(info) {
932
+ if (!info.meta?.commonjs?.requires?.length) {
933
+ return;
934
+ }
935
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
936
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
937
+ );
938
+ if (!hasNodeGypBuild) {
939
+ return;
940
+ }
941
+ modulesToTrack.add(info.id);
942
+ modulesToTrackPackageInfo.set(info.id, localPkg.getPackageInfo(info.id));
943
+ },
944
+ async generateBundle(options, bundle) {
945
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
946
+ for (const [fileName, chunk] of Object.entries(bundle)) {
947
+ if (chunk.type === "chunk") {
948
+ for (const moduleId of chunk.moduleIds) {
949
+ if (modulesToTrackPackageInfo.has(moduleId)) {
950
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
951
+ if (!binaryMapByChunk.has(fileName)) {
952
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
953
+ }
954
+ if (pkgInfo?.packageJson?.name) {
955
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
956
+ }
957
+ }
958
+ }
959
+ }
960
+ }
961
+ const binaryMapJson = Object.fromEntries(
962
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
963
+ );
964
+ this.emitFile({
965
+ type: "asset",
966
+ name: "binary-map.json",
967
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
968
+ });
969
+ }
970
+ };
971
+ }
972
+
973
+ // src/build/plugins/subpath-externals-resolver.ts
974
+ function subpathExternalsResolver(externals) {
975
+ return {
976
+ name: "subpath-externals-resolver",
977
+ resolveId(id) {
978
+ if (id.startsWith(".") || id.startsWith("/")) {
979
+ return null;
980
+ }
981
+ const isPartOfExternals = externals.some((external) => chunkF2LCS2DV_cjs.isDependencyPartOfPackage(id, external));
982
+ if (isPartOfExternals) {
983
+ return {
984
+ id,
985
+ external: true
986
+ };
987
+ }
988
+ }
989
+ };
990
+ }
991
+ function moduleResolveMap(externals, projectRoot) {
992
+ const importMap = /* @__PURE__ */ new Map();
993
+ return {
994
+ name: "module-resolve-map",
995
+ moduleParsed(info) {
996
+ if (info.importedIds.length === 0 || !info.id) {
997
+ return;
998
+ }
999
+ for (const importedId of info.importedIds) {
1000
+ for (const external of externals) {
1001
+ if (chunkF2LCS2DV_cjs.isDependencyPartOfPackage(importedId, external)) {
1002
+ importMap.set(external, info.id);
1003
+ }
1004
+ }
1005
+ }
1006
+ },
1007
+ async generateBundle(options, bundle) {
1008
+ const resolveMap = /* @__PURE__ */ new Map();
1009
+ for (const [fileName, chunk] of Object.entries(bundle)) {
1010
+ if (chunk.type === "chunk") {
1011
+ for (const [external, resolvedFrom] of importMap) {
1012
+ if (chunk.moduleIds.includes(resolvedFrom)) {
1013
+ const fullPath = url.pathToFileURL(chunkF2LCS2DV_cjs.slash(path2.join(projectRoot, fileName))).toString();
1014
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
1015
+ innerMap.set(external, url.pathToFileURL(chunkF2LCS2DV_cjs.slash(resolvedFrom)).toString());
1016
+ resolveMap.set(fullPath, innerMap);
1017
+ }
1018
+ }
1019
+ }
1020
+ }
1021
+ const resolveMapJson = Object.fromEntries(
1022
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
1023
+ );
1024
+ this.emitFile({
1025
+ type: "asset",
1026
+ name: "module-resolve-map.json",
1027
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
1028
+ });
1029
+ }
1030
+ };
1031
+ }
1032
+
1033
+ // src/build/analyze/bundleExternals.ts
834
1034
  function prepareEntryFileName(name, rootDir) {
835
- return rollupSafeName(name, rootDir);
1035
+ return chunkF2LCS2DV_cjs.rollupSafeName(name, rootDir);
836
1036
  }
837
1037
  function createVirtualDependencies(depsToOptimize, {
838
1038
  projectRoot,
@@ -882,7 +1082,7 @@ function createVirtualDependencies(depsToOptimize, {
882
1082
  continue;
883
1083
  }
884
1084
  const fileName = posix.basename(currentDepPath.name);
885
- const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir);
1085
+ const entryName = prepareEntryFileName(chunkF2LCS2DV_cjs.getCompiledDepCachePath(rootPath, fileName), rootDir);
886
1086
  fileNameToDependencyMap.set(entryName, dep);
887
1087
  optimizedDependencyEntries.set(dep, {
888
1088
  ...currentDepPath,
@@ -896,13 +1096,14 @@ async function getInputPlugins2(virtualDependencies, {
896
1096
  transpilePackages,
897
1097
  workspaceMap,
898
1098
  bundlerOptions,
899
- rootDir
1099
+ rootDir,
1100
+ externals
900
1101
  }) {
901
1102
  const transpilePackagesMap = /* @__PURE__ */ new Map();
902
1103
  for (const pkg2 of transpilePackages) {
903
1104
  const dir = await getPackageRootPath(pkg2);
904
1105
  if (dir) {
905
- transpilePackagesMap.set(pkg2, slash(dir));
1106
+ transpilePackagesMap.set(pkg2, chunkF2LCS2DV_cjs.slash(dir));
906
1107
  } else {
907
1108
  transpilePackagesMap.set(pkg2, workspaceMap.get(pkg2)?.location ?? pkg2);
908
1109
  }
@@ -917,6 +1118,7 @@ async function getInputPlugins2(virtualDependencies, {
917
1118
  {}
918
1119
  )
919
1120
  ),
1121
+ subpathExternalsResolver(externals),
920
1122
  transpilePackagesMap.size ? esbuild({
921
1123
  format: "esm",
922
1124
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -945,7 +1147,8 @@ async function getInputPlugins2(virtualDependencies, {
945
1147
  if (!resolvedPath) {
946
1148
  resolvedPath = pkgJson.main ?? "index.js";
947
1149
  }
948
- return await this.resolve(path2__namespace.posix.join(packageRootPath, resolvedPath), importer, options);
1150
+ const resolved = await this.resolve(path2__namespace.posix.join(packageRootPath, resolvedPath), importer, options);
1151
+ return resolved;
949
1152
  }
950
1153
  } : null,
951
1154
  rollupPlugin.optimizeLodashImports({
@@ -960,10 +1163,12 @@ async function getInputPlugins2(virtualDependencies, {
960
1163
  preferBuiltins: true,
961
1164
  exportConditions: ["node"]
962
1165
  }),
963
- bundlerOptions.isDev ? esmShim__default.default() : null,
1166
+ bundlerOptions.isDev ? esmShim() : null,
964
1167
  // hono is imported from deployer, so we need to resolve from here instead of the project root
965
1168
  aliasHono(),
966
1169
  json__default.default(),
1170
+ nodeGypDetector(),
1171
+ moduleResolveMap(externals, rootDir),
967
1172
  {
968
1173
  name: "not-found-resolver",
969
1174
  resolveId: {
@@ -1021,12 +1226,13 @@ async function buildExternalDependencies(virtualDependencies, {
1021
1226
  {}
1022
1227
  ),
1023
1228
  external: externals,
1024
- treeshake: "safest",
1229
+ treeshake: bundlerOptions.isDev ? false : "safest",
1025
1230
  plugins: getInputPlugins2(virtualDependencies, {
1026
1231
  transpilePackages: packagesToTranspile,
1027
1232
  workspaceMap,
1028
1233
  bundlerOptions,
1029
- rootDir
1234
+ rootDir,
1235
+ externals
1030
1236
  })
1031
1237
  });
1032
1238
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
@@ -1034,6 +1240,8 @@ async function buildExternalDependencies(virtualDependencies, {
1034
1240
  format: "esm",
1035
1241
  dir: rootDir,
1036
1242
  entryFileNames: "[name].mjs",
1243
+ // used to get the filename of the actual error
1244
+ sourcemap: true,
1037
1245
  /**
1038
1246
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1039
1247
  * So we want to write them to the `.mastra/output` folder as well.
@@ -1042,9 +1250,9 @@ async function buildExternalDependencies(virtualDependencies, {
1042
1250
  if (bundlerOptions.isDev) {
1043
1251
  const importedFromPackages = /* @__PURE__ */ new Set();
1044
1252
  for (const moduleId of chunkInfo.moduleIds) {
1045
- const normalized = slash(moduleId);
1253
+ const normalized = chunkF2LCS2DV_cjs.slash(moduleId);
1046
1254
  for (const [pkgName, pkgInfo] of workspaceMap.entries()) {
1047
- const location = slash(pkgInfo.location);
1255
+ const location = chunkF2LCS2DV_cjs.slash(pkgInfo.location);
1048
1256
  if (normalized.startsWith(location)) {
1049
1257
  importedFromPackages.add(pkgName);
1050
1258
  break;
@@ -1066,11 +1274,12 @@ async function buildExternalDependencies(virtualDependencies, {
1066
1274
  if (importedFromPackages.size === 1) {
1067
1275
  const [pkgName] = importedFromPackages;
1068
1276
  const workspaceLocation = workspaceMap.get(pkgName).location;
1069
- return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
1277
+ return prepareEntryFileName(chunkF2LCS2DV_cjs.getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
1070
1278
  }
1071
1279
  }
1072
1280
  return `${outputDirRelative}/[name].mjs`;
1073
1281
  },
1282
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1074
1283
  hoistTransitiveImports: false
1075
1284
  });
1076
1285
  await bundler.close();
@@ -1079,7 +1288,7 @@ async function buildExternalDependencies(virtualDependencies, {
1079
1288
  function findExternalImporter(module, external, allOutputs) {
1080
1289
  const capturedFiles = /* @__PURE__ */ new Set();
1081
1290
  for (const id of module.imports) {
1082
- if (id === external) {
1291
+ if (chunkF2LCS2DV_cjs.isDependencyPartOfPackage(id, external)) {
1083
1292
  return module;
1084
1293
  } else {
1085
1294
  if (id.endsWith(".mjs")) {
@@ -1125,7 +1334,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1125
1334
  isDev
1126
1335
  }
1127
1336
  });
1128
- const moduleResolveMap = /* @__PURE__ */ new Map();
1337
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1129
1338
  const filteredChunks = output.filter((o) => o.type === "chunk");
1130
1339
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1131
1340
  for (const external of allExternals) {
@@ -1135,10 +1344,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1135
1344
  const importer = findExternalImporter(o, external, filteredChunks);
1136
1345
  if (importer) {
1137
1346
  const fullPath = path2__namespace.join(workspaceRoot || projectRoot, importer.fileName);
1138
- let innerMap = moduleResolveMap.get(fullPath);
1347
+ let innerMap = moduleResolveMap2.get(fullPath);
1139
1348
  if (!innerMap) {
1140
1349
  innerMap = /* @__PURE__ */ new Map();
1141
- moduleResolveMap.set(fullPath, innerMap);
1350
+ moduleResolveMap2.set(fullPath, innerMap);
1142
1351
  }
1143
1352
  if (importer.moduleIds.length) {
1144
1353
  innerMap.set(
@@ -1150,7 +1359,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1150
1359
  }
1151
1360
  }
1152
1361
  const usedExternals = /* @__PURE__ */ Object.create(null);
1153
- for (const [fullPath, innerMap] of moduleResolveMap) {
1362
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1154
1363
  const innerObj = /* @__PURE__ */ Object.create(null);
1155
1364
  for (const [external, value] of innerMap) {
1156
1365
  innerObj[external] = value;
@@ -1159,6 +1368,108 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1159
1368
  }
1160
1369
  return { output, fileNameToDependencyMap, usedExternals };
1161
1370
  }
1371
+
1372
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1373
+ var UNKNOWN_FUNCTION = "<unknown>";
1374
+ function parse(stackString) {
1375
+ var lines = stackString.split("\n");
1376
+ return lines.reduce(function(stack, line) {
1377
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1378
+ if (parseResult) {
1379
+ stack.push(parseResult);
1380
+ }
1381
+ return stack;
1382
+ }, []);
1383
+ }
1384
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1385
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1386
+ function parseChrome(line) {
1387
+ var parts = chromeRe.exec(line);
1388
+ if (!parts) {
1389
+ return null;
1390
+ }
1391
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1392
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1393
+ var submatch = chromeEvalRe.exec(parts[2]);
1394
+ if (isEval && submatch != null) {
1395
+ parts[2] = submatch[1];
1396
+ parts[3] = submatch[2];
1397
+ parts[4] = submatch[3];
1398
+ }
1399
+ return {
1400
+ file: !isNative ? parts[2] : null,
1401
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1402
+ arguments: isNative ? [parts[2]] : [],
1403
+ lineNumber: parts[3] ? +parts[3] : null,
1404
+ column: parts[4] ? +parts[4] : null
1405
+ };
1406
+ }
1407
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1408
+ function parseWinjs(line) {
1409
+ var parts = winjsRe.exec(line);
1410
+ if (!parts) {
1411
+ return null;
1412
+ }
1413
+ return {
1414
+ file: parts[2],
1415
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1416
+ arguments: [],
1417
+ lineNumber: +parts[3],
1418
+ column: parts[4] ? +parts[4] : null
1419
+ };
1420
+ }
1421
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1422
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1423
+ function parseGecko(line) {
1424
+ var parts = geckoRe.exec(line);
1425
+ if (!parts) {
1426
+ return null;
1427
+ }
1428
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1429
+ var submatch = geckoEvalRe.exec(parts[3]);
1430
+ if (isEval && submatch != null) {
1431
+ parts[3] = submatch[1];
1432
+ parts[4] = submatch[2];
1433
+ parts[5] = null;
1434
+ }
1435
+ return {
1436
+ file: parts[3],
1437
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1438
+ arguments: parts[2] ? parts[2].split(",") : [],
1439
+ lineNumber: parts[4] ? +parts[4] : null,
1440
+ column: parts[5] ? +parts[5] : null
1441
+ };
1442
+ }
1443
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1444
+ function parseJSC(line) {
1445
+ var parts = javaScriptCoreRe.exec(line);
1446
+ if (!parts) {
1447
+ return null;
1448
+ }
1449
+ return {
1450
+ file: parts[3],
1451
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1452
+ arguments: [],
1453
+ lineNumber: +parts[4],
1454
+ column: parts[5] ? +parts[5] : null
1455
+ };
1456
+ }
1457
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1458
+ function parseNode(line) {
1459
+ var parts = nodeRe.exec(line);
1460
+ if (!parts) {
1461
+ return null;
1462
+ }
1463
+ return {
1464
+ file: parts[2],
1465
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1466
+ arguments: [],
1467
+ lineNumber: +parts[3],
1468
+ column: parts[4] ? +parts[4] : null
1469
+ };
1470
+ }
1471
+
1472
+ // src/build/analyze.ts
1162
1473
  function throwExternalDependencyError({
1163
1474
  errorId,
1164
1475
  moduleName,
@@ -1182,6 +1493,110 @@ export const mastra = new Mastra({
1182
1493
  })`
1183
1494
  });
1184
1495
  }
1496
+ function getPackageNameFromBundledModuleName(moduleName) {
1497
+ const chunks = moduleName.split("-");
1498
+ if (!chunks.length) {
1499
+ return moduleName;
1500
+ }
1501
+ if (chunks[0]?.startsWith("@")) {
1502
+ return chunks.slice(0, 2).join("/");
1503
+ }
1504
+ return chunks[0];
1505
+ }
1506
+ function validateError(err, file, {
1507
+ binaryMapData,
1508
+ workspaceMap
1509
+ }) {
1510
+ let moduleName = null;
1511
+ let errorConfig = null;
1512
+ if (err instanceof ValidationError) {
1513
+ const parsedStack = parse(err.stack);
1514
+ if (err.type === "TypeError") {
1515
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1516
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1517
+ if (stacktraceFrame) {
1518
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1519
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(path2.basename(file.name));
1520
+ } else {
1521
+ moduleName = getPackageNameFromBundledModuleName(path2.basename(file.name));
1522
+ }
1523
+ errorConfig = {
1524
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1525
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1526
+ };
1527
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1528
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1529
+ const parentModuleName = getPackageNameFromBundledModuleName(path2.basename(file.name));
1530
+ errorConfig = {
1531
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1532
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1533
+ };
1534
+ if (moduleName === parentModuleName) {
1535
+ return;
1536
+ }
1537
+ }
1538
+ }
1539
+ if (err.message.includes("No native build was found")) {
1540
+ const pkgName = getPackageNameFromBundledModuleName(path2.basename(file.name));
1541
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1542
+ errorConfig = {
1543
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1544
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1545
+ };
1546
+ }
1547
+ if (moduleName && workspaceMap.has(moduleName)) {
1548
+ throw new error.MastraError({
1549
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1550
+ domain: error.ErrorDomain.DEPLOYER,
1551
+ category: error.ErrorCategory.USER,
1552
+ details: {
1553
+ // importFile: moduleName,
1554
+ packageName: moduleName
1555
+ },
1556
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1557
+ Error: ${err.stack}`
1558
+ });
1559
+ }
1560
+ if (errorConfig && moduleName) {
1561
+ throwExternalDependencyError({
1562
+ errorId: errorConfig.id,
1563
+ moduleName,
1564
+ packageName: moduleName,
1565
+ messagePrefix: errorConfig.messagePrefix
1566
+ });
1567
+ }
1568
+ }
1569
+ async function validateFile(root, file, {
1570
+ binaryMapData,
1571
+ moduleResolveMapLocation,
1572
+ logger,
1573
+ workspaceMap
1574
+ }) {
1575
+ try {
1576
+ if (!file.isDynamicEntry && file.isEntry) {
1577
+ await validate(path2.join(root, file.fileName), {
1578
+ moduleResolveMapLocation,
1579
+ injectESMShim: false
1580
+ });
1581
+ }
1582
+ } catch (err) {
1583
+ let errorToHandle = err;
1584
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1585
+ try {
1586
+ await validate(path2.join(root, file.fileName), {
1587
+ moduleResolveMapLocation,
1588
+ injectESMShim: true
1589
+ });
1590
+ errorToHandle = null;
1591
+ } catch (err2) {
1592
+ errorToHandle = err2;
1593
+ }
1594
+ }
1595
+ if (errorToHandle instanceof Error) {
1596
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1597
+ }
1598
+ }
1599
+ }
1185
1600
  async function validateOutput({
1186
1601
  output,
1187
1602
  reverseVirtualReferenceMap,
@@ -1195,60 +1610,30 @@ async function validateOutput({
1195
1610
  externalDependencies: /* @__PURE__ */ new Set(),
1196
1611
  workspaceMap
1197
1612
  };
1198
- await promises.writeFile(path2.join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1199
1613
  for (const deps of Object.values(usedExternals)) {
1200
1614
  for (const dep of Object.keys(deps)) {
1201
1615
  result.externalDependencies.add(dep);
1202
1616
  }
1203
1617
  }
1618
+ let binaryMapData = {};
1619
+ if (fs.existsSync(path2.join(outputDir, "binary-map.json"))) {
1620
+ const binaryMap = await promises.readFile(path2.join(outputDir, "binary-map.json"), "utf-8");
1621
+ binaryMapData = JSON.parse(binaryMap);
1622
+ }
1204
1623
  for (const file of output) {
1205
1624
  if (file.type === "asset") {
1206
1625
  continue;
1207
1626
  }
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
- }
1627
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1628
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1629
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1251
1630
  }
1631
+ await validateFile(projectRoot, file, {
1632
+ binaryMapData,
1633
+ moduleResolveMapLocation: path2.join(outputDir, "module-resolve-map.json"),
1634
+ logger,
1635
+ workspaceMap
1636
+ });
1252
1637
  }
1253
1638
  return result;
1254
1639
  }
@@ -1280,17 +1665,26 @@ If you think your configuration is valid, please open an issue.`);
1280
1665
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1281
1666
  let index = 0;
1282
1667
  const depsToOptimize = /* @__PURE__ */ new Map();
1668
+ const { externals: customExternals = [] } = bundlerOptions || {};
1669
+ const allExternals = [...GLOBAL_EXTERNALS, ...customExternals];
1283
1670
  logger.info("Analyzing dependencies...");
1671
+ const allUsedExternals = /* @__PURE__ */ new Set();
1284
1672
  for (const entry of entries) {
1285
1673
  const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry);
1286
1674
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1287
1675
  logger,
1288
1676
  sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1289
1677
  workspaceMap,
1290
- projectRoot
1678
+ projectRoot,
1679
+ shouldCheckTransitiveDependencies: isDev
1291
1680
  });
1292
1681
  await promises.writeFile(path2.join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1293
1682
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1683
+ const isPartOfExternals = allExternals.some((external) => chunkF2LCS2DV_cjs.isDependencyPartOfPackage(dep, external));
1684
+ if (isPartOfExternals) {
1685
+ allUsedExternals.add(dep);
1686
+ continue;
1687
+ }
1294
1688
  if (depsToOptimize.has(dep)) {
1295
1689
  const existingEntry = depsToOptimize.get(dep);
1296
1690
  depsToOptimize.set(dep, {
@@ -1309,14 +1703,13 @@ If you think your configuration is valid, please open an issue.`);
1309
1703
  }
1310
1704
  }
1311
1705
  }
1312
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1706
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1313
1707
  logger.info("Optimizing dependencies...");
1314
- logger.debug(
1315
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1316
- );
1708
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1317
1709
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1318
1710
  bundlerOptions: {
1319
1711
  ...bundlerOptions,
1712
+ externals: allExternals,
1320
1713
  enableEsmShim,
1321
1714
  isDev
1322
1715
  },
@@ -1335,20 +1728,23 @@ If you think your configuration is valid, please open an issue.`);
1335
1728
  },
1336
1729
  logger
1337
1730
  );
1338
- return result;
1731
+ return {
1732
+ ...result,
1733
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1734
+ };
1339
1735
  }
1340
1736
 
1341
1737
  exports.aliasHono = aliasHono;
1342
1738
  exports.analyzeBundle = analyzeBundle;
1343
1739
  exports.esbuild = esbuild;
1740
+ exports.esmShim = esmShim;
1344
1741
  exports.extractMastraOption = extractMastraOption;
1345
1742
  exports.getBundlerOptions = getBundlerOptions;
1346
- exports.getPackageName = getPackageName;
1347
1743
  exports.getPackageRootPath = getPackageRootPath;
1348
1744
  exports.getWorkspaceInformation = getWorkspaceInformation;
1349
1745
  exports.removeAllOptionsFromMastraExcept = removeAllOptionsFromMastraExcept;
1350
1746
  exports.removeDeployer = removeDeployer2;
1351
- exports.slash = slash;
1747
+ exports.subpathExternalsResolver = subpathExternalsResolver;
1352
1748
  exports.tsConfigPaths = tsConfigPaths;
1353
- //# sourceMappingURL=chunk-C74EXQSL.cjs.map
1354
- //# sourceMappingURL=chunk-C74EXQSL.cjs.map
1749
+ //# sourceMappingURL=chunk-EHZKDGGA.cjs.map
1750
+ //# sourceMappingURL=chunk-EHZKDGGA.cjs.map