@mastra/deployer 0.0.0-bundle-recursion-20251030002519 → 0.0.0-bundle-studio-cloud-20251222034739

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 (237) hide show
  1. package/CHANGELOG.md +954 -5
  2. package/dist/arktype-aI7TBD0R-CCZH3EYK.js +8 -0
  3. package/dist/arktype-aI7TBD0R-CCZH3EYK.js.map +1 -0
  4. package/dist/arktype-aI7TBD0R-XHBHUL3T.cjs +10 -0
  5. package/dist/arktype-aI7TBD0R-XHBHUL3T.cjs.map +1 -0
  6. package/dist/build/analyze/analyzeEntry.d.ts +4 -1
  7. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  8. package/dist/build/analyze/bundleExternals.d.ts +4 -5
  9. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  10. package/dist/build/analyze/constants.d.ts.map +1 -1
  11. package/dist/build/analyze.cjs +2 -2
  12. package/dist/build/analyze.d.ts +4 -5
  13. package/dist/build/analyze.d.ts.map +1 -1
  14. package/dist/build/analyze.js +1 -1
  15. package/dist/build/babel/remove-deployer.d.ts.map +1 -1
  16. package/dist/build/bundler.cjs +3 -3
  17. package/dist/build/bundler.d.ts +2 -1
  18. package/dist/build/bundler.d.ts.map +1 -1
  19. package/dist/build/bundler.js +1 -1
  20. package/dist/build/bundlerOptions.d.ts.map +1 -1
  21. package/dist/build/deployer.d.ts.map +1 -1
  22. package/dist/build/index.cjs +18 -13
  23. package/dist/build/index.d.ts +1 -0
  24. package/dist/build/index.d.ts.map +1 -1
  25. package/dist/build/index.js +5 -4
  26. package/dist/build/package-info.d.ts +9 -0
  27. package/dist/build/package-info.d.ts.map +1 -0
  28. package/dist/build/plugins/esm-shim.d.ts +14 -0
  29. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  30. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  31. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  32. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  33. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  34. package/dist/build/plugins/node-modules-extension-resolver.d.ts +7 -0
  35. package/dist/build/plugins/node-modules-extension-resolver.d.ts.map +1 -1
  36. package/dist/build/plugins/remove-all-except.d.ts +10 -0
  37. package/dist/build/plugins/remove-all-except.d.ts.map +1 -0
  38. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  39. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  40. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  41. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  42. package/dist/build/serverOptions.d.ts.map +1 -1
  43. package/dist/build/shared/extract-mastra-option.d.ts +4 -8
  44. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  45. package/dist/build/types.d.ts +5 -0
  46. package/dist/build/types.d.ts.map +1 -1
  47. package/dist/build/utils.d.ts +19 -4
  48. package/dist/build/utils.d.ts.map +1 -1
  49. package/dist/build/watcher.d.ts.map +1 -1
  50. package/dist/bundler/index.cjs +6 -2
  51. package/dist/bundler/index.d.ts +10 -9
  52. package/dist/bundler/index.d.ts.map +1 -1
  53. package/dist/bundler/index.js +1 -1
  54. package/dist/chunk-2VG357HT.cjs +4 -0
  55. package/dist/chunk-2VG357HT.cjs.map +1 -0
  56. package/dist/chunk-4P2LYC33.js +14 -0
  57. package/dist/chunk-4P2LYC33.js.map +1 -0
  58. package/dist/chunk-54PQDTM3.cjs +16 -0
  59. package/dist/chunk-54PQDTM3.cjs.map +1 -0
  60. package/dist/chunk-5HTKP372.js +159 -0
  61. package/dist/chunk-5HTKP372.js.map +1 -0
  62. package/dist/{chunk-HS4XRPI7.cjs → chunk-7F6JKGX4.cjs} +70 -37
  63. package/dist/chunk-7F6JKGX4.cjs.map +1 -0
  64. package/dist/{chunk-65RQUN2A.js → chunk-BDA7RMRF.js} +814 -349
  65. package/dist/chunk-BDA7RMRF.js.map +1 -0
  66. package/dist/{chunk-JCACPNJQ.cjs → chunk-CRIOGWZD.cjs} +827 -362
  67. package/dist/chunk-CRIOGWZD.cjs.map +1 -0
  68. package/dist/chunk-DMISJICL.cjs +162 -0
  69. package/dist/chunk-DMISJICL.cjs.map +1 -0
  70. package/dist/{chunk-5QFG6SCM.js → chunk-DPDWM7HQ.js} +2 -2
  71. package/dist/chunk-DPDWM7HQ.js.map +1 -0
  72. package/dist/{chunk-L6Z4LACC.js → chunk-ESR6AK5N.js} +63 -31
  73. package/dist/chunk-ESR6AK5N.js.map +1 -0
  74. package/dist/chunk-G6GFAPPU.js +6 -0
  75. package/dist/chunk-G6GFAPPU.js.map +1 -0
  76. package/dist/chunk-HHA2Y3AS.js +61 -0
  77. package/dist/chunk-HHA2Y3AS.js.map +1 -0
  78. package/dist/chunk-HPGDVJAZ.js +3 -0
  79. package/dist/chunk-HPGDVJAZ.js.map +1 -0
  80. package/dist/chunk-HRCR6OKC.cjs +112 -0
  81. package/dist/chunk-HRCR6OKC.cjs.map +1 -0
  82. package/dist/chunk-JBE6KM7R.cjs +95 -0
  83. package/dist/chunk-JBE6KM7R.cjs.map +1 -0
  84. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  85. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  86. package/dist/chunk-KE4NVPI4.cjs +8 -0
  87. package/dist/chunk-KE4NVPI4.cjs.map +1 -0
  88. package/dist/{chunk-ZIBSZS2J.js → chunk-ONWHS3PA.js} +71 -23
  89. package/dist/chunk-ONWHS3PA.js.map +1 -0
  90. package/dist/{chunk-QOMQKAKY.cjs → chunk-OVVUJ46G.cjs} +79 -31
  91. package/dist/chunk-OVVUJ46G.cjs.map +1 -0
  92. package/dist/chunk-V4HCIN6G.js +93 -0
  93. package/dist/chunk-V4HCIN6G.js.map +1 -0
  94. package/dist/chunk-VA2CSOKJ.cjs +69 -0
  95. package/dist/chunk-VA2CSOKJ.cjs.map +1 -0
  96. package/dist/chunk-WFIG7I5C.js +88 -0
  97. package/dist/chunk-WFIG7I5C.js.map +1 -0
  98. package/dist/default-u_dwuiYb-IKALPRLV.js +3 -0
  99. package/dist/default-u_dwuiYb-IKALPRLV.js.map +1 -0
  100. package/dist/default-u_dwuiYb-ZNEZWEPC.cjs +9 -0
  101. package/dist/default-u_dwuiYb-ZNEZWEPC.cjs.map +1 -0
  102. package/dist/deploy/log.d.ts +1 -1
  103. package/dist/deploy/log.d.ts.map +1 -1
  104. package/dist/effect-QlVUlMFu-2KN4AWBH.cjs +17 -0
  105. package/dist/effect-QlVUlMFu-2KN4AWBH.cjs.map +1 -0
  106. package/dist/effect-QlVUlMFu-MWXQUT6S.js +15 -0
  107. package/dist/effect-QlVUlMFu-MWXQUT6S.js.map +1 -0
  108. package/dist/esm-BLVTLTJW.js +1289 -0
  109. package/dist/esm-BLVTLTJW.js.map +1 -0
  110. package/dist/esm-E3NUCNVN.cjs +1336 -0
  111. package/dist/esm-E3NUCNVN.cjs.map +1 -0
  112. package/dist/index.cjs +11 -22
  113. package/dist/index.cjs.map +1 -1
  114. package/dist/index.js +5 -16
  115. package/dist/index.js.map +1 -1
  116. package/dist/server/handlers/health.d.ts +5 -0
  117. package/dist/server/handlers/health.d.ts.map +1 -0
  118. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  119. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  120. package/dist/server/handlers/utils/query-parsers.d.ts +15 -0
  121. package/dist/server/handlers/utils/query-parsers.d.ts.map +1 -1
  122. package/dist/server/handlers/utils.d.ts +0 -7
  123. package/dist/server/handlers/utils.d.ts.map +1 -1
  124. package/dist/server/index.cjs +2405 -11321
  125. package/dist/server/index.cjs.map +1 -1
  126. package/dist/server/index.d.ts +3 -12
  127. package/dist/server/index.d.ts.map +1 -1
  128. package/dist/server/index.js +2422 -11338
  129. package/dist/server/index.js.map +1 -1
  130. package/dist/server/welcome.d.ts +1 -1
  131. package/dist/server/welcome.d.ts.map +1 -1
  132. package/dist/services/index.cjs +4 -4
  133. package/dist/services/index.js +1 -1
  134. package/dist/sury-CWZTCd75-6QYFZXZY.cjs +17 -0
  135. package/dist/sury-CWZTCd75-6QYFZXZY.cjs.map +1 -0
  136. package/dist/sury-CWZTCd75-DAPFEZIA.js +15 -0
  137. package/dist/sury-CWZTCd75-DAPFEZIA.js.map +1 -0
  138. package/dist/typebox-Dei93FPO-LBLFC3RD.js +8 -0
  139. package/dist/typebox-Dei93FPO-LBLFC3RD.js.map +1 -0
  140. package/dist/typebox-Dei93FPO-RDSW6DFA.cjs +10 -0
  141. package/dist/typebox-Dei93FPO-RDSW6DFA.cjs.map +1 -0
  142. package/dist/valibot--1zFm7rT-AASENK42.js +15 -0
  143. package/dist/valibot--1zFm7rT-AASENK42.js.map +1 -0
  144. package/dist/valibot--1zFm7rT-OOWNQW47.cjs +17 -0
  145. package/dist/valibot--1zFm7rT-OOWNQW47.cjs.map +1 -0
  146. package/dist/valibot-D_HTw1Gn-PBXMZJWR.cjs +45 -0
  147. package/dist/valibot-D_HTw1Gn-PBXMZJWR.cjs.map +1 -0
  148. package/dist/valibot-D_HTw1Gn-PCY2UTIB.js +43 -0
  149. package/dist/valibot-D_HTw1Gn-PCY2UTIB.js.map +1 -0
  150. package/dist/validator/custom-resolver.cjs +20 -12
  151. package/dist/validator/custom-resolver.cjs.map +1 -1
  152. package/dist/validator/custom-resolver.d.ts.map +1 -1
  153. package/dist/validator/custom-resolver.js +18 -10
  154. package/dist/validator/custom-resolver.js.map +1 -1
  155. package/dist/validator/validate.d.ts +15 -1
  156. package/dist/validator/validate.d.ts.map +1 -1
  157. package/dist/zod-Bwrt9trS-MTR3E2QO.js +29 -0
  158. package/dist/zod-Bwrt9trS-MTR3E2QO.js.map +1 -0
  159. package/dist/zod-Bwrt9trS-OXQA54TZ.cjs +31 -0
  160. package/dist/zod-Bwrt9trS-OXQA54TZ.cjs.map +1 -0
  161. package/dist/zod-DSgpEGAE-7BIIMWZW.cjs +39 -0
  162. package/dist/zod-DSgpEGAE-7BIIMWZW.cjs.map +1 -0
  163. package/dist/zod-DSgpEGAE-UO7OP3J6.js +37 -0
  164. package/dist/zod-DSgpEGAE-UO7OP3J6.js.map +1 -0
  165. package/package.json +25 -26
  166. package/dist/build/babel/get-deployer.d.ts +0 -3
  167. package/dist/build/babel/get-deployer.d.ts.map +0 -1
  168. package/dist/build/babel/remove-all-options-bundler.d.ts +0 -5
  169. package/dist/build/babel/remove-all-options-bundler.d.ts.map +0 -1
  170. package/dist/build/babel/remove-all-options-deployer.d.ts +0 -5
  171. package/dist/build/babel/remove-all-options-deployer.d.ts.map +0 -1
  172. package/dist/build/babel/remove-all-options-server.d.ts +0 -5
  173. package/dist/build/babel/remove-all-options-server.d.ts.map +0 -1
  174. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  175. package/dist/chunk-5QFG6SCM.js.map +0 -1
  176. package/dist/chunk-65RQUN2A.js.map +0 -1
  177. package/dist/chunk-6OU6DT6H.js +0 -168
  178. package/dist/chunk-6OU6DT6H.js.map +0 -1
  179. package/dist/chunk-HS4XRPI7.cjs.map +0 -1
  180. package/dist/chunk-JAY7OZFT.cjs +0 -195
  181. package/dist/chunk-JAY7OZFT.cjs.map +0 -1
  182. package/dist/chunk-JCACPNJQ.cjs.map +0 -1
  183. package/dist/chunk-L6Z4LACC.js.map +0 -1
  184. package/dist/chunk-QOMQKAKY.cjs.map +0 -1
  185. package/dist/chunk-ZIBSZS2J.js.map +0 -1
  186. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  187. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  188. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  189. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  190. package/dist/server/handlers/auth/index.d.ts +0 -11
  191. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  192. package/dist/server/handlers/prompt.d.ts +0 -3
  193. package/dist/server/handlers/prompt.d.ts.map +0 -1
  194. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -22
  195. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  196. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  197. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  198. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -363
  199. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  200. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  201. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  202. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  203. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  204. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  205. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  206. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  207. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  208. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  209. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  210. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  211. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  212. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -17
  213. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  214. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  215. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  216. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  217. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  218. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  219. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  220. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -300
  221. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  222. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  223. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  224. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  225. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  226. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  227. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  228. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  229. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  230. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  231. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  232. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -22
  233. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  234. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts +0 -11
  235. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts.map +0 -1
  236. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  237. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
@@ -1,107 +1,44 @@
1
+ import { slash, isDependencyPartOfPackage, isBuiltinModule, getPackageName, getCompiledDepCachePath, rollupSafeName } from './chunk-HHA2Y3AS.js';
1
2
  import * as babel from '@babel/core';
2
3
  import babel__default from '@babel/core';
3
4
  import fs, { existsSync } from 'fs';
4
5
  import { readFile, writeFile } from 'fs/promises';
5
6
  import * as path2 from 'path';
6
- import path2__default, { dirname, join, normalize, relative, basename as basename$1 } from 'path';
7
+ import path2__default, { dirname, join, relative, normalize, basename as basename$1 } from 'path';
7
8
  import { spawn as spawn$1 } from 'child_process';
8
- import { getPackageInfo } from 'local-pkg';
9
- import { pathToFileURL, fileURLToPath } from 'url';
10
9
  import { rollup } from 'rollup';
11
10
  import originalEsbuild from 'rollup-plugin-esbuild';
12
11
  import commonjs from '@rollup/plugin-commonjs';
13
12
  import resolveFrom2 from 'resolve-from';
13
+ import stripJsonComments from 'strip-json-comments';
14
14
  import { createHandler } from 'typescript-paths';
15
15
  import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
16
16
  import json from '@rollup/plugin-json';
17
+ import { pathToFileURL, fileURLToPath } from 'url';
17
18
  import * as pkg from 'empathic/package';
18
19
  import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
19
20
  import { noopLogger } from '@mastra/core/logger';
20
21
  import virtual from '@rollup/plugin-virtual';
21
22
  import { builtinModules } from 'module';
23
+ import { getPackageInfo } from 'local-pkg';
22
24
  import nodeResolve from '@rollup/plugin-node-resolve';
23
- import esmShim from '@rollup/plugin-esm-shim';
25
+ import originalEsmShim from '@rollup/plugin-esm-shim';
24
26
  import { basename } from 'path/posix';
25
27
  import * as resolve from 'resolve.exports';
26
28
  import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
27
29
 
28
- // src/build/analyze.ts
29
- function getPackageName(id) {
30
- const parts = id.split("/");
31
- if (id.startsWith("@")) {
32
- return parts.slice(0, 2).join("/");
30
+ var ValidationError = class extends Error {
31
+ type;
32
+ stack;
33
+ constructor(args) {
34
+ super(args.message);
35
+ this.type = args.type;
36
+ this.stack = args.stack;
33
37
  }
34
- return parts[0];
35
- }
36
- async function getPackageRootPath(packageName, parentPath) {
37
- let rootPath;
38
- try {
39
- let options = void 0;
40
- if (parentPath) {
41
- if (!parentPath.startsWith("file://")) {
42
- parentPath = pathToFileURL(parentPath).href;
43
- }
44
- options = {
45
- paths: [parentPath]
46
- };
47
- }
48
- const pkg2 = await getPackageInfo(packageName, options);
49
- rootPath = pkg2?.rootPath ?? null;
50
- } catch (e) {
51
- rootPath = null;
52
- }
53
- return rootPath;
54
- }
55
- function getCompiledDepCachePath(rootPath, packageName) {
56
- return slash(join(rootPath, "node_modules", ".cache", packageName));
57
- }
58
- function slash(path3) {
59
- const isExtendedLengthPath = path3.startsWith("\\\\?\\");
60
- if (isExtendedLengthPath) {
61
- return path3;
62
- }
63
- return path3.replaceAll("\\", "/");
64
- }
65
- function rollupSafeName(name, rootDir) {
66
- const rel = relative(rootDir, name);
67
- let entry = slash(rel);
68
- entry = entry.replace(/^(\.\.\/)+/, "");
69
- entry = entry.replace(/^\/+/, "");
70
- entry = entry.replace(/^[A-Za-z]:\//, "");
71
- if (!entry) {
72
- entry = slash(basename$1(name));
73
- }
74
- return entry;
75
- }
76
- var NATIVE_BINDING_LOADERS = [
77
- "node-gyp-build",
78
- "prebuild-install",
79
- "bindings",
80
- "node-addon-api",
81
- "node-pre-gyp",
82
- "nan"
83
- // Native Abstractions for Node.js
84
- ];
85
- function findNativePackageModule(moduleIds) {
86
- return moduleIds.find((id) => {
87
- if (id.startsWith("\0")) {
88
- return false;
89
- }
90
- if (!id.includes("/node_modules/")) {
91
- return false;
92
- }
93
- for (const loader of NATIVE_BINDING_LOADERS) {
94
- if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {
95
- return false;
96
- }
97
- }
98
- return true;
99
- });
100
- }
101
-
102
- // src/validator/validate.ts
38
+ };
103
39
  function spawn(command, args = [], options = {}) {
104
40
  return new Promise((resolve2, reject) => {
41
+ let validationError = null;
105
42
  const childProcess = spawn$1(command, args, {
106
43
  // stdio: 'inherit',
107
44
  ...options
@@ -111,113 +48,67 @@ function spawn(command, args = [], options = {}) {
111
48
  });
112
49
  let stderr = "";
113
50
  childProcess.stderr?.on("data", (message) => {
114
- stderr += message;
51
+ try {
52
+ validationError = JSON.parse(message.toString());
53
+ } catch {
54
+ stderr += message;
55
+ }
115
56
  });
116
57
  childProcess.on("close", (code) => {
117
58
  if (code === 0) {
118
59
  resolve2();
119
60
  } else {
120
- reject(new Error(stderr));
61
+ if (validationError) {
62
+ reject(new ValidationError(validationError));
63
+ } else {
64
+ reject(new Error(stderr));
65
+ }
121
66
  }
122
67
  });
123
68
  });
124
69
  }
125
- function validate(file) {
70
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation }) {
71
+ let prefixCode = "";
72
+ if (injectESMShim) {
73
+ prefixCode = `import { fileURLToPath } from 'url';
74
+ import { dirname } from 'path';
75
+
76
+ globalThis.__filename = fileURLToPath(import.meta.url);
77
+ globalThis.__dirname = dirname(__filename);
78
+ `;
79
+ }
80
+ function errorHandler(err) {
81
+ console.error(
82
+ JSON.stringify({
83
+ type: err.name,
84
+ message: err.message,
85
+ stack: err.stack
86
+ })
87
+ );
88
+ process.exit(1);
89
+ }
126
90
  return spawn(
127
- "node",
91
+ process.execPath,
128
92
  [
129
93
  "--import",
130
94
  import.meta.resolve("@mastra/deployer/loader"),
131
95
  "--input-type=module",
96
+ "--enable-source-maps",
132
97
  "-e",
133
- `import('file://${slash(file)}')`
98
+ `${prefixCode};import('file://${slash(file)}').catch(err => {
99
+ ${errorHandler.toString()}
100
+ errorHandler(err);
101
+ })`.replaceAll(/\n/g, "")
134
102
  ],
135
103
  {
104
+ env: {
105
+ ...process.env,
106
+ MODULE_MAP: `${moduleResolveMapLocation}`
107
+ },
136
108
  cwd: dirname(file)
137
109
  }
138
110
  );
139
111
  }
140
- function removeAllOptionsFromMastraExcept(result, option, logger) {
141
- const t = babel__default.types;
142
- return {
143
- name: "remove-all-except-" + option + "-config",
144
- visitor: {
145
- ExportNamedDeclaration: {
146
- // remove all exports
147
- exit(path3) {
148
- path3.remove();
149
- }
150
- },
151
- NewExpression(path3, state) {
152
- const varDeclaratorPath = path3.findParent((path4) => t.isVariableDeclarator(path4.node));
153
- if (!varDeclaratorPath) {
154
- return;
155
- }
156
- const parentNode = path3.parentPath.node;
157
- if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
158
- return;
159
- }
160
- let mastraArgs = t.objectExpression([]);
161
- if (t.isObjectExpression(path3.node.arguments[0])) {
162
- mastraArgs = path3.node.arguments[0];
163
- }
164
- let configProperty = mastraArgs.properties.find(
165
- // @ts-ignore
166
- (prop) => prop.key.name === option
167
- );
168
- let configValue = t.objectExpression([]);
169
- const programPath = path3.scope.getProgramParent().path;
170
- if (!programPath) {
171
- return;
172
- }
173
- if (configProperty && t.isObjectProperty(configProperty) && t.isExpression(configProperty.value)) {
174
- result.hasCustomConfig = true;
175
- configValue = configProperty.value;
176
- if (t.isIdentifier(configProperty.value) && configProperty.value.name === option) {
177
- const configBinding = state.file.scope.getBinding(option);
178
- if (configBinding && t.isVariableDeclarator(configBinding.path.node)) {
179
- const id = path3.scope.generateUidIdentifier(option);
180
- configBinding.path.replaceWith(t.variableDeclarator(id, configBinding.path.node.init));
181
- configValue = id;
182
- }
183
- }
184
- }
185
- const exportDeclaration = t.exportNamedDeclaration(
186
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), configValue)]),
187
- []
188
- );
189
- programPath.node.body.push(exportDeclaration);
190
- },
191
- Program: {
192
- exit(path3) {
193
- const hasExport = path3.node.body.some(
194
- (node) => node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration"
195
- );
196
- if (!hasExport) {
197
- if (logger) {
198
- logger.warn(`Mastra ${option} config could not be extracted. Please make sure your entry file looks like this:
199
- export const mastra = new Mastra({
200
- ${option}: <value>
201
- })
202
-
203
- `);
204
- }
205
- const fallbackExportDeclaration = t.exportNamedDeclaration(
206
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), t.objectExpression([]))]),
207
- []
208
- );
209
- path3.node.body.push(fallbackExportDeclaration);
210
- }
211
- }
212
- }
213
- }
214
- };
215
- }
216
-
217
- // src/build/babel/remove-all-options-bundler.ts
218
- function removeAllOptionsExceptBundler(result, logger) {
219
- return removeAllOptionsFromMastraExcept(result, "bundler", logger);
220
- }
221
112
  function esbuild(options = {}) {
222
113
  return originalEsbuild({
223
114
  target: "node20",
@@ -227,29 +118,90 @@ function esbuild(options = {}) {
227
118
  });
228
119
  }
229
120
  var PLUGIN_NAME = "tsconfig-paths";
121
+ function hasPaths(tsConfigPath) {
122
+ try {
123
+ const content = fs.readFileSync(tsConfigPath, "utf8");
124
+ const config = JSON.parse(stripJsonComments(content));
125
+ return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
126
+ } catch {
127
+ return false;
128
+ }
129
+ }
230
130
  function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
231
- let handler;
131
+ const handlerCache = /* @__PURE__ */ new Map();
132
+ function findTsConfigForFile(filePath) {
133
+ let currentDir = path2__default.dirname(filePath);
134
+ const root = path2__default.parse(currentDir).root;
135
+ while (currentDir !== root) {
136
+ const tsConfigPath2 = path2__default.join(currentDir, "tsconfig.json");
137
+ if (fs.existsSync(tsConfigPath2)) {
138
+ if (hasPaths(tsConfigPath2)) {
139
+ return tsConfigPath2;
140
+ }
141
+ }
142
+ const tsConfigBasePath = path2__default.join(currentDir, "tsconfig.base.json");
143
+ if (fs.existsSync(tsConfigBasePath)) {
144
+ if (hasPaths(tsConfigBasePath)) {
145
+ return tsConfigBasePath;
146
+ }
147
+ }
148
+ currentDir = path2__default.dirname(currentDir);
149
+ }
150
+ return null;
151
+ }
152
+ function getHandlerForFile(filePath) {
153
+ if (tsConfigPath && typeof tsConfigPath === "string") {
154
+ if (!handlerCache.has(tsConfigPath)) {
155
+ handlerCache.set(
156
+ tsConfigPath,
157
+ createHandler({
158
+ log: () => {
159
+ },
160
+ tsConfigPath,
161
+ respectCoreModule,
162
+ falllback: (moduleName) => fs.existsSync(moduleName)
163
+ })
164
+ );
165
+ }
166
+ return handlerCache.get(tsConfigPath);
167
+ }
168
+ const configPath = findTsConfigForFile(filePath);
169
+ if (!configPath) {
170
+ return null;
171
+ }
172
+ if (!handlerCache.has(configPath)) {
173
+ handlerCache.set(
174
+ configPath,
175
+ createHandler({
176
+ log: () => {
177
+ },
178
+ tsConfigPath: configPath,
179
+ respectCoreModule,
180
+ falllback: (moduleName) => fs.existsSync(moduleName)
181
+ })
182
+ );
183
+ }
184
+ return handlerCache.get(configPath);
185
+ }
186
+ function resolveAlias(request, importer) {
187
+ const dynamicHandler = getHandlerForFile(importer);
188
+ if (!dynamicHandler) {
189
+ return null;
190
+ }
191
+ const resolved = dynamicHandler(request, normalize(importer));
192
+ return resolved;
193
+ }
232
194
  return {
233
195
  name: PLUGIN_NAME,
234
- buildStart() {
235
- handler = createHandler({
236
- log: () => {
237
- },
238
- tsConfigPath,
239
- respectCoreModule,
240
- falllback: (moduleName) => fs.existsSync(moduleName)
241
- });
242
- return;
243
- },
244
196
  async resolveId(request, importer, options) {
245
- if (!importer || request.startsWith("\0")) {
197
+ if (!importer || request.startsWith("\0") || importer.charCodeAt(0) === 0) {
246
198
  return null;
247
199
  }
248
- const moduleName = handler?.(request, normalize(importer));
200
+ const moduleName = resolveAlias(request, importer);
249
201
  if (!moduleName) {
250
202
  let importerMeta = {};
251
- const resolved = await this.resolve(request, importer, { skipSelf: true, ...options });
252
- if (!resolved) {
203
+ const resolved2 = await this.resolve(request, importer, { skipSelf: true, ...options });
204
+ if (!resolved2) {
253
205
  return null;
254
206
  }
255
207
  if (localResolve) {
@@ -257,37 +209,42 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
257
209
  importerMeta = importerInfo?.meta || {};
258
210
  if (!request.startsWith("./") && !request.startsWith("../") && importerMeta?.[PLUGIN_NAME]?.resolved) {
259
211
  return {
260
- ...resolved,
212
+ ...resolved2,
261
213
  external: !request.startsWith("hono/") && request !== "hono"
262
214
  };
263
215
  }
264
216
  }
265
217
  return {
266
- ...resolved,
218
+ ...resolved2,
267
219
  meta: {
268
- ...resolved.meta || {},
220
+ ...resolved2.meta || {},
269
221
  ...importerMeta
270
222
  }
271
223
  };
272
224
  }
273
225
  if (!path2__default.extname(moduleName)) {
274
- const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
275
- if (!resolved) {
226
+ const resolved2 = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
227
+ if (!resolved2) {
276
228
  return null;
277
229
  }
278
230
  return {
279
- ...resolved,
231
+ ...resolved2,
280
232
  meta: {
281
- ...resolved.meta,
233
+ ...resolved2.meta,
282
234
  [PLUGIN_NAME]: {
283
235
  resolved: true
284
236
  }
285
237
  }
286
238
  };
287
239
  }
240
+ const resolved = await this.resolve(moduleName, importer, { skipSelf: true, ...options });
241
+ if (!resolved) {
242
+ return null;
243
+ }
288
244
  return {
289
- id: moduleName,
245
+ ...resolved,
290
246
  meta: {
247
+ ...resolved.meta,
291
248
  [PLUGIN_NAME]: {
292
249
  resolved: true
293
250
  }
@@ -369,7 +326,117 @@ function recursiveRemoveNonReferencedNodes(code) {
369
326
  );
370
327
  });
371
328
  }
372
- function extractMastraOptionBundler(name, entryFile, transformer, result, logger) {
329
+ function removeAllOptionsFromMastraExcept(result, option, logger) {
330
+ const t = babel__default.types;
331
+ return {
332
+ name: "remove-all-except-" + option + "-config",
333
+ visitor: {
334
+ ExportNamedDeclaration: {
335
+ // remove all exports
336
+ exit(path3) {
337
+ path3.remove();
338
+ }
339
+ },
340
+ NewExpression(path3, state) {
341
+ const varDeclaratorPath = path3.findParent((path4) => t.isVariableDeclarator(path4.node));
342
+ if (!varDeclaratorPath) {
343
+ return;
344
+ }
345
+ const parentNode = path3.parentPath.node;
346
+ if (!t.isVariableDeclarator(parentNode) || !t.isIdentifier(parentNode.id) || parentNode.id.name !== "mastra") {
347
+ return;
348
+ }
349
+ let mastraArgs = t.objectExpression([]);
350
+ if (t.isObjectExpression(path3.node.arguments[0])) {
351
+ mastraArgs = path3.node.arguments[0];
352
+ }
353
+ let configProperty = mastraArgs.properties.find(
354
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === option
355
+ );
356
+ let configValue = t.objectExpression([]);
357
+ const programPath = path3.scope.getProgramParent().path;
358
+ if (!programPath) {
359
+ return;
360
+ }
361
+ if (configProperty && t.isObjectProperty(configProperty) && t.isExpression(configProperty.value)) {
362
+ result.hasCustomConfig = true;
363
+ configValue = configProperty.value;
364
+ if (t.isIdentifier(configProperty.value) && configProperty.value.name === option) {
365
+ const configBinding = state.file.scope.getBinding(option);
366
+ if (configBinding && t.isVariableDeclarator(configBinding.path.node)) {
367
+ const id = path3.scope.generateUidIdentifier(option);
368
+ configBinding.path.replaceWith(t.variableDeclarator(id, configBinding.path.node.init));
369
+ configValue = id;
370
+ }
371
+ }
372
+ }
373
+ const exportDeclaration = t.exportNamedDeclaration(
374
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), configValue)]),
375
+ []
376
+ );
377
+ programPath.node.body.push(exportDeclaration);
378
+ },
379
+ Program: {
380
+ exit(path3) {
381
+ const hasExport = path3.node.body.some(
382
+ (node) => node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration"
383
+ );
384
+ if (!hasExport) {
385
+ if (logger) {
386
+ logger.warn(`Mastra ${option} config could not be extracted. Please make sure your entry file looks like this:
387
+ export const mastra = new Mastra({
388
+ ${option}: <value>
389
+ })
390
+
391
+ `);
392
+ }
393
+ const fallbackExportDeclaration = t.exportNamedDeclaration(
394
+ t.variableDeclaration("const", [t.variableDeclarator(t.identifier(option), t.objectExpression([]))]),
395
+ []
396
+ );
397
+ path3.node.body.push(fallbackExportDeclaration);
398
+ }
399
+ }
400
+ }
401
+ }
402
+ };
403
+ }
404
+
405
+ // src/build/plugins/remove-all-except.ts
406
+ function removeAllOptionsFromMastraExceptPlugin(mastraEntry, name, result, options) {
407
+ return {
408
+ name: `remove-${name}`,
409
+ transform(code, id) {
410
+ if (id !== mastraEntry) {
411
+ return;
412
+ }
413
+ return new Promise((resolve2, reject) => {
414
+ babel.transform(
415
+ code,
416
+ {
417
+ babelrc: false,
418
+ configFile: false,
419
+ filename: id,
420
+ plugins: [removeAllOptionsFromMastraExcept(result, name, options?.logger)],
421
+ sourceMaps: options?.sourcemap
422
+ },
423
+ (err, result2) => {
424
+ if (err) {
425
+ return reject(err);
426
+ }
427
+ resolve2({
428
+ code: result2.code,
429
+ map: result2.map
430
+ });
431
+ }
432
+ );
433
+ });
434
+ }
435
+ };
436
+ }
437
+
438
+ // src/build/shared/extract-mastra-option.ts
439
+ function extractMastraOptionBundler(name, entryFile, result, logger) {
373
440
  return rollup({
374
441
  logLevel: "silent",
375
442
  input: {
@@ -390,34 +457,7 @@ function extractMastraOptionBundler(name, entryFile, transformer, result, logger
390
457
  ignoreTryCatch: false
391
458
  }),
392
459
  json(),
393
- {
394
- name: `extract-${name}-config`,
395
- transform(code, id) {
396
- if (id !== entryFile) {
397
- return;
398
- }
399
- return new Promise((resolve2, reject) => {
400
- babel.transform(
401
- code,
402
- {
403
- babelrc: false,
404
- configFile: false,
405
- filename: id,
406
- plugins: [transformer(result, logger)]
407
- },
408
- (err, result2) => {
409
- if (err) {
410
- return reject(err);
411
- }
412
- resolve2({
413
- code: result2.code,
414
- map: result2.map
415
- });
416
- }
417
- );
418
- });
419
- }
420
- },
460
+ removeAllOptionsFromMastraExceptPlugin(entryFile, name, result, { logger }),
421
461
  // let esbuild remove all unused imports
422
462
  esbuild(),
423
463
  {
@@ -434,11 +474,11 @@ function extractMastraOptionBundler(name, entryFile, transformer, result, logger
434
474
  ]
435
475
  });
436
476
  }
437
- async function extractMastraOption(name, entryFile, transformer, outputDir, logger) {
477
+ async function extractMastraOption(name, entryFile, outputDir, logger) {
438
478
  const result = {
439
479
  hasCustomConfig: false
440
480
  };
441
- const bundler = await extractMastraOptionBundler(name, entryFile, transformer, result, logger);
481
+ const bundler = await extractMastraOptionBundler(name, entryFile, result, logger);
442
482
  const output = await bundler.write({
443
483
  dir: outputDir,
444
484
  format: "es",
@@ -448,7 +488,7 @@ async function extractMastraOption(name, entryFile, transformer, outputDir, logg
448
488
  const configPath = `${outputDir}/${name}-config.mjs`;
449
489
  return {
450
490
  bundleOutput: output,
451
- getConfig: () => import(`file:${configPath}`).then((m) => m[name])
491
+ getConfig: () => import(pathToFileURL(configPath).href).then((m) => m[name])
452
492
  };
453
493
  }
454
494
  return null;
@@ -456,13 +496,7 @@ async function extractMastraOption(name, entryFile, transformer, outputDir, logg
456
496
 
457
497
  // src/build/bundlerOptions.ts
458
498
  async function getBundlerOptions(entryFile, outputDir, logger) {
459
- const result = await extractMastraOption(
460
- "bundler",
461
- entryFile,
462
- removeAllOptionsExceptBundler,
463
- outputDir,
464
- logger
465
- );
499
+ const result = await extractMastraOption("bundler", entryFile, outputDir, logger);
466
500
  if (!result) {
467
501
  return null;
468
502
  }
@@ -531,8 +565,57 @@ function isNodeBuiltin(dep) {
531
565
  const [pkg2] = dep.split("/");
532
566
  return dep.startsWith("node:") || builtinModules.includes(dep) || builtinModules.includes(pkg2);
533
567
  }
568
+ async function getPackageRootPath(packageName, parentPath) {
569
+ let rootPath;
570
+ try {
571
+ let options = void 0;
572
+ if (parentPath) {
573
+ if (!parentPath.startsWith("file://")) {
574
+ parentPath = pathToFileURL(parentPath).href;
575
+ }
576
+ options = {
577
+ paths: [parentPath]
578
+ };
579
+ }
580
+ const pkg2 = await getPackageInfo(packageName, options);
581
+ rootPath = pkg2?.rootPath ?? null;
582
+ } catch (e) {
583
+ rootPath = null;
584
+ }
585
+ return rootPath;
586
+ }
587
+
588
+ // src/build/analyze/constants.ts
589
+ var DEPS_TO_IGNORE = ["#tools"];
590
+ var GLOBAL_EXTERNALS = [
591
+ "pino",
592
+ "pino-pretty",
593
+ "@libsql/client",
594
+ "pg",
595
+ "libsql",
596
+ "#tools",
597
+ "typescript",
598
+ "undici",
599
+ "readable-stream"
600
+ ];
601
+ var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
534
602
  function removeDeployer() {
535
603
  const t = babel__default.types;
604
+ function removeDeployerFromObject(objectExpr, scope) {
605
+ const deployerProp = objectExpr.properties.find(
606
+ (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
607
+ );
608
+ if (deployerProp) {
609
+ objectExpr.properties = objectExpr.properties.filter((prop) => prop !== deployerProp);
610
+ if (t.isIdentifier(deployerProp.value)) {
611
+ const deployerBinding = scope.getBinding(deployerProp.value.name);
612
+ if (deployerBinding) {
613
+ deployerBinding.path?.parentPath?.remove();
614
+ }
615
+ }
616
+ }
617
+ return deployerProp;
618
+ }
536
619
  return {
537
620
  name: "remove-deployer",
538
621
  visitor: {
@@ -548,23 +631,30 @@ function removeDeployer() {
548
631
  if (!state.hasReplaced) {
549
632
  state.hasReplaced = true;
550
633
  const newMastraObj = t.cloneNode(path3.node);
551
- if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.[0]) {
552
- const deployer = newMastraObj.arguments[0].properties.find(
553
- (prop) => t.isObjectProperty(prop) && t.isIdentifier(prop.key) && prop.key.name === "deployer"
554
- );
555
- if (!deployer) {
556
- return;
634
+ if (t.isObjectExpression(newMastraObj.arguments[0]) && newMastraObj.arguments[0].properties?.length) {
635
+ const objectArg = newMastraObj.arguments[0];
636
+ let foundDeployer = false;
637
+ const directDeployer = removeDeployerFromObject(objectArg, state.file.scope);
638
+ if (directDeployer) {
639
+ foundDeployer = true;
557
640
  }
558
- newMastraObj.arguments[0].properties = newMastraObj.arguments[0].properties.filter(
559
- (prop) => prop !== deployer
560
- );
561
- if (t.isObjectProperty(deployer) && t.isIdentifier(deployer.value)) {
562
- const deployerBinding = state.file.scope.getBinding(deployer.value.name);
563
- if (deployerBinding) {
564
- deployerBinding?.path?.parentPath?.remove();
641
+ for (const prop of objectArg.properties) {
642
+ if (t.isSpreadElement(prop) && t.isIdentifier(prop.argument)) {
643
+ const spreadBinding = state.file.scope.getBinding(prop.argument.name);
644
+ if (spreadBinding?.path && t.isVariableDeclarator(spreadBinding.path.node)) {
645
+ const init = spreadBinding.path.node.init;
646
+ if (t.isObjectExpression(init)) {
647
+ const spreadDeployer = removeDeployerFromObject(init, state.file.scope);
648
+ if (spreadDeployer) {
649
+ foundDeployer = true;
650
+ }
651
+ }
652
+ }
565
653
  }
566
654
  }
567
- path3.replaceWith(newMastraObj);
655
+ if (foundDeployer) {
656
+ path3.replaceWith(newMastraObj);
657
+ }
568
658
  }
569
659
  }
570
660
  }
@@ -605,20 +695,6 @@ function removeDeployer2(mastraEntry, options) {
605
695
  };
606
696
  }
607
697
 
608
- // src/build/analyze/constants.ts
609
- var DEPS_TO_IGNORE = ["#tools"];
610
- var GLOBAL_EXTERNALS = [
611
- "pino",
612
- "pino-pretty",
613
- "@libsql/client",
614
- "pg",
615
- "libsql",
616
- "#tools",
617
- "typescript",
618
- "undici"
619
- ];
620
- var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
621
-
622
698
  // src/build/analyze/analyzeEntry.ts
623
699
  function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
624
700
  const normalizedMastraEntry = slash(mastraEntry);
@@ -658,14 +734,17 @@ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabl
658
734
  transformMixedEsModules: true,
659
735
  extensions: [".js", ".ts"]
660
736
  }),
661
- removeDeployer2(mastraEntry, { sourcemap: sourcemapEnabled }),
737
+ removeDeployer2(mastraEntry, {
738
+ sourcemap: sourcemapEnabled
739
+ }),
662
740
  esbuild()
663
741
  ]
664
742
  );
665
743
  return plugins;
666
744
  }
667
745
  async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
668
- logger
746
+ logger,
747
+ shouldCheckTransitiveDependencies
669
748
  }) {
670
749
  const depsToOptimize = /* @__PURE__ */ new Map();
671
750
  if (!output.facadeModuleId) {
@@ -678,7 +757,7 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
678
757
  entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
679
758
  }
680
759
  for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
681
- if (isNodeBuiltin(dependency) || DEPS_TO_IGNORE.includes(dependency)) {
760
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
682
761
  continue;
683
762
  }
684
763
  const pkgName = getPackageName(dependency);
@@ -689,7 +768,11 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
689
768
  isWorkspace = workspaceMap.has(pkgName);
690
769
  }
691
770
  const normalizedRootPath = rootPath ? slash(rootPath) : null;
692
- depsToOptimize.set(dependency, { exports: bindings, rootPath: normalizedRootPath, isWorkspace });
771
+ depsToOptimize.set(dependency, {
772
+ exports: bindings,
773
+ rootPath: normalizedRootPath,
774
+ isWorkspace
775
+ });
693
776
  }
694
777
  async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
695
778
  if (currentDepth >= maxDepth) {
@@ -733,12 +816,18 @@ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot,
733
816
  await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
734
817
  }
735
818
  }
736
- await checkTransitiveDependencies(initialDepsToOptimize);
819
+ if (shouldCheckTransitiveDependencies) {
820
+ await checkTransitiveDependencies(initialDepsToOptimize);
821
+ }
737
822
  const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
738
823
  if (dynamicImports.length) {
739
824
  for (const dynamicImport of dynamicImports) {
740
825
  if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
741
- depsToOptimize.set(dynamicImport, { exports: ["*"], rootPath: null, isWorkspace: false });
826
+ depsToOptimize.set(dynamicImport, {
827
+ exports: ["*"],
828
+ rootPath: null,
829
+ isWorkspace: false
830
+ });
742
831
  }
743
832
  }
744
833
  }
@@ -752,13 +841,14 @@ async function analyzeEntry({
752
841
  sourcemapEnabled,
753
842
  workspaceMap,
754
843
  projectRoot,
755
- initialDepsToOptimize = /* @__PURE__ */ new Map()
844
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
756
845
  // used to avoid infinite recursion
846
+ shouldCheckTransitiveDependencies = false
757
847
  }) {
758
848
  const optimizerBundler = await rollup({
759
849
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
760
850
  input: isVirtualFile ? "#entry" : entry,
761
- treeshake: "smallest",
851
+ treeshake: false,
762
852
  preserveSymlinks: true,
763
853
  plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
764
854
  external: DEPS_TO_IGNORE
@@ -774,7 +864,8 @@ async function analyzeEntry({
774
864
  projectRoot,
775
865
  initialDepsToOptimize,
776
866
  {
777
- logger
867
+ logger,
868
+ shouldCheckTransitiveDependencies
778
869
  }
779
870
  );
780
871
  return {
@@ -785,6 +876,27 @@ async function analyzeEntry({
785
876
  }
786
877
  };
787
878
  }
879
+ var FilenameDeclarationRegex = /(?:const|let|var)\s+__filename/;
880
+ var DirnameDeclarationRegex = /(?:const|let|var)\s+__dirname/;
881
+ function esmShim() {
882
+ const original = originalEsmShim();
883
+ return {
884
+ name: "esm-shim",
885
+ renderChunk(code, chunk, opts, meta) {
886
+ const hasFilename = code.includes("__filename");
887
+ const hasDirname = code.includes("__dirname");
888
+ const userDeclaredFilename = hasFilename && FilenameDeclarationRegex.test(code);
889
+ const userDeclaredDirname = hasDirname && DirnameDeclarationRegex.test(code);
890
+ if (userDeclaredFilename || userDeclaredDirname) {
891
+ return null;
892
+ }
893
+ if (typeof original.renderChunk === "function") {
894
+ return original.renderChunk.call(this, code, chunk, opts, meta);
895
+ }
896
+ return null;
897
+ }
898
+ };
899
+ }
788
900
  function aliasHono() {
789
901
  return {
790
902
  name: "hono-alias",
@@ -797,6 +909,114 @@ function aliasHono() {
797
909
  }
798
910
  };
799
911
  }
912
+ function nodeGypDetector() {
913
+ const modulesToTrack = /* @__PURE__ */ new Set();
914
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
915
+ return {
916
+ name: "node-gyp-build-detector",
917
+ moduleParsed(info) {
918
+ if (!info.meta?.commonjs?.requires?.length) {
919
+ return;
920
+ }
921
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
922
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
923
+ );
924
+ if (!hasNodeGypBuild) {
925
+ return;
926
+ }
927
+ modulesToTrack.add(info.id);
928
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
929
+ },
930
+ async generateBundle(options, bundle) {
931
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
932
+ for (const [fileName, chunk] of Object.entries(bundle)) {
933
+ if (chunk.type === "chunk") {
934
+ for (const moduleId of chunk.moduleIds) {
935
+ if (modulesToTrackPackageInfo.has(moduleId)) {
936
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
937
+ if (!binaryMapByChunk.has(fileName)) {
938
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
939
+ }
940
+ if (pkgInfo?.packageJson?.name) {
941
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
942
+ }
943
+ }
944
+ }
945
+ }
946
+ }
947
+ const binaryMapJson = Object.fromEntries(
948
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
949
+ );
950
+ this.emitFile({
951
+ type: "asset",
952
+ name: "binary-map.json",
953
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
954
+ });
955
+ }
956
+ };
957
+ }
958
+
959
+ // src/build/plugins/subpath-externals-resolver.ts
960
+ function subpathExternalsResolver(externals) {
961
+ return {
962
+ name: "subpath-externals-resolver",
963
+ resolveId(id) {
964
+ if (id.startsWith(".") || id.startsWith("/")) {
965
+ return null;
966
+ }
967
+ const isPartOfExternals = externals.some((external) => isDependencyPartOfPackage(id, external));
968
+ if (isPartOfExternals) {
969
+ return {
970
+ id,
971
+ external: true
972
+ };
973
+ }
974
+ }
975
+ };
976
+ }
977
+ function moduleResolveMap(externals, projectRoot) {
978
+ const importMap = /* @__PURE__ */ new Map();
979
+ return {
980
+ name: "module-resolve-map",
981
+ moduleParsed(info) {
982
+ if (info.importedIds.length === 0 || !info.id) {
983
+ return;
984
+ }
985
+ for (const importedId of info.importedIds) {
986
+ for (const external of externals) {
987
+ if (isDependencyPartOfPackage(importedId, external)) {
988
+ importMap.set(external, info.id);
989
+ }
990
+ }
991
+ }
992
+ },
993
+ async generateBundle(options, bundle) {
994
+ const resolveMap = /* @__PURE__ */ new Map();
995
+ for (const [fileName, chunk] of Object.entries(bundle)) {
996
+ if (chunk.type === "chunk") {
997
+ for (const [external, resolvedFrom] of importMap) {
998
+ if (chunk.moduleIds.includes(resolvedFrom)) {
999
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
1000
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
1001
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
1002
+ resolveMap.set(fullPath, innerMap);
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+ const resolveMapJson = Object.fromEntries(
1008
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
1009
+ );
1010
+ this.emitFile({
1011
+ type: "asset",
1012
+ name: "module-resolve-map.json",
1013
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
1014
+ });
1015
+ }
1016
+ };
1017
+ }
1018
+
1019
+ // src/build/analyze/bundleExternals.ts
800
1020
  function prepareEntryFileName(name, rootDir) {
801
1021
  return rollupSafeName(name, rootDir);
802
1022
  }
@@ -806,7 +1026,7 @@ function createVirtualDependencies(depsToOptimize, {
806
1026
  outputDir,
807
1027
  bundlerOptions
808
1028
  }) {
809
- const { isDev = false } = bundlerOptions || {};
1029
+ const { isDev = false, externalsPreset = false } = bundlerOptions || {};
810
1030
  const fileNameToDependencyMap = /* @__PURE__ */ new Map();
811
1031
  const optimizedDependencyEntries = /* @__PURE__ */ new Map();
812
1032
  const rootDir = workspaceRoot || projectRoot;
@@ -838,7 +1058,7 @@ function createVirtualDependencies(depsToOptimize, {
838
1058
  virtual: virtualFile.join("\n")
839
1059
  });
840
1060
  }
841
- if (isDev) {
1061
+ if (isDev || externalsPreset) {
842
1062
  for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
843
1063
  if (!isWorkspace || !rootPath || !workspaceRoot) {
844
1064
  continue;
@@ -862,7 +1082,8 @@ async function getInputPlugins2(virtualDependencies, {
862
1082
  transpilePackages,
863
1083
  workspaceMap,
864
1084
  bundlerOptions,
865
- rootDir
1085
+ rootDir,
1086
+ externals
866
1087
  }) {
867
1088
  const transpilePackagesMap = /* @__PURE__ */ new Map();
868
1089
  for (const pkg2 of transpilePackages) {
@@ -883,6 +1104,7 @@ async function getInputPlugins2(virtualDependencies, {
883
1104
  {}
884
1105
  )
885
1106
  ),
1107
+ subpathExternalsResolver(externals),
886
1108
  transpilePackagesMap.size ? esbuild({
887
1109
  format: "esm",
888
1110
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -893,7 +1115,7 @@ async function getInputPlugins2(virtualDependencies, {
893
1115
  }
894
1116
  })
895
1117
  }) : null,
896
- bundlerOptions.isDev ? {
1118
+ bundlerOptions.noBundling ? {
897
1119
  name: "alias-optimized-deps",
898
1120
  async resolveId(id, importer, options) {
899
1121
  if (!virtualDependencies.has(id)) {
@@ -911,7 +1133,8 @@ async function getInputPlugins2(virtualDependencies, {
911
1133
  if (!resolvedPath) {
912
1134
  resolvedPath = pkgJson.main ?? "index.js";
913
1135
  }
914
- return await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1136
+ const resolved = await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1137
+ return resolved;
915
1138
  }
916
1139
  } : null,
917
1140
  optimizeLodashImports({
@@ -922,14 +1145,16 @@ async function getInputPlugins2(virtualDependencies, {
922
1145
  transformMixedEsModules: true,
923
1146
  ignoreTryCatch: false
924
1147
  }),
925
- bundlerOptions.isDev ? null : nodeResolve({
1148
+ bundlerOptions.noBundling ? null : nodeResolve({
926
1149
  preferBuiltins: true,
927
1150
  exportConditions: ["node"]
928
1151
  }),
929
- bundlerOptions.isDev ? esmShim() : null,
1152
+ bundlerOptions.noBundling ? esmShim() : null,
930
1153
  // hono is imported from deployer, so we need to resolve from here instead of the project root
931
1154
  aliasHono(),
932
1155
  json(),
1156
+ nodeGypDetector(),
1157
+ moduleResolveMap(externals, rootDir),
933
1158
  {
934
1159
  name: "not-found-resolver",
935
1160
  resolveId: {
@@ -977,6 +1202,16 @@ async function buildExternalDependencies(virtualDependencies, {
977
1202
  if (virtualDependencies.size === 0) {
978
1203
  return [];
979
1204
  }
1205
+ const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;
1206
+ const plugins = await getInputPlugins2(virtualDependencies, {
1207
+ transpilePackages: packagesToTranspile,
1208
+ workspaceMap,
1209
+ bundlerOptions: {
1210
+ noBundling
1211
+ },
1212
+ rootDir,
1213
+ externals
1214
+ });
980
1215
  const bundler = await rollup({
981
1216
  logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
982
1217
  input: Array.from(virtualDependencies.entries()).reduce(
@@ -987,25 +1222,22 @@ async function buildExternalDependencies(virtualDependencies, {
987
1222
  {}
988
1223
  ),
989
1224
  external: externals,
990
- treeshake: "smallest",
991
- plugins: getInputPlugins2(virtualDependencies, {
992
- transpilePackages: packagesToTranspile,
993
- workspaceMap,
994
- bundlerOptions,
995
- rootDir
996
- })
1225
+ treeshake: noBundling ? false : "safest",
1226
+ plugins
997
1227
  });
998
1228
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
999
1229
  const { output } = await bundler.write({
1000
1230
  format: "esm",
1001
1231
  dir: rootDir,
1002
1232
  entryFileNames: "[name].mjs",
1233
+ // used to get the filename of the actual error
1234
+ sourcemap: true,
1003
1235
  /**
1004
1236
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1005
1237
  * So we want to write them to the `.mastra/output` folder as well.
1006
1238
  */
1007
1239
  chunkFileNames: (chunkInfo) => {
1008
- if (bundlerOptions.isDev) {
1240
+ if (noBundling) {
1009
1241
  const importedFromPackages = /* @__PURE__ */ new Set();
1010
1242
  for (const moduleId of chunkInfo.moduleIds) {
1011
1243
  const normalized = slash(moduleId);
@@ -1037,6 +1269,7 @@ async function buildExternalDependencies(virtualDependencies, {
1037
1269
  }
1038
1270
  return `${outputDirRelative}/[name].mjs`;
1039
1271
  },
1272
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1040
1273
  hoistTransitiveImports: false
1041
1274
  });
1042
1275
  await bundler.close();
@@ -1045,7 +1278,7 @@ async function buildExternalDependencies(virtualDependencies, {
1045
1278
  function findExternalImporter(module, external, allOutputs) {
1046
1279
  const capturedFiles = /* @__PURE__ */ new Set();
1047
1280
  for (const id of module.imports) {
1048
- if (id === external) {
1281
+ if (isDependencyPartOfPackage(id, external)) {
1049
1282
  return module;
1050
1283
  } else {
1051
1284
  if (id.endsWith(".mjs")) {
@@ -1066,19 +1299,31 @@ function findExternalImporter(module, external, allOutputs) {
1066
1299
  }
1067
1300
  async function bundleExternals(depsToOptimize, outputDir, options) {
1068
1301
  const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions = {} } = options;
1069
- const {
1070
- externals: customExternals = [],
1071
- transpilePackages = [],
1072
- isDev = false} = bundlerOptions || {};
1073
- const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...customExternals];
1302
+ const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
1303
+ let externalsPreset = false;
1304
+ if (customExternals === true) {
1305
+ externalsPreset = true;
1306
+ }
1307
+ const externalsList = Array.isArray(customExternals) ? customExternals : [];
1308
+ const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...externalsList];
1074
1309
  const workspacePackagesNames = Array.from(workspaceMap.keys());
1075
1310
  const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
1311
+ const extractedExternals = /* @__PURE__ */ new Map();
1312
+ if (externalsPreset) {
1313
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1314
+ if (!metadata.isWorkspace) {
1315
+ extractedExternals.set(dep, metadata.rootPath ?? dep);
1316
+ depsToOptimize.delete(dep);
1317
+ }
1318
+ }
1319
+ }
1076
1320
  const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {
1077
1321
  workspaceRoot,
1078
1322
  outputDir,
1079
1323
  projectRoot,
1080
1324
  bundlerOptions: {
1081
- isDev
1325
+ isDev,
1326
+ externalsPreset
1082
1327
  }
1083
1328
  });
1084
1329
  const output = await buildExternalDependencies(optimizedDependencyEntries, {
@@ -1088,10 +1333,11 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1088
1333
  rootDir: workspaceRoot || projectRoot,
1089
1334
  outputDir,
1090
1335
  bundlerOptions: {
1091
- isDev
1336
+ isDev,
1337
+ externalsPreset
1092
1338
  }
1093
1339
  });
1094
- const moduleResolveMap = /* @__PURE__ */ new Map();
1340
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1095
1341
  const filteredChunks = output.filter((o) => o.type === "chunk");
1096
1342
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1097
1343
  for (const external of allExternals) {
@@ -1101,10 +1347,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1101
1347
  const importer = findExternalImporter(o, external, filteredChunks);
1102
1348
  if (importer) {
1103
1349
  const fullPath = path2.join(workspaceRoot || projectRoot, importer.fileName);
1104
- let innerMap = moduleResolveMap.get(fullPath);
1350
+ let innerMap = moduleResolveMap2.get(fullPath);
1105
1351
  if (!innerMap) {
1106
1352
  innerMap = /* @__PURE__ */ new Map();
1107
- moduleResolveMap.set(fullPath, innerMap);
1353
+ moduleResolveMap2.set(fullPath, innerMap);
1108
1354
  }
1109
1355
  if (importer.moduleIds.length) {
1110
1356
  innerMap.set(
@@ -1116,15 +1362,125 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1116
1362
  }
1117
1363
  }
1118
1364
  const usedExternals = /* @__PURE__ */ Object.create(null);
1119
- for (const [fullPath, innerMap] of moduleResolveMap) {
1365
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1120
1366
  const innerObj = /* @__PURE__ */ Object.create(null);
1121
1367
  for (const [external, value] of innerMap) {
1122
1368
  innerObj[external] = value;
1123
1369
  }
1124
1370
  usedExternals[fullPath] = innerObj;
1125
1371
  }
1372
+ if (extractedExternals.size > 0) {
1373
+ const syntheticPath = path2.join(workspaceRoot || projectRoot, "__externals__");
1374
+ const externalsObj = /* @__PURE__ */ Object.create(null);
1375
+ for (const [dep, rootPath] of extractedExternals) {
1376
+ externalsObj[dep] = rootPath;
1377
+ }
1378
+ usedExternals[syntheticPath] = externalsObj;
1379
+ }
1126
1380
  return { output, fileNameToDependencyMap, usedExternals };
1127
1381
  }
1382
+
1383
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1384
+ var UNKNOWN_FUNCTION = "<unknown>";
1385
+ function parse(stackString) {
1386
+ var lines = stackString.split("\n");
1387
+ return lines.reduce(function(stack, line) {
1388
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1389
+ if (parseResult) {
1390
+ stack.push(parseResult);
1391
+ }
1392
+ return stack;
1393
+ }, []);
1394
+ }
1395
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1396
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1397
+ function parseChrome(line) {
1398
+ var parts = chromeRe.exec(line);
1399
+ if (!parts) {
1400
+ return null;
1401
+ }
1402
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1403
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1404
+ var submatch = chromeEvalRe.exec(parts[2]);
1405
+ if (isEval && submatch != null) {
1406
+ parts[2] = submatch[1];
1407
+ parts[3] = submatch[2];
1408
+ parts[4] = submatch[3];
1409
+ }
1410
+ return {
1411
+ file: !isNative ? parts[2] : null,
1412
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1413
+ arguments: isNative ? [parts[2]] : [],
1414
+ lineNumber: parts[3] ? +parts[3] : null,
1415
+ column: parts[4] ? +parts[4] : null
1416
+ };
1417
+ }
1418
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1419
+ function parseWinjs(line) {
1420
+ var parts = winjsRe.exec(line);
1421
+ if (!parts) {
1422
+ return null;
1423
+ }
1424
+ return {
1425
+ file: parts[2],
1426
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1427
+ arguments: [],
1428
+ lineNumber: +parts[3],
1429
+ column: parts[4] ? +parts[4] : null
1430
+ };
1431
+ }
1432
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1433
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1434
+ function parseGecko(line) {
1435
+ var parts = geckoRe.exec(line);
1436
+ if (!parts) {
1437
+ return null;
1438
+ }
1439
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1440
+ var submatch = geckoEvalRe.exec(parts[3]);
1441
+ if (isEval && submatch != null) {
1442
+ parts[3] = submatch[1];
1443
+ parts[4] = submatch[2];
1444
+ parts[5] = null;
1445
+ }
1446
+ return {
1447
+ file: parts[3],
1448
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1449
+ arguments: parts[2] ? parts[2].split(",") : [],
1450
+ lineNumber: parts[4] ? +parts[4] : null,
1451
+ column: parts[5] ? +parts[5] : null
1452
+ };
1453
+ }
1454
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1455
+ function parseJSC(line) {
1456
+ var parts = javaScriptCoreRe.exec(line);
1457
+ if (!parts) {
1458
+ return null;
1459
+ }
1460
+ return {
1461
+ file: parts[3],
1462
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1463
+ arguments: [],
1464
+ lineNumber: +parts[4],
1465
+ column: parts[5] ? +parts[5] : null
1466
+ };
1467
+ }
1468
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1469
+ function parseNode(line) {
1470
+ var parts = nodeRe.exec(line);
1471
+ if (!parts) {
1472
+ return null;
1473
+ }
1474
+ return {
1475
+ file: parts[2],
1476
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1477
+ arguments: [],
1478
+ lineNumber: +parts[3],
1479
+ column: parts[4] ? +parts[4] : null
1480
+ };
1481
+ }
1482
+
1483
+ // src/build/analyze.ts
1128
1484
  function throwExternalDependencyError({
1129
1485
  errorId,
1130
1486
  moduleName,
@@ -1148,6 +1504,110 @@ export const mastra = new Mastra({
1148
1504
  })`
1149
1505
  });
1150
1506
  }
1507
+ function getPackageNameFromBundledModuleName(moduleName) {
1508
+ const chunks = moduleName.split("-");
1509
+ if (!chunks.length) {
1510
+ return moduleName;
1511
+ }
1512
+ if (chunks[0]?.startsWith("@")) {
1513
+ return chunks.slice(0, 2).join("/");
1514
+ }
1515
+ return chunks[0];
1516
+ }
1517
+ function validateError(err, file, {
1518
+ binaryMapData,
1519
+ workspaceMap
1520
+ }) {
1521
+ let moduleName = null;
1522
+ let errorConfig = null;
1523
+ if (err instanceof ValidationError) {
1524
+ const parsedStack = parse(err.stack);
1525
+ if (err.type === "TypeError") {
1526
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1527
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1528
+ if (stacktraceFrame) {
1529
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1530
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1531
+ } else {
1532
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1533
+ }
1534
+ errorConfig = {
1535
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1536
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1537
+ };
1538
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1539
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1540
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1541
+ errorConfig = {
1542
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1543
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1544
+ };
1545
+ if (moduleName === parentModuleName) {
1546
+ return;
1547
+ }
1548
+ }
1549
+ }
1550
+ if (err.message.includes("No native build was found")) {
1551
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1552
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1553
+ errorConfig = {
1554
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1555
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1556
+ };
1557
+ }
1558
+ if (moduleName && workspaceMap.has(moduleName)) {
1559
+ throw new MastraError({
1560
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1561
+ domain: ErrorDomain.DEPLOYER,
1562
+ category: ErrorCategory.USER,
1563
+ details: {
1564
+ // importFile: moduleName,
1565
+ packageName: moduleName
1566
+ },
1567
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1568
+ Error: ${err.stack}`
1569
+ });
1570
+ }
1571
+ if (errorConfig && moduleName) {
1572
+ throwExternalDependencyError({
1573
+ errorId: errorConfig.id,
1574
+ moduleName,
1575
+ packageName: moduleName,
1576
+ messagePrefix: errorConfig.messagePrefix
1577
+ });
1578
+ }
1579
+ }
1580
+ async function validateFile(root, file, {
1581
+ binaryMapData,
1582
+ moduleResolveMapLocation,
1583
+ logger,
1584
+ workspaceMap
1585
+ }) {
1586
+ try {
1587
+ if (!file.isDynamicEntry && file.isEntry) {
1588
+ await validate(join(root, file.fileName), {
1589
+ moduleResolveMapLocation,
1590
+ injectESMShim: false
1591
+ });
1592
+ }
1593
+ } catch (err) {
1594
+ let errorToHandle = err;
1595
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1596
+ try {
1597
+ await validate(join(root, file.fileName), {
1598
+ moduleResolveMapLocation,
1599
+ injectESMShim: true
1600
+ });
1601
+ errorToHandle = null;
1602
+ } catch (err2) {
1603
+ errorToHandle = err2;
1604
+ }
1605
+ }
1606
+ if (errorToHandle instanceof Error) {
1607
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1608
+ }
1609
+ }
1610
+ }
1151
1611
  async function validateOutput({
1152
1612
  output,
1153
1613
  reverseVirtualReferenceMap,
@@ -1161,60 +1621,30 @@ async function validateOutput({
1161
1621
  externalDependencies: /* @__PURE__ */ new Set(),
1162
1622
  workspaceMap
1163
1623
  };
1164
- await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1165
1624
  for (const deps of Object.values(usedExternals)) {
1166
1625
  for (const dep of Object.keys(deps)) {
1167
1626
  result.externalDependencies.add(dep);
1168
1627
  }
1169
1628
  }
1629
+ let binaryMapData = {};
1630
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1631
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1632
+ binaryMapData = JSON.parse(binaryMap);
1633
+ }
1170
1634
  for (const file of output) {
1171
1635
  if (file.type === "asset") {
1172
1636
  continue;
1173
1637
  }
1174
- try {
1175
- logger.debug(`Validating if ${file.fileName} is a valid module.`);
1176
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1177
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1178
- }
1179
- if (!file.isDynamicEntry && file.isEntry) {
1180
- await validate(join(projectRoot, file.fileName));
1181
- }
1182
- } catch (err) {
1183
- if (err instanceof Error) {
1184
- let moduleName = null;
1185
- let errorConfig = null;
1186
- if (err.message.includes("[ERR_MODULE_NOT_FOUND]")) {
1187
- const moduleIdName = file.moduleIds.length >= 2 ? file.moduleIds[file.moduleIds.length - 2] : void 0;
1188
- const fallbackName = file.name.split("/").pop();
1189
- moduleName = moduleIdName ?? fallbackName;
1190
- errorConfig = {
1191
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1192
- messagePrefix: "Mastra wasn't able to build your project. Please add"
1193
- };
1194
- } else if (err.message.includes("Error: No native build was found for ")) {
1195
- moduleName = findNativePackageModule(file.moduleIds);
1196
- errorConfig = {
1197
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1198
- messagePrefix: "We found a binary dependency in your bundle. Please add"
1199
- };
1200
- }
1201
- if (moduleName && errorConfig) {
1202
- const pkgInfo = await getPackageInfo(moduleName);
1203
- const packageName = pkgInfo?.packageJson?.name;
1204
- if (packageName) {
1205
- throwExternalDependencyError({
1206
- errorId: errorConfig.id,
1207
- moduleName,
1208
- packageName,
1209
- messagePrefix: errorConfig.messagePrefix
1210
- });
1211
- } else {
1212
- logger.debug(`Could not determine the module name for file ${file.fileName}`);
1213
- }
1214
- }
1215
- logger.debug(`Error while validating module ${file.fileName}: ${err.message}`);
1216
- }
1638
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1639
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1640
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1217
1641
  }
1642
+ await validateFile(projectRoot, file, {
1643
+ binaryMapData,
1644
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1645
+ logger,
1646
+ workspaceMap
1647
+ });
1218
1648
  }
1219
1649
  return result;
1220
1650
  }
@@ -1222,7 +1652,7 @@ async function analyzeBundle(entries, mastraEntry, {
1222
1652
  outputDir,
1223
1653
  projectRoot,
1224
1654
  isDev = false,
1225
- bundlerOptions: _bundlerOptions
1655
+ bundlerOptions
1226
1656
  }, logger) {
1227
1657
  const mastraConfig = await readFile(mastraEntry, "utf-8");
1228
1658
  const mastraConfigResult = {
@@ -1241,22 +1671,33 @@ export const mastra = new Mastra({
1241
1671
 
1242
1672
  If you think your configuration is valid, please open an issue.`);
1243
1673
  }
1244
- const { enableEsmShim = true } = _bundlerOptions || {};
1245
- const bundlerOptions = await getBundlerOptions(mastraEntry, outputDir);
1246
1674
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1675
+ let externalsPreset = false;
1676
+ const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
1677
+ if (bundlerOptions?.externals === true) {
1678
+ externalsPreset = true;
1679
+ }
1247
1680
  let index = 0;
1248
1681
  const depsToOptimize = /* @__PURE__ */ new Map();
1682
+ const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
1249
1683
  logger.info("Analyzing dependencies...");
1684
+ const allUsedExternals = /* @__PURE__ */ new Set();
1250
1685
  for (const entry of entries) {
1251
1686
  const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1252
1687
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1253
1688
  logger,
1254
- sourcemapEnabled: bundlerOptions?.sourcemap ?? false,
1689
+ sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,
1255
1690
  workspaceMap,
1256
- projectRoot
1691
+ projectRoot,
1692
+ shouldCheckTransitiveDependencies: isDev || externalsPreset
1257
1693
  });
1258
1694
  await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1259
1695
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1696
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1697
+ if (isPartOfExternals || externalsPreset && !metadata.isWorkspace) {
1698
+ allUsedExternals.add(dep);
1699
+ continue;
1700
+ }
1260
1701
  if (depsToOptimize.has(dep)) {
1261
1702
  const existingEntry = depsToOptimize.get(dep);
1262
1703
  depsToOptimize.set(dep, {
@@ -1268,28 +1709,49 @@ If you think your configuration is valid, please open an issue.`);
1268
1709
  }
1269
1710
  }
1270
1711
  }
1271
- if (isDev) {
1712
+ if (isDev || externalsPreset) {
1272
1713
  for (const [dep, metadata] of depsToOptimize.entries()) {
1273
1714
  if (!metadata.isWorkspace) {
1274
1715
  depsToOptimize.delete(dep);
1275
1716
  }
1276
1717
  }
1277
1718
  }
1278
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1719
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1279
1720
  logger.info("Optimizing dependencies...");
1280
- logger.debug(
1281
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1282
- );
1721
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1283
1722
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1284
1723
  bundlerOptions: {
1285
1724
  ...bundlerOptions,
1286
- enableEsmShim,
1725
+ externals: bundlerOptions?.externals ?? allExternals,
1287
1726
  isDev
1288
1727
  },
1289
1728
  projectRoot,
1290
1729
  workspaceRoot,
1291
1730
  workspaceMap
1292
1731
  });
1732
+ const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map(
1733
+ (pkgInfo) => relative(workspaceRoot || projectRoot, pkgInfo.location)
1734
+ );
1735
+ for (const o of output) {
1736
+ if (o.type === "asset") {
1737
+ continue;
1738
+ }
1739
+ for (const i of o.imports) {
1740
+ if (isBuiltinModule(i)) {
1741
+ continue;
1742
+ }
1743
+ if (i.startsWith(".") || i.startsWith("/")) {
1744
+ continue;
1745
+ }
1746
+ if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) {
1747
+ continue;
1748
+ }
1749
+ const pkgName = getPackageName(i);
1750
+ if (pkgName) {
1751
+ allUsedExternals.add(pkgName);
1752
+ }
1753
+ }
1754
+ }
1293
1755
  const result = await validateOutput(
1294
1756
  {
1295
1757
  output,
@@ -1301,9 +1763,12 @@ If you think your configuration is valid, please open an issue.`);
1301
1763
  },
1302
1764
  logger
1303
1765
  );
1304
- return result;
1766
+ return {
1767
+ ...result,
1768
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1769
+ };
1305
1770
  }
1306
1771
 
1307
- export { aliasHono, analyzeBundle, esbuild, extractMastraOption, getBundlerOptions, getPackageName, getPackageRootPath, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, slash, tsConfigPaths };
1308
- //# sourceMappingURL=chunk-65RQUN2A.js.map
1309
- //# sourceMappingURL=chunk-65RQUN2A.js.map
1772
+ export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getPackageRootPath, getWorkspaceInformation, removeDeployer2 as removeDeployer, subpathExternalsResolver, tsConfigPaths };
1773
+ //# sourceMappingURL=chunk-BDA7RMRF.js.map
1774
+ //# sourceMappingURL=chunk-BDA7RMRF.js.map