@mastra/deployer 0.0.0-error-handler-fix-20251020202607 → 0.0.0-esbuild-bundle-worker-20260807182016

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 (319) hide show
  1. package/CHANGELOG.md +5691 -5
  2. package/LICENSE.md +15 -0
  3. package/dist/_types/@hono_node-server/dist/index.d.mts +101 -0
  4. package/dist/_types/@mastra_hono/dist/auth-middleware.d.ts +8 -0
  5. package/dist/_types/@mastra_hono/dist/browser-stream/index.d.ts +35 -0
  6. package/dist/_types/@mastra_hono/dist/index.d.ts +59 -0
  7. package/dist/analyze-7xxwhB5F.js +1405 -0
  8. package/dist/analyze-7xxwhB5F.js.map +1 -0
  9. package/dist/analyze-D100622N.cjs +1434 -0
  10. package/dist/analyze-D100622N.cjs.map +1 -0
  11. package/dist/arktype-aI7TBD0R-BWucI7hY.cjs +8 -0
  12. package/dist/arktype-aI7TBD0R-BWucI7hY.cjs.map +1 -0
  13. package/dist/arktype-aI7TBD0R-D06--n84.js +8 -0
  14. package/dist/arktype-aI7TBD0R-D06--n84.js.map +1 -0
  15. package/dist/build/analyze/analyzeEntry.d.ts +17 -11
  16. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  17. package/dist/build/analyze/bundleExternals.d.ts +8 -7
  18. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  19. package/dist/build/analyze/constants.d.ts.map +1 -1
  20. package/dist/build/analyze.cjs +3 -12
  21. package/dist/build/analyze.d.ts +15 -7
  22. package/dist/build/analyze.d.ts.map +1 -1
  23. package/dist/build/analyze.js +2 -3
  24. package/dist/build/analyzeEntryProjectType.d.ts +12 -0
  25. package/dist/build/analyzeEntryProjectType.d.ts.map +1 -0
  26. package/dist/build/babel/check-config-export.d.ts +3 -2
  27. package/dist/build/babel/check-config-export.d.ts.map +1 -1
  28. package/dist/build/babel/detect-pino-transports.d.ts +13 -0
  29. package/dist/build/babel/detect-pino-transports.d.ts.map +1 -0
  30. package/dist/build/babel/remove-all-options-except.d.ts +3 -3
  31. package/dist/build/babel/remove-all-options-except.d.ts.map +1 -1
  32. package/dist/build/babel/remove-deployer.d.ts +6 -2
  33. package/dist/build/babel/remove-deployer.d.ts.map +1 -1
  34. package/dist/build/babel/remove-non-referenced-nodes.d.ts +2 -2
  35. package/dist/build/babel/remove-non-referenced-nodes.d.ts.map +1 -1
  36. package/dist/build/bundler.cjs +6 -16
  37. package/dist/build/bundler.d.ts +13 -3
  38. package/dist/build/bundler.d.ts.map +1 -1
  39. package/dist/build/bundler.js +2 -3
  40. package/dist/build/bundlerOptions.d.ts +1 -1
  41. package/dist/build/bundlerOptions.d.ts.map +1 -1
  42. package/dist/build/deployer.d.ts +1 -1
  43. package/dist/build/deployer.d.ts.map +1 -1
  44. package/dist/build/fs-routing/codegen.d.ts +42 -0
  45. package/dist/build/fs-routing/codegen.d.ts.map +1 -0
  46. package/dist/build/fs-routing/discover.d.ts +178 -0
  47. package/dist/build/fs-routing/discover.d.ts.map +1 -0
  48. package/dist/build/fs-routing/mirror.d.ts +16 -0
  49. package/dist/build/fs-routing/mirror.d.ts.map +1 -0
  50. package/dist/build/fs-routing/prepare.d.ts +67 -0
  51. package/dist/build/fs-routing/prepare.d.ts.map +1 -0
  52. package/dist/build/index.cjs +29 -52
  53. package/dist/build/index.d.ts +9 -1
  54. package/dist/build/index.d.ts.map +1 -1
  55. package/dist/build/index.js +7 -7
  56. package/dist/build/package-info.d.ts +14 -0
  57. package/dist/build/package-info.d.ts.map +1 -0
  58. package/dist/build/plugins/esm-shim.d.ts +14 -0
  59. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  60. package/dist/build/plugins/local-storage-detector.d.ts +50 -0
  61. package/dist/build/plugins/local-storage-detector.d.ts.map +1 -0
  62. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  63. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  64. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  65. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  66. package/dist/build/plugins/node-modules-extension-resolver.d.ts +7 -0
  67. package/dist/build/plugins/node-modules-extension-resolver.d.ts.map +1 -1
  68. package/dist/build/plugins/pino.d.ts.map +1 -1
  69. package/dist/build/plugins/protocol-external-resolver.d.ts +5 -0
  70. package/dist/build/plugins/protocol-external-resolver.d.ts.map +1 -0
  71. package/dist/build/plugins/remove-all-except.d.ts +10 -0
  72. package/dist/build/plugins/remove-all-except.d.ts.map +1 -0
  73. package/dist/build/plugins/remove-deployer.d.ts.map +1 -1
  74. package/dist/build/plugins/remove-unused-references.d.ts.map +1 -1
  75. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  76. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  77. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  78. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  79. package/dist/build/plugins/workspace-deps-watcher.d.ts +33 -0
  80. package/dist/build/plugins/workspace-deps-watcher.d.ts.map +1 -0
  81. package/dist/build/serverOptions.d.ts +1 -1
  82. package/dist/build/serverOptions.d.ts.map +1 -1
  83. package/dist/build/shared/extract-mastra-option.d.ts +5 -9
  84. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  85. package/dist/build/types.d.ts +35 -0
  86. package/dist/build/types.d.ts.map +1 -1
  87. package/dist/build/utils.d.ts +106 -2
  88. package/dist/build/utils.d.ts.map +1 -1
  89. package/dist/build/watcher.d.ts +5 -1
  90. package/dist/build/watcher.d.ts.map +1 -1
  91. package/dist/build-DEie1huB.js +1084 -0
  92. package/dist/build-DEie1huB.js.map +1 -0
  93. package/dist/build-YV8-9zZy.cjs +1158 -0
  94. package/dist/build-YV8-9zZy.cjs.map +1 -0
  95. package/dist/bundler/entries.d.ts +12 -0
  96. package/dist/bundler/entries.d.ts.map +1 -0
  97. package/dist/bundler/index.cjs +7 -12
  98. package/dist/bundler/index.d.ts +85 -12
  99. package/dist/bundler/index.d.ts.map +1 -1
  100. package/dist/bundler/index.js +2 -3
  101. package/dist/bundler/workspaceDependencies.d.ts +3 -5
  102. package/dist/bundler/workspaceDependencies.d.ts.map +1 -1
  103. package/dist/bundler-CD-PSWRS.cjs +591 -0
  104. package/dist/bundler-CD-PSWRS.cjs.map +1 -0
  105. package/dist/bundler-NdSt2FYG.js +558 -0
  106. package/dist/bundler-NdSt2FYG.js.map +1 -0
  107. package/dist/bundler-U9F2---r.js +704 -0
  108. package/dist/bundler-U9F2---r.js.map +1 -0
  109. package/dist/bundler-u9WOUtpl.cjs +791 -0
  110. package/dist/bundler-u9WOUtpl.cjs.map +1 -0
  111. package/dist/bundlerOptions-9DigsVhY.js +180 -0
  112. package/dist/bundlerOptions-9DigsVhY.js.map +1 -0
  113. package/dist/bundlerOptions-CYRir4LE.cjs +194 -0
  114. package/dist/bundlerOptions-CYRir4LE.cjs.map +1 -0
  115. package/dist/core-D0wEgdn3.cjs +790 -0
  116. package/dist/core-D0wEgdn3.cjs.map +1 -0
  117. package/dist/core-DF65PJXc.js +790 -0
  118. package/dist/core-DF65PJXc.js.map +1 -0
  119. package/dist/deploy/log.d.ts +2 -2
  120. package/dist/deploy/log.d.ts.map +1 -1
  121. package/dist/dist-BauTimif.js +532 -0
  122. package/dist/dist-BauTimif.js.map +1 -0
  123. package/dist/dist-Cv-mAEtr.cjs +532 -0
  124. package/dist/dist-Cv-mAEtr.cjs.map +1 -0
  125. package/dist/docs/SKILL.md +31 -0
  126. package/dist/docs/assets/SOURCE_MAP.json +6 -0
  127. package/dist/docs/references/docs-deployment-cloud-providers.md +23 -0
  128. package/dist/docs/references/docs-deployment-mastra-server.md +157 -0
  129. package/dist/docs/references/docs-deployment-monorepo.md +140 -0
  130. package/dist/docs/references/docs-deployment-overview.md +79 -0
  131. package/dist/docs/references/docs-deployment-web-framework.md +54 -0
  132. package/dist/docs/references/docs-deployment-workflow-runners.md +17 -0
  133. package/dist/docs/references/reference-deployer.md +102 -0
  134. package/dist/effect-QlVUlMFu-CWx-dnsz.cjs +14 -0
  135. package/dist/effect-QlVUlMFu-CWx-dnsz.cjs.map +1 -0
  136. package/dist/effect-QlVUlMFu-CovUzKO9.js +14 -0
  137. package/dist/effect-QlVUlMFu-CovUzKO9.js.map +1 -0
  138. package/dist/esm-B51vJPGv.js +4634 -0
  139. package/dist/esm-B51vJPGv.js.map +1 -0
  140. package/dist/esm-DZ1Siz1C.cjs +4634 -0
  141. package/dist/esm-DZ1Siz1C.cjs.map +1 -0
  142. package/dist/index-CLddUTqr-Btqs8t-3.js +140 -0
  143. package/dist/index-CLddUTqr-Btqs8t-3.js.map +1 -0
  144. package/dist/index-CLddUTqr-C8lMvBz9.cjs +145 -0
  145. package/dist/index-CLddUTqr-C8lMvBz9.cjs.map +1 -0
  146. package/dist/index.cjs +35 -59
  147. package/dist/index.cjs.map +1 -1
  148. package/dist/index.js +29 -41
  149. package/dist/index.js.map +1 -1
  150. package/dist/rolldown-runtime-emK7D4bc.cjs +35 -0
  151. package/dist/server/handlers/a2a.d.ts +28 -3
  152. package/dist/server/handlers/a2a.d.ts.map +1 -1
  153. package/dist/server/handlers/agent-learning.d.ts +3 -0
  154. package/dist/server/handlers/agent-learning.d.ts.map +1 -0
  155. package/dist/server/handlers/health.d.ts +5 -0
  156. package/dist/server/handlers/health.d.ts.map +1 -0
  157. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  158. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  159. package/dist/server/handlers/utils/query-parsers.d.ts +15 -0
  160. package/dist/server/handlers/utils/query-parsers.d.ts.map +1 -1
  161. package/dist/server/handlers/utils.d.ts +0 -7
  162. package/dist/server/handlers/utils.d.ts.map +1 -1
  163. package/dist/server/index.cjs +4375 -11856
  164. package/dist/server/index.cjs.map +1 -1
  165. package/dist/server/index.d.ts +4 -13
  166. package/dist/server/index.d.ts.map +1 -1
  167. package/dist/server/index.js +4370 -11830
  168. package/dist/server/index.js.map +1 -1
  169. package/dist/server/types.d.ts +2 -1
  170. package/dist/server/types.d.ts.map +1 -1
  171. package/dist/server/welcome.d.ts +1 -1
  172. package/dist/server/welcome.d.ts.map +1 -1
  173. package/dist/services/deps.d.ts +9 -1
  174. package/dist/services/deps.d.ts.map +1 -1
  175. package/dist/services/env.d.ts.map +1 -1
  176. package/dist/services/index.cjs +5 -20
  177. package/dist/services/index.js +2 -3
  178. package/dist/services-BRF1RRXB.js +430 -0
  179. package/dist/services-BRF1RRXB.js.map +1 -0
  180. package/dist/services-_ksvysL5.cjs +469 -0
  181. package/dist/services-_ksvysL5.cjs.map +1 -0
  182. package/dist/sury-CWZTCd75-Bbjr0vWq.cjs +14 -0
  183. package/dist/sury-CWZTCd75-Bbjr0vWq.cjs.map +1 -0
  184. package/dist/sury-CWZTCd75-C3LyvnOp.js +14 -0
  185. package/dist/sury-CWZTCd75-C3LyvnOp.js.map +1 -0
  186. package/dist/typebox-Dei93FPO-EcvSqxpn.js +8 -0
  187. package/dist/typebox-Dei93FPO-EcvSqxpn.js.map +1 -0
  188. package/dist/typebox-Dei93FPO-n37w7tHC.cjs +8 -0
  189. package/dist/typebox-Dei93FPO-n37w7tHC.cjs.map +1 -0
  190. package/dist/utils-FVOUvj-I.js +190 -0
  191. package/dist/utils-FVOUvj-I.js.map +1 -0
  192. package/dist/utils-O98BGdnP.cjs +267 -0
  193. package/dist/utils-O98BGdnP.cjs.map +1 -0
  194. package/dist/valibot--1zFm7rT-BN2-Xy7Y.cjs +14 -0
  195. package/dist/valibot--1zFm7rT-BN2-Xy7Y.cjs.map +1 -0
  196. package/dist/valibot--1zFm7rT-DLXBDt2x.js +14 -0
  197. package/dist/valibot--1zFm7rT-DLXBDt2x.js.map +1 -0
  198. package/dist/validator/custom-resolver.cjs +77 -45
  199. package/dist/validator/custom-resolver.cjs.map +1 -1
  200. package/dist/validator/custom-resolver.d.ts +15 -1
  201. package/dist/validator/custom-resolver.d.ts.map +1 -1
  202. package/dist/validator/custom-resolver.js +74 -42
  203. package/dist/validator/custom-resolver.js.map +1 -1
  204. package/dist/validator/loader.cjs +6 -7
  205. package/dist/validator/loader.cjs.map +1 -1
  206. package/dist/validator/loader.js +8 -4
  207. package/dist/validator/loader.js.map +1 -1
  208. package/dist/validator/validate.d.ts +16 -1
  209. package/dist/validator/validate.d.ts.map +1 -1
  210. package/dist/zod-Bwrt9trS-Cbwhu5Zl.cjs +23 -0
  211. package/dist/zod-Bwrt9trS-Cbwhu5Zl.cjs.map +1 -0
  212. package/dist/zod-Bwrt9trS-Si3ZkB_H.js +23 -0
  213. package/dist/zod-Bwrt9trS-Si3ZkB_H.js.map +1 -0
  214. package/package.json +50 -45
  215. package/dist/build/analyze.cjs.map +0 -1
  216. package/dist/build/analyze.js.map +0 -1
  217. package/dist/build/babel/get-deployer.d.ts +0 -3
  218. package/dist/build/babel/get-deployer.d.ts.map +0 -1
  219. package/dist/build/babel/remove-all-options-bundler.d.ts +0 -5
  220. package/dist/build/babel/remove-all-options-bundler.d.ts.map +0 -1
  221. package/dist/build/babel/remove-all-options-deployer.d.ts +0 -5
  222. package/dist/build/babel/remove-all-options-deployer.d.ts.map +0 -1
  223. package/dist/build/babel/remove-all-options-server.d.ts +0 -5
  224. package/dist/build/babel/remove-all-options-server.d.ts.map +0 -1
  225. package/dist/build/babel/remove-all-options-telemetry.d.ts +0 -5
  226. package/dist/build/babel/remove-all-options-telemetry.d.ts.map +0 -1
  227. package/dist/build/bundler.cjs.map +0 -1
  228. package/dist/build/bundler.js.map +0 -1
  229. package/dist/build/customInstrumentation.d.ts +0 -10
  230. package/dist/build/customInstrumentation.d.ts.map +0 -1
  231. package/dist/build/index.cjs.map +0 -1
  232. package/dist/build/index.js.map +0 -1
  233. package/dist/build/telemetry.d.ts +0 -8
  234. package/dist/build/telemetry.d.ts.map +0 -1
  235. package/dist/bundler/index.cjs.map +0 -1
  236. package/dist/bundler/index.js.map +0 -1
  237. package/dist/chunk-3JYRSECU.cjs +0 -430
  238. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  239. package/dist/chunk-465ZVXAK.js +0 -409
  240. package/dist/chunk-465ZVXAK.js.map +0 -1
  241. package/dist/chunk-5QFG6SCM.js +0 -398
  242. package/dist/chunk-5QFG6SCM.js.map +0 -1
  243. package/dist/chunk-CEXVMFUD.js +0 -1265
  244. package/dist/chunk-CEXVMFUD.js.map +0 -1
  245. package/dist/chunk-CKUCDCGI.js +0 -168
  246. package/dist/chunk-CKUCDCGI.js.map +0 -1
  247. package/dist/chunk-HMMDNIEQ.cjs +0 -167
  248. package/dist/chunk-HMMDNIEQ.cjs.map +0 -1
  249. package/dist/chunk-LGC3GUMR.cjs +0 -437
  250. package/dist/chunk-LGC3GUMR.cjs.map +0 -1
  251. package/dist/chunk-MCDDO4WY.cjs +0 -1309
  252. package/dist/chunk-MCDDO4WY.cjs.map +0 -1
  253. package/dist/chunk-OYO2MJED.cjs +0 -195
  254. package/dist/chunk-OYO2MJED.cjs.map +0 -1
  255. package/dist/chunk-SBTEIZ3B.js +0 -26
  256. package/dist/chunk-SBTEIZ3B.js.map +0 -1
  257. package/dist/chunk-WAWEQ3DP.js +0 -156
  258. package/dist/chunk-WAWEQ3DP.js.map +0 -1
  259. package/dist/chunk-WIQEFIRX.cjs +0 -28
  260. package/dist/chunk-WIQEFIRX.cjs.map +0 -1
  261. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  262. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  263. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  264. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  265. package/dist/server/handlers/auth/index.d.ts +0 -11
  266. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  267. package/dist/server/handlers/prompt.d.ts +0 -3
  268. package/dist/server/handlers/prompt.d.ts.map +0 -1
  269. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -17
  270. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  271. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  272. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  273. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -363
  274. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  275. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  276. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  277. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  278. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  279. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  280. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  281. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  282. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  283. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  284. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  285. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  286. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  287. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -17
  288. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  289. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  290. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  291. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  292. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  293. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  294. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  295. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -300
  296. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  297. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  298. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  299. package/dist/server/handlers/routes/telemetry/handlers.d.ts +0 -4
  300. package/dist/server/handlers/routes/telemetry/handlers.d.ts.map +0 -1
  301. package/dist/server/handlers/routes/telemetry/router.d.ts +0 -3
  302. package/dist/server/handlers/routes/telemetry/router.d.ts.map +0 -1
  303. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  304. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  305. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  306. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  307. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  308. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  309. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  310. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  311. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  312. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  313. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts +0 -11
  314. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts.map +0 -1
  315. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  316. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
  317. package/dist/services/index.cjs.map +0 -1
  318. package/dist/services/index.js.map +0 -1
  319. package/dist/templates/instrumentation-template.js +0 -172
@@ -0,0 +1,1405 @@
1
+ import { a as getPackageName, c as isBuiltinModule, f as rollupSafeName, i as getNodeResolveOptions, l as isDependencyPartOfPackage, p as slash, r as getCompiledDepCachePath, s as isBareModuleSpecifier, u as isExternalProtocolImport } from "./utils-FVOUvj-I.js";
2
+ import { i as DepsService } from "./services-BRF1RRXB.js";
3
+ import { a as tsConfigPaths, c as protocolExternalResolver, d as getPackageRootPath, f as esmShim, i as mastraToolsAliasPlugin, o as subpathExternalsResolver, p as esbuild, r as mastraInternalAliasPlugin, s as removeDeployer, u as getPackageMetadata } from "./bundler-U9F2---r.js";
4
+ import { spawn } from "child_process";
5
+ import { existsSync } from "fs";
6
+ import { readFile, writeFile } from "fs/promises";
7
+ import * as path$1 from "path";
8
+ import { basename, dirname, isAbsolute, join, relative } from "path";
9
+ import { ErrorCategory, ErrorDomain, MastraBaseError, MastraError } from "@mastra/core/error";
10
+ import virtual from "@rollup/plugin-virtual";
11
+ import * as pkg from "empathic/package";
12
+ import { transformAsync, transformSync, types } from "@babel/core";
13
+ import slugify from "@sindresorhus/slugify";
14
+ import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from "find-workspaces";
15
+ import { ensureDir } from "fs-extra";
16
+ import { fileURLToPath, pathToFileURL } from "url";
17
+ import commonjs from "@rollup/plugin-commonjs";
18
+ import json from "@rollup/plugin-json";
19
+ import { rollup } from "rollup";
20
+ import { optimizeLodashImports } from "@optimize-lodash/rollup-plugin";
21
+ import nodeResolve from "@rollup/plugin-node-resolve";
22
+ import { getPackageInfo } from "local-pkg";
23
+ import { basename as basename$1 } from "path/posix";
24
+ import * as resolve$1 from "resolve.exports";
25
+ //#region \0rolldown/runtime.js
26
+ var __create = Object.create;
27
+ var __defProp = Object.defineProperty;
28
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
29
+ var __getOwnPropNames = Object.getOwnPropertyNames;
30
+ var __getProtoOf = Object.getPrototypeOf;
31
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
32
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
33
+ var __copyProps = (to, from, except, desc) => {
34
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
35
+ key = keys[i];
36
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
37
+ get: ((k) => from[k]).bind(null, key),
38
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
39
+ });
40
+ }
41
+ return to;
42
+ };
43
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
44
+ value: mod,
45
+ enumerable: true
46
+ }) : target, mod));
47
+ //#endregion
48
+ //#region src/bundler/workspaceDependencies.ts
49
+ var import_stack_trace_parser_cjs = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ var UNKNOWN_FUNCTION = "<unknown>";
52
+ /**
53
+ * This parses the different stack traces and puts them into one format
54
+ * This borrows heavily from TraceKit (https://github.com/csnover/TraceKit)
55
+ */
56
+ function parse(stackString) {
57
+ return stackString.split("\n").reduce(function(stack, line) {
58
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
59
+ if (parseResult) stack.push(parseResult);
60
+ return stack;
61
+ }, []);
62
+ }
63
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
64
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
65
+ function parseChrome(line) {
66
+ var parts = chromeRe.exec(line);
67
+ if (!parts) return null;
68
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
69
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
70
+ var submatch = chromeEvalRe.exec(parts[2]);
71
+ if (isEval && submatch != null) {
72
+ parts[2] = submatch[1];
73
+ parts[3] = submatch[2];
74
+ parts[4] = submatch[3];
75
+ }
76
+ return {
77
+ file: !isNative ? parts[2] : null,
78
+ methodName: parts[1] || UNKNOWN_FUNCTION,
79
+ arguments: isNative ? [parts[2]] : [],
80
+ lineNumber: parts[3] ? +parts[3] : null,
81
+ column: parts[4] ? +parts[4] : null
82
+ };
83
+ }
84
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
85
+ function parseWinjs(line) {
86
+ var parts = winjsRe.exec(line);
87
+ if (!parts) return null;
88
+ return {
89
+ file: parts[2],
90
+ methodName: parts[1] || UNKNOWN_FUNCTION,
91
+ arguments: [],
92
+ lineNumber: +parts[3],
93
+ column: parts[4] ? +parts[4] : null
94
+ };
95
+ }
96
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
97
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
98
+ function parseGecko(line) {
99
+ var parts = geckoRe.exec(line);
100
+ if (!parts) return null;
101
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
102
+ var submatch = geckoEvalRe.exec(parts[3]);
103
+ if (isEval && submatch != null) {
104
+ parts[3] = submatch[1];
105
+ parts[4] = submatch[2];
106
+ parts[5] = null;
107
+ }
108
+ return {
109
+ file: parts[3],
110
+ methodName: parts[1] || UNKNOWN_FUNCTION,
111
+ arguments: parts[2] ? parts[2].split(",") : [],
112
+ lineNumber: parts[4] ? +parts[4] : null,
113
+ column: parts[5] ? +parts[5] : null
114
+ };
115
+ }
116
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
117
+ function parseJSC(line) {
118
+ var parts = javaScriptCoreRe.exec(line);
119
+ if (!parts) return null;
120
+ return {
121
+ file: parts[3],
122
+ methodName: parts[1] || UNKNOWN_FUNCTION,
123
+ arguments: [],
124
+ lineNumber: +parts[4],
125
+ column: parts[5] ? +parts[5] : null
126
+ };
127
+ }
128
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
129
+ function parseNode(line) {
130
+ var parts = nodeRe.exec(line);
131
+ if (!parts) return null;
132
+ return {
133
+ file: parts[2],
134
+ methodName: parts[1] || UNKNOWN_FUNCTION,
135
+ arguments: [],
136
+ lineNumber: +parts[3],
137
+ column: parts[4] ? +parts[4] : null
138
+ };
139
+ }
140
+ exports.parse = parse;
141
+ })))(), 1);
142
+ const isExportTargetImportable = (target) => {
143
+ if (!target) return false;
144
+ if (typeof target === "string") return true;
145
+ if (Array.isArray(target)) return target.some(isExportTargetImportable);
146
+ if (typeof target !== "object") return false;
147
+ return Object.values(target).some(isExportTargetImportable);
148
+ };
149
+ const hasRootExport = (exportsField) => {
150
+ if (exportsField === void 0) return true;
151
+ if (typeof exportsField === "string" || Array.isArray(exportsField)) return isExportTargetImportable(exportsField);
152
+ if (!exportsField || typeof exportsField !== "object") return false;
153
+ const exportMap = exportsField;
154
+ const exportKeys = Object.keys(exportMap);
155
+ if (exportKeys.length === 0) return false;
156
+ if (Object.prototype.hasOwnProperty.call(exportMap, ".")) return isExportTargetImportable(exportMap["."]);
157
+ if (exportKeys.some((key) => key.startsWith("./"))) return false;
158
+ return isExportTargetImportable(exportMap);
159
+ };
160
+ /**
161
+ * Create a shared cache for find-workspaces
162
+ */
163
+ const workspacesCache = createWorkspacesCache();
164
+ /**
165
+ * A utility function around find-workspaces to get information about:
166
+ * - Which workspace packages are available in the project
167
+ * - What is the workspace root location
168
+ * - Is the current package a workspace package
169
+ *
170
+ * Because `findWorkspacesRoot` only traverses up until it finds workspace information, but doesn't check if the current package is even part of the workspace. We rather want to return `null` for these cases because in other code paths we use `workspaceRoot || projectRoot` to determine the root of the project.
171
+ *
172
+ * @params dir - The directory to start searching from (default: `process.cwd()`)
173
+ * @params location - The location of the current package (usually the directory containing the package.json)
174
+ */
175
+ async function getWorkspaceInformation({ dir = process.cwd(), mastraEntryFile }) {
176
+ const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });
177
+ const location = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());
178
+ const workspaces = await findWorkspaces(dir, { cache: workspacesCache });
179
+ const _workspaceMap = new Map(workspaces?.map((workspace) => [workspace.package.name, {
180
+ location: workspace.location,
181
+ dependencies: workspace.package.dependencies,
182
+ version: workspace.package.version,
183
+ exports: workspace.package.exports
184
+ }]) ?? []);
185
+ const isWorkspacePackage = (workspaces ?? []).some((ws) => ws.location === location);
186
+ const workspaceRoot = isWorkspacePackage ? findWorkspacesRoot(dir, { cache: workspacesCache })?.location : void 0;
187
+ return {
188
+ workspaceMap: isWorkspacePackage ? _workspaceMap : /* @__PURE__ */ new Map(),
189
+ workspaceRoot,
190
+ isWorkspacePackage
191
+ };
192
+ }
193
+ /**
194
+ * Collects all transitive workspace dependencies and their TGZ paths
195
+ */
196
+ const collectTransitiveWorkspaceDependencies = ({ workspaceMap, initialDependencies, logger }) => {
197
+ const usedWorkspacePackages = /* @__PURE__ */ new Set();
198
+ const queue = Array.from(initialDependencies);
199
+ const resolutions = {};
200
+ while (queue.length > 0) {
201
+ const len = queue.length;
202
+ for (let i = 0; i < len; i += 1) {
203
+ const pkgName = queue.shift();
204
+ if (!pkgName || usedWorkspacePackages.has(pkgName)) continue;
205
+ const dep = workspaceMap.get(pkgName);
206
+ if (!dep) continue;
207
+ const root = findWorkspacesRoot();
208
+ if (!root) throw new Error("Could not find workspace root");
209
+ const depsService = new DepsService(root.location);
210
+ depsService.__setLogger(logger);
211
+ const sanitizedName = slugify(pkgName);
212
+ resolutions[pkgName] = depsService.getWorkspaceDependencyPath({
213
+ pkgName: sanitizedName,
214
+ version: dep.version
215
+ });
216
+ usedWorkspacePackages.add(pkgName);
217
+ for (const [depName, _depVersion] of Object.entries(dep?.dependencies ?? {})) if (!usedWorkspacePackages.has(depName) && workspaceMap.has(depName)) queue.push(depName);
218
+ }
219
+ }
220
+ return {
221
+ resolutions,
222
+ usedWorkspacePackages
223
+ };
224
+ };
225
+ /**
226
+ * Creates TGZ packages for workspace dependencies in the workspace-module directory
227
+ */
228
+ const packWorkspaceDependencies = async ({ workspaceMap, usedWorkspacePackages, bundleOutputDir, logger }) => {
229
+ const root = findWorkspacesRoot();
230
+ if (!root) throw new Error("Could not find workspace root");
231
+ const depsService = new DepsService(root.location);
232
+ depsService.__setLogger(logger);
233
+ if (usedWorkspacePackages.size > 0) {
234
+ const workspaceDirPath = join(bundleOutputDir, "workspace-module");
235
+ await ensureDir(workspaceDirPath);
236
+ logger.info("Packaging workspace dependencies", { count: usedWorkspacePackages.size });
237
+ const batchSize = 5;
238
+ const packages = Array.from(usedWorkspacePackages.values());
239
+ for (let i = 0; i < packages.length; i += batchSize) {
240
+ const batch = packages.slice(i, i + batchSize);
241
+ logger.info(`Packaging batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(packages.length / batchSize)}: ${batch.join(", ")}`);
242
+ await Promise.all(batch.map(async (pkgName) => {
243
+ const dep = workspaceMap.get(pkgName);
244
+ const sanitizedName = slugify(pkgName);
245
+ if (!dep) return;
246
+ await depsService.pack({
247
+ dir: dep.location,
248
+ destination: workspaceDirPath,
249
+ sanitizedName
250
+ });
251
+ }));
252
+ }
253
+ logger.info("Successfully packaged workspace dependencies", { count: usedWorkspacePackages.size });
254
+ }
255
+ };
256
+ //#endregion
257
+ //#region src/validator/validate.ts
258
+ var ValidationError = class extends Error {
259
+ type;
260
+ stack;
261
+ constructor(args) {
262
+ super(args.message);
263
+ this.type = args.type;
264
+ this.stack = args.stack;
265
+ }
266
+ };
267
+ /**
268
+ * Promisified version of Node.js spawn function
269
+ *
270
+ * @param command - The command to run
271
+ * @param args - List of string arguments
272
+ * @param options - Spawn options
273
+ * @returns Promise that resolves with the exit code when the process completes
274
+ */
275
+ function spawn$1(command, args = [], options = {}) {
276
+ return new Promise((resolve, reject) => {
277
+ let validationError = null;
278
+ const childProcess = spawn(command, args, {
279
+ stdio: [
280
+ "ignore",
281
+ "ignore",
282
+ "pipe"
283
+ ],
284
+ ...options
285
+ });
286
+ childProcess.on("error", (error) => {
287
+ reject(error);
288
+ });
289
+ let stderr = "";
290
+ childProcess.stderr?.on("data", (message) => {
291
+ try {
292
+ validationError = JSON.parse(message.toString());
293
+ } catch {
294
+ stderr += message;
295
+ }
296
+ });
297
+ childProcess.on("close", (code) => {
298
+ if (code === 0) resolve();
299
+ else if (validationError) reject(new ValidationError(validationError));
300
+ else reject(new Error(stderr));
301
+ });
302
+ });
303
+ }
304
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation, stubbedExternals = [] }) {
305
+ let prefixCode = "";
306
+ if (injectESMShim) prefixCode = `import { fileURLToPath } from 'url';
307
+ import { dirname } from 'path';
308
+
309
+ globalThis.__filename = fileURLToPath(import.meta.url);
310
+ globalThis.__dirname = dirname(__filename);
311
+ `;
312
+ function errorHandler(err) {
313
+ console.error(JSON.stringify({
314
+ type: err.name,
315
+ message: err.message,
316
+ stack: err.stack
317
+ }));
318
+ process.exit(1);
319
+ }
320
+ return spawn$1(process.execPath, [
321
+ "--import",
322
+ import.meta.resolve("@mastra/deployer/loader"),
323
+ "--input-type=module",
324
+ "--enable-source-maps",
325
+ "-e",
326
+ `${prefixCode};import('${pathToFileURL(file).href}').catch(err => {
327
+ ${errorHandler.toString()}
328
+ errorHandler(err);
329
+ })`.replaceAll(/\n/g, "")
330
+ ], {
331
+ env: {
332
+ ...process.env,
333
+ MODULE_MAP: `${moduleResolveMapLocation}`,
334
+ STUBBED_EXTERNALS: JSON.stringify(stubbedExternals)
335
+ },
336
+ cwd: dirname(file)
337
+ });
338
+ }
339
+ //#endregion
340
+ //#region src/build/analyze/constants.ts
341
+ const DEPS_TO_IGNORE = [
342
+ "#tools",
343
+ "execa",
344
+ "effect",
345
+ "sury",
346
+ "@ast-grep/napi",
347
+ "@hono/node-ws"
348
+ ];
349
+ const GLOBAL_EXTERNALS = [
350
+ "pino",
351
+ "pino-pretty",
352
+ "@libsql/client",
353
+ "pg",
354
+ "libsql",
355
+ "#tools",
356
+ "typescript",
357
+ "undici",
358
+ "readable-stream",
359
+ "bufferutil",
360
+ "utf-8-validate",
361
+ "execa",
362
+ "@ast-grep/napi",
363
+ "@hono/node-ws"
364
+ ];
365
+ const DEPRECATED_EXTERNALS = [
366
+ "fastembed",
367
+ "nodemailer",
368
+ "jsdom",
369
+ "sqlite3"
370
+ ];
371
+ //#endregion
372
+ //#region src/build/analyze/analyzeEntry.ts
373
+ /**
374
+ * Configures and returns the Rollup plugins needed for analyzing entry files.
375
+ * Sets up module resolution, transpilation, and custom alias handling for Mastra-specific imports.
376
+ */
377
+ function getInputPlugins$1({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
378
+ let virtualPlugin = null;
379
+ if (isVirtualFile) {
380
+ virtualPlugin = virtual({ "#entry": entry });
381
+ entry = "#entry";
382
+ }
383
+ const plugins = [];
384
+ if (virtualPlugin) plugins.push(virtualPlugin);
385
+ plugins.push(...[
386
+ protocolExternalResolver(),
387
+ mastraInternalAliasPlugin(mastraEntry),
388
+ mastraToolsAliasPlugin(),
389
+ tsConfigPaths(),
390
+ json(),
391
+ esbuild(),
392
+ commonjs({
393
+ strictRequires: "debug",
394
+ ignoreTryCatch: false,
395
+ transformMixedEsModules: true,
396
+ extensions: [".js", ".ts"]
397
+ }),
398
+ removeDeployer(mastraEntry, { sourcemap: sourcemapEnabled }),
399
+ esbuild()
400
+ ]);
401
+ return plugins;
402
+ }
403
+ /**
404
+ * Extracts and categorizes dependencies from Rollup output to determine which ones need optimization.
405
+ * Analyzes both static imports and dynamic imports while filtering out Node.js built-ins and ignored dependencies.
406
+ * Identifies workspace packages and resolves package root paths for proper bundling optimization.
407
+ */
408
+ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, { logger, shouldCheckTransitiveDependencies }) {
409
+ const depsToOptimize = /* @__PURE__ */ new Map();
410
+ if (!output.facadeModuleId) throw new Error("Something went wrong, we could not find the package name of the entry file. Please open an issue.");
411
+ let entryRootPath = projectRoot;
412
+ if (!output.facadeModuleId.startsWith("\0virtual:")) entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
413
+ for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
414
+ if (!isBareModuleSpecifier(dependency)) continue;
415
+ const pkgName = getPackageName(dependency);
416
+ let rootPath = null;
417
+ let isWorkspace = false;
418
+ let version;
419
+ let packageSpec;
420
+ if (pkgName) {
421
+ const metadata = await getPackageMetadata(dependency, entryRootPath);
422
+ rootPath = metadata.rootPath;
423
+ version = metadata.version;
424
+ packageSpec = metadata.packageSpec;
425
+ isWorkspace = workspaceMap.has(pkgName);
426
+ }
427
+ const normalizedRootPath = rootPath ? slash(rootPath) : null;
428
+ depsToOptimize.set(dependency, {
429
+ exports: bindings,
430
+ rootPath: normalizedRootPath,
431
+ isWorkspace,
432
+ version,
433
+ packageSpec
434
+ });
435
+ }
436
+ const processedWorkspaceDeps = /* @__PURE__ */ new Set();
437
+ /**
438
+ * Recursively discovers transitive workspace dependencies from package manifests.
439
+ */
440
+ function checkTransitiveDependencies(maxDepth = 10, currentDepth = 0) {
441
+ if (currentDepth >= maxDepth) {
442
+ logger.warn("Maximum dependency depth reached while checking transitive dependencies.");
443
+ return;
444
+ }
445
+ const depsSnapshot = new Map(depsToOptimize);
446
+ let hasAddedDeps = false;
447
+ for (const [dep, meta] of depsSnapshot) {
448
+ const pkgName = getPackageName(dep);
449
+ if (!pkgName || !meta.isWorkspace || processedWorkspaceDeps.has(pkgName)) continue;
450
+ processedWorkspaceDeps.add(pkgName);
451
+ const workspaceInfo = workspaceMap.get(pkgName);
452
+ if (!workspaceInfo?.dependencies) continue;
453
+ for (const [innerDep, _innerDepVersion] of Object.entries(workspaceInfo.dependencies)) {
454
+ const innerWorkspaceInfo = workspaceMap.get(innerDep);
455
+ if (!innerWorkspaceInfo) continue;
456
+ if (!hasRootExport(innerWorkspaceInfo.exports)) continue;
457
+ const existingMeta = depsToOptimize.get(innerDep);
458
+ if (existingMeta) {
459
+ depsToOptimize.set(innerDep, {
460
+ ...existingMeta,
461
+ exports: existingMeta.exports.includes("*") ? existingMeta.exports : [...existingMeta.exports, "*"]
462
+ });
463
+ continue;
464
+ }
465
+ depsToOptimize.set(innerDep, {
466
+ exports: ["*"],
467
+ rootPath: slash(innerWorkspaceInfo.location),
468
+ isWorkspace: true,
469
+ version: innerWorkspaceInfo.version
470
+ });
471
+ hasAddedDeps = true;
472
+ }
473
+ }
474
+ if (hasAddedDeps) checkTransitiveDependencies(maxDepth, currentDepth + 1);
475
+ }
476
+ if (shouldCheckTransitiveDependencies) checkTransitiveDependencies();
477
+ const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
478
+ if (dynamicImports.length) {
479
+ for (const dynamicImport of dynamicImports) if (!depsToOptimize.has(dynamicImport) && isBareModuleSpecifier(dynamicImport)) {
480
+ const pkgName = getPackageName(dynamicImport);
481
+ let version;
482
+ let packageSpec;
483
+ let rootPath = null;
484
+ if (pkgName) {
485
+ const metadata = await getPackageMetadata(dynamicImport, entryRootPath);
486
+ rootPath = metadata.rootPath;
487
+ version = metadata.version;
488
+ packageSpec = metadata.packageSpec;
489
+ }
490
+ depsToOptimize.set(dynamicImport, {
491
+ exports: ["*"],
492
+ rootPath: rootPath ? slash(rootPath) : null,
493
+ isWorkspace: false,
494
+ version,
495
+ packageSpec
496
+ });
497
+ }
498
+ }
499
+ return depsToOptimize;
500
+ }
501
+ async function analyzeEntry({ entry, isVirtualFile }, mastraEntry, { logger, sourcemapEnabled, workspaceMap, projectRoot, shouldCheckTransitiveDependencies = false, analyzeCache }) {
502
+ const cacheKey = isVirtualFile ? void 0 : slash(entry);
503
+ if (cacheKey && analyzeCache?.has(cacheKey)) return analyzeCache.get(cacheKey);
504
+ const optimizerBundler = await rollup({
505
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
506
+ input: isVirtualFile ? "#entry" : entry,
507
+ treeshake: false,
508
+ preserveSymlinks: true,
509
+ plugins: getInputPlugins$1({
510
+ entry,
511
+ isVirtualFile
512
+ }, mastraEntry, { sourcemapEnabled }),
513
+ external: DEPS_TO_IGNORE
514
+ });
515
+ const { output } = await optimizerBundler.generate({
516
+ format: "esm",
517
+ inlineDynamicImports: true
518
+ });
519
+ await optimizerBundler.close();
520
+ const result = {
521
+ dependencies: await captureDependenciesToOptimize(output[0], workspaceMap, projectRoot, {
522
+ logger,
523
+ shouldCheckTransitiveDependencies
524
+ }),
525
+ output: {
526
+ code: output[0].code,
527
+ map: output[0].map
528
+ }
529
+ };
530
+ if (cacheKey && analyzeCache) analyzeCache.set(cacheKey, result);
531
+ return result;
532
+ }
533
+ //#endregion
534
+ //#region src/build/plugins/hono-alias.ts
535
+ function aliasHono() {
536
+ return {
537
+ name: "hono-alias",
538
+ resolveId(id) {
539
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") return;
540
+ return fileURLToPath(import.meta.resolve(id));
541
+ }
542
+ };
543
+ }
544
+ //#endregion
545
+ //#region src/build/plugins/module-resolve-map.ts
546
+ function moduleResolveMap(externals, projectRoot) {
547
+ const importMap = /* @__PURE__ */ new Map();
548
+ return {
549
+ name: "module-resolve-map",
550
+ moduleParsed(info) {
551
+ if (info.importedIds.length === 0 || !info.id) return;
552
+ for (const importedId of info.importedIds) for (const external of externals) if (isDependencyPartOfPackage(importedId, external)) importMap.set(external, info.id);
553
+ },
554
+ async generateBundle(options, bundle) {
555
+ const resolveMap = /* @__PURE__ */ new Map();
556
+ for (const [fileName, chunk] of Object.entries(bundle)) if (chunk.type === "chunk") {
557
+ for (const [external, resolvedFrom] of importMap) if (chunk.moduleIds.includes(resolvedFrom)) {
558
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
559
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
560
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
561
+ resolveMap.set(fullPath, innerMap);
562
+ }
563
+ }
564
+ const resolveMapJson = Object.fromEntries(Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())]));
565
+ this.emitFile({
566
+ type: "asset",
567
+ name: "module-resolve-map.json",
568
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
569
+ });
570
+ }
571
+ };
572
+ }
573
+ //#endregion
574
+ //#region src/build/plugins/node-gyp-detector.ts
575
+ function nodeGypDetector() {
576
+ const modulesToTrack = /* @__PURE__ */ new Set();
577
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
578
+ return {
579
+ name: "node-gyp-build-detector",
580
+ moduleParsed(info) {
581
+ if (!info.meta?.commonjs?.requires?.length) return;
582
+ if (!info.meta.commonjs.requires.some((m) => m?.resolved?.id.endsWith("node-gyp-build/index.js"))) return;
583
+ modulesToTrack.add(info.id);
584
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
585
+ },
586
+ async generateBundle(options, bundle) {
587
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
588
+ for (const [fileName, chunk] of Object.entries(bundle)) if (chunk.type === "chunk") {
589
+ for (const moduleId of chunk.moduleIds) if (modulesToTrackPackageInfo.has(moduleId)) {
590
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
591
+ if (!binaryMapByChunk.has(fileName)) binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
592
+ if (pkgInfo?.packageJson?.name) binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
593
+ }
594
+ }
595
+ const binaryMapJson = Object.fromEntries(Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)]));
596
+ this.emitFile({
597
+ type: "asset",
598
+ name: "binary-map.json",
599
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
600
+ });
601
+ }
602
+ };
603
+ }
604
+ //#endregion
605
+ //#region src/build/analyze/bundleExternals.ts
606
+ function prepareEntryFileName(name, rootDir) {
607
+ return rollupSafeName(name, rootDir);
608
+ }
609
+ /**
610
+ * Creates virtual dependency modules for optimized bundling by generating virtual entry points for each dependency with their specific exports and handling workspace package path resolution.
611
+ */
612
+ function createVirtualDependencies(depsToOptimize, { projectRoot, workspaceRoot, outputDir, bundlerOptions }) {
613
+ const { isDev = false, externalsPreset = false } = bundlerOptions || {};
614
+ const fileNameToDependencyMap = /* @__PURE__ */ new Map();
615
+ const optimizedDependencyEntries = /* @__PURE__ */ new Map();
616
+ const rootDir = workspaceRoot || projectRoot;
617
+ for (const [dep, { exports }] of depsToOptimize.entries()) {
618
+ const fileName = dep.replaceAll("/", "__");
619
+ const virtualFile = [];
620
+ const exportStringBuilder = [];
621
+ for (const local of exports) if (local === "*") {
622
+ virtualFile.push(`export * from '${dep}';`);
623
+ continue;
624
+ } else if (local === "default") exportStringBuilder.push("default");
625
+ else exportStringBuilder.push(local);
626
+ const chunks = [];
627
+ if (exportStringBuilder.length) chunks.push(`{ ${exportStringBuilder.join(", ")} }`);
628
+ if (chunks.length) virtualFile.push(`export ${chunks.join(", ")} from '${dep}';`);
629
+ let entryName = prepareEntryFileName(path$1.join(outputDir, fileName), rootDir);
630
+ fileNameToDependencyMap.set(entryName, dep);
631
+ optimizedDependencyEntries.set(dep, {
632
+ name: entryName,
633
+ virtual: virtualFile.join("\n")
634
+ });
635
+ }
636
+ if (isDev || externalsPreset) for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
637
+ if (!isWorkspace || !rootPath || !workspaceRoot) continue;
638
+ const currentDepPath = optimizedDependencyEntries.get(dep);
639
+ if (!currentDepPath) continue;
640
+ const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, basename$1(currentDepPath.name)), rootDir);
641
+ fileNameToDependencyMap.set(entryName, dep);
642
+ optimizedDependencyEntries.set(dep, {
643
+ ...currentDepPath,
644
+ name: entryName
645
+ });
646
+ }
647
+ return {
648
+ optimizedDependencyEntries,
649
+ fileNameToDependencyMap
650
+ };
651
+ }
652
+ /**
653
+ * Configures and returns Rollup plugins for bundling external dependencies.
654
+ * Sets up virtual modules, TypeScript compilation, CommonJS transformation, and workspace resolution.
655
+ */
656
+ async function getInputPlugins(virtualDependencies, { transpilePackages, workspaceMap, bundlerOptions, rootDir, externals, platform }) {
657
+ const transpilePackagesMap = /* @__PURE__ */ new Map();
658
+ for (const pkg of transpilePackages) {
659
+ const dir = await getPackageRootPath(pkg);
660
+ if (dir) transpilePackagesMap.set(pkg, slash(dir));
661
+ else transpilePackagesMap.set(pkg, workspaceMap.get(pkg)?.location ?? pkg);
662
+ }
663
+ return [
664
+ virtual(Array.from(virtualDependencies.entries()).reduce((acc, [dep, virtualDep]) => {
665
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
666
+ return acc;
667
+ }, {})),
668
+ tsConfigPaths(),
669
+ protocolExternalResolver(),
670
+ subpathExternalsResolver(externals),
671
+ transpilePackagesMap.size ? esbuild({
672
+ format: "esm",
673
+ include: [...[...transpilePackagesMap.values()].map((p) => {
674
+ if (path$1.isAbsolute(p)) return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
675
+ else return new RegExp(`\/${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
676
+ }), ...[...transpilePackagesMap.keys()].map((pkgName) => {
677
+ const escapedPkgName = pkgName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
678
+ return new RegExp(`/node_modules/${escapedPkgName}/(?!.*node_modules).*$`);
679
+ })],
680
+ exclude: []
681
+ }) : null,
682
+ bundlerOptions.noBundling ? {
683
+ name: "alias-optimized-deps",
684
+ async resolveId(id, importer, options) {
685
+ if (!virtualDependencies.has(id)) return null;
686
+ const info = virtualDependencies.get(id);
687
+ const packageRootPath = path$1.join(rootDir, path$1.dirname(path$1.dirname(path$1.dirname(info.name))));
688
+ const pkgJsonBuffer = await readFile(path$1.join(packageRootPath, "package.json"), "utf-8");
689
+ const pkgJson = JSON.parse(pkgJsonBuffer);
690
+ if (!pkgJson) return null;
691
+ const pkgName = pkgJson.name || "";
692
+ let resolvedPath = resolve$1.exports(pkgJson, id.replace(pkgName, "."))?.[0];
693
+ if (!resolvedPath) resolvedPath = pkgJson.main ?? "index.js";
694
+ return await this.resolve(path$1.posix.join(packageRootPath, resolvedPath), importer, options);
695
+ }
696
+ } : null,
697
+ optimizeLodashImports({ include: "**/*.{js,ts,mjs,cjs}" }),
698
+ commonjs({
699
+ strictRequires: "strict",
700
+ transformMixedEsModules: true,
701
+ ignoreTryCatch: false
702
+ }),
703
+ bundlerOptions.noBundling ? null : nodeResolve(getNodeResolveOptions(platform)),
704
+ bundlerOptions.noBundling ? esmShim() : null,
705
+ aliasHono(),
706
+ json(),
707
+ nodeGypDetector(),
708
+ moduleResolveMap(externals, rootDir),
709
+ {
710
+ name: "not-found-resolver",
711
+ resolveId: {
712
+ order: "post",
713
+ async handler(id, importer) {
714
+ if (!importer) return null;
715
+ if (!id.endsWith(".node")) return null;
716
+ const packageName = (await getPackageInfo(importer))?.packageJson?.name || id;
717
+ throw new MastraBaseError({
718
+ id: "DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD",
719
+ domain: ErrorDomain.DEPLOYER,
720
+ category: ErrorCategory.USER,
721
+ details: {
722
+ importFile: importer,
723
+ packageName
724
+ },
725
+ text: `We found a possible binary dependency in your bundle. ${id} was not found when imported at ${importer}.
726
+
727
+ Please consider adding \`${packageName}\` to your externals, or updating this import to not end with ".node".
728
+
729
+ export const mastra = new Mastra({
730
+ bundler: {
731
+ externals: ["${packageName}"],
732
+ }
733
+ })`
734
+ });
735
+ }
736
+ }
737
+ }
738
+ ].filter(Boolean);
739
+ }
740
+ /**
741
+ * Executes the Rollup build process for virtual dependencies using configured plugins.
742
+ * Bundles all virtual dependency modules into optimized ESM files with proper external handling.
743
+ */
744
+ async function buildExternalDependencies(virtualDependencies, { externals, packagesToTranspile, workspaceMap, rootDir, outputDir, bundlerOptions, platform }) {
745
+ /**
746
+ * If there are no virtual dependencies to bundle, return an empty array to avoid Rollup errors.
747
+ */
748
+ if (virtualDependencies.size === 0) return [];
749
+ const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;
750
+ const plugins = await getInputPlugins(virtualDependencies, {
751
+ transpilePackages: packagesToTranspile,
752
+ workspaceMap,
753
+ bundlerOptions: { noBundling },
754
+ rootDir,
755
+ externals,
756
+ platform
757
+ });
758
+ const bundler = await rollup({
759
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
760
+ input: Array.from(virtualDependencies.entries()).reduce((acc, [dep, virtualDep]) => {
761
+ acc[virtualDep.name] = `#virtual-${dep}`;
762
+ return acc;
763
+ }, {}),
764
+ external: externals,
765
+ treeshake: noBundling ? false : "safest",
766
+ plugins
767
+ });
768
+ const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
769
+ const { output } = await bundler.write({
770
+ format: "esm",
771
+ dir: rootDir,
772
+ entryFileNames: "[name].mjs",
773
+ sourcemap: true,
774
+ /**
775
+ * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
776
+ * So we want to write them to the `.mastra/output` folder as well.
777
+ */
778
+ chunkFileNames: (chunkInfo) => {
779
+ /**
780
+ * This whole bunch of logic directly below is for the edge case shown in the e2e-tests/monorepo with "tinyrainbow" package. It's used in multiple places in the package and as such Rollup creates a shared chunk for it. During 'mastra dev' / with externals: true, we don't want that chunk to show up in the '.mastra/output' folder (outputDirRelative) but inside <pkg>/node_modules/.cache instead.
781
+ * We only care about this for the "noBundling" case!
782
+ */
783
+ if (noBundling) {
784
+ const importedFromPackages = /* @__PURE__ */ new Set();
785
+ for (const moduleId of chunkInfo.moduleIds) {
786
+ const normalized = slash(moduleId);
787
+ for (const [pkgName, pkgInfo] of workspaceMap.entries()) {
788
+ const location = slash(pkgInfo.location);
789
+ if (normalized.startsWith(location)) {
790
+ importedFromPackages.add(pkgName);
791
+ break;
792
+ }
793
+ }
794
+ }
795
+ if (importedFromPackages.size > 1) throw new MastraBaseError({
796
+ id: "DEPLOYER_BUNDLE_EXTERNALS_SHARED_CHUNK",
797
+ domain: ErrorDomain.DEPLOYER,
798
+ category: ErrorCategory.USER,
799
+ details: {
800
+ chunkName: chunkInfo.name,
801
+ packages: JSON.stringify(Array.from(importedFromPackages))
802
+ },
803
+ text: `Please open an issue. We found a shared chunk "${chunkInfo.name}" used by multiple workspace packages: ${Array.from(importedFromPackages).join(", ")}.`
804
+ });
805
+ if (importedFromPackages.size === 1) {
806
+ const [pkgName] = importedFromPackages;
807
+ const workspaceLocation = workspaceMap.get(pkgName).location;
808
+ return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
809
+ }
810
+ }
811
+ return `${outputDirRelative}/[name].mjs`;
812
+ },
813
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
814
+ hoistTransitiveImports: false
815
+ });
816
+ await bundler.close();
817
+ return output;
818
+ }
819
+ /**
820
+ * Recursively searches through Rollup output chunks to find which module imports a specific external dependency.
821
+ * Used to build the module resolution map for proper external dependency tracking.
822
+ */
823
+ function findExternalImporter(module, external, allOutputs, visited = /* @__PURE__ */ new Set()) {
824
+ if (visited.has(module.fileName)) return null;
825
+ visited.add(module.fileName);
826
+ const capturedFiles = /* @__PURE__ */ new Set();
827
+ for (const id of [...module.imports, ...module.dynamicImports]) if (isDependencyPartOfPackage(id, external)) return module;
828
+ else if (id.endsWith(".mjs")) capturedFiles.add(id);
829
+ for (const file of capturedFiles) {
830
+ const nextModule = allOutputs.find((o) => o.fileName === file);
831
+ if (nextModule) {
832
+ const importer = findExternalImporter(nextModule, external, allOutputs, visited);
833
+ if (importer) return importer;
834
+ }
835
+ }
836
+ return null;
837
+ }
838
+ /**
839
+ * Bundles vendor dependencies identified in the analysis step.
840
+ * Creates virtual modules for each dependency and bundles them using rollup.
841
+ *
842
+ * @param depsToOptimize - Map of dependencies to optimize with their metadata (exported bindings, rootPath, isWorkspace)
843
+ * @param outputDir - Directory where bundled files will be written
844
+ * @param logger - Logger instance for debugging
845
+ * @returns Object containing bundle output and reference map for validation
846
+ */
847
+ async function bundleExternals(depsToOptimize, outputDir, options) {
848
+ const { workspaceRoot = null, workspaceMap = /* @__PURE__ */ new Map(), projectRoot = outputDir, bundlerOptions = {}, platform = "node" } = options;
849
+ const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
850
+ /**
851
+ * A user can set `externals: true` to indicate they want to externalize all dependencies. In this case, we set `externalsPreset` to true to skip bundling any externals.
852
+ */
853
+ let externalsPreset = false;
854
+ if (customExternals === true) externalsPreset = true;
855
+ const externalsList = Array.isArray(customExternals) ? customExternals : [];
856
+ const allExternals = [
857
+ ...GLOBAL_EXTERNALS,
858
+ ...DEPRECATED_EXTERNALS,
859
+ ...externalsList
860
+ ];
861
+ const workspacePackagesNames = Array.from(workspaceMap.keys());
862
+ const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
863
+ /**
864
+ * When externals: true, we need to extract non-workspace deps from depsToOptimize
865
+ * and add them directly to usedExternals instead of bundling them.
866
+ */
867
+ const extractedExternals = /* @__PURE__ */ new Map();
868
+ if (externalsPreset) {
869
+ for (const [dep, metadata] of depsToOptimize.entries()) if (!metadata.isWorkspace) {
870
+ extractedExternals.set(dep, metadata.rootPath ?? dep);
871
+ depsToOptimize.delete(dep);
872
+ }
873
+ }
874
+ const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {
875
+ workspaceRoot,
876
+ outputDir,
877
+ projectRoot,
878
+ bundlerOptions: {
879
+ isDev,
880
+ externalsPreset
881
+ }
882
+ });
883
+ const output = await buildExternalDependencies(optimizedDependencyEntries, {
884
+ externals: allExternals,
885
+ packagesToTranspile,
886
+ workspaceMap,
887
+ rootDir: workspaceRoot || projectRoot,
888
+ outputDir,
889
+ bundlerOptions: {
890
+ isDev,
891
+ externalsPreset
892
+ },
893
+ platform
894
+ });
895
+ const moduleResolveMap = /* @__PURE__ */ new Map();
896
+ const filteredChunks = output.filter((o) => o.type === "chunk");
897
+ for (const o of filteredChunks.filter((o) => o.isEntry || o.isDynamicEntry)) for (const external of allExternals) {
898
+ if (DEPS_TO_IGNORE.includes(external)) continue;
899
+ const importer = findExternalImporter(o, external, filteredChunks);
900
+ if (importer) {
901
+ const fullPath = path$1.join(workspaceRoot || projectRoot, importer.fileName);
902
+ let innerMap = moduleResolveMap.get(fullPath);
903
+ if (!innerMap) {
904
+ innerMap = /* @__PURE__ */ new Map();
905
+ moduleResolveMap.set(fullPath, innerMap);
906
+ }
907
+ if (importer.moduleIds.length) innerMap.set(external, importer.moduleIds[importer.moduleIds.length - 1]?.startsWith("\0virtual:#virtual") ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1]);
908
+ }
909
+ }
910
+ /**
911
+ * Convert moduleResolveMap to a plain object with prototype-less objects
912
+ */
913
+ const usedExternals = Object.create(null);
914
+ for (const [fullPath, innerMap] of moduleResolveMap) {
915
+ const innerObj = Object.create(null);
916
+ for (const [external, value] of innerMap) innerObj[external] = value;
917
+ usedExternals[fullPath] = innerObj;
918
+ }
919
+ /**
920
+ * When externals: true, add the extracted non-workspace deps to usedExternals
921
+ * using a synthetic entry path to track them.
922
+ */
923
+ if (extractedExternals.size > 0) {
924
+ const syntheticPath = path$1.join(workspaceRoot || projectRoot, "__externals__");
925
+ const externalsObj = Object.create(null);
926
+ for (const [dep, rootPath] of extractedExternals) externalsObj[dep] = rootPath;
927
+ usedExternals[syntheticPath] = externalsObj;
928
+ }
929
+ return {
930
+ output,
931
+ fileNameToDependencyMap,
932
+ usedExternals
933
+ };
934
+ }
935
+ //#endregion
936
+ //#region src/build/babel/check-config-export.ts
937
+ function checkConfigExport(result) {
938
+ const mastraVars = /* @__PURE__ */ new Set();
939
+ return { visitor: {
940
+ NewExpression(path) {
941
+ if (!types.isIdentifier(path.node.callee)) return;
942
+ const binding = path.scope.getBinding(path.node.callee.name);
943
+ if (binding?.path.isImportSpecifier() && types.isIdentifier(binding.path.node.imported, { name: "MastraFactory" })) result.projectType = "factory";
944
+ },
945
+ ExportNamedDeclaration(path) {
946
+ const decl = path.node.declaration;
947
+ if (types.isVariableDeclaration(decl)) {
948
+ const varDecl = decl.declarations[0];
949
+ if (types.isIdentifier(varDecl?.id, { name: "mastra" }) && types.isNewExpression(varDecl.init) && types.isIdentifier(varDecl.init.callee, { name: "Mastra" })) result.hasValidConfig = true;
950
+ }
951
+ /**
952
+ * 2) export { foo as mastra }
953
+ * 3) export { mastra }
954
+ * 4) export { mastra, foo }
955
+ */
956
+ if (Array.isArray(path.node.specifiers)) {
957
+ for (const spec of path.node.specifiers) if (types.isExportSpecifier(spec) && types.isIdentifier(spec.exported, { name: "mastra" }) && types.isIdentifier(spec.local) && mastraVars.has(spec.local.name)) result.hasValidConfig = true;
958
+ }
959
+ },
960
+ VariableDeclaration(path) {
961
+ for (const decl of path.node.declarations) if (types.isIdentifier(decl.id) && types.isNewExpression(decl.init) && types.isIdentifier(decl.init.callee, { name: "Mastra" })) mastraVars.add(decl.id.name);
962
+ }
963
+ } };
964
+ }
965
+ //#endregion
966
+ //#region src/build/babel/detect-pino-transports.ts
967
+ /**
968
+ * Extract string value from a node (supports StringLiteral and TemplateLiteral without expressions)
969
+ */
970
+ function getStringValue(node) {
971
+ if (!node) return null;
972
+ if (types.isStringLiteral(node)) return node.value;
973
+ if (types.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) return node.quasis[0]?.value.cooked ?? null;
974
+ return null;
975
+ }
976
+ /**
977
+ * Extract target value from an object property
978
+ */
979
+ function extractTargetFromProperty(prop) {
980
+ if (!types.isObjectProperty(prop)) return null;
981
+ const key = prop.key;
982
+ if (types.isIdentifier(key, { name: "target" }) || types.isStringLiteral(key) && key.value === "target") return getStringValue(prop.value);
983
+ return null;
984
+ }
985
+ /**
986
+ * Check if a binding came from a pino import/require
987
+ */
988
+ function isBindingFromPino(path, identifierName) {
989
+ const binding = path.scope.getBinding(identifierName);
990
+ if (!binding) return identifierName === "pino";
991
+ const bindingPath = binding.path;
992
+ if (bindingPath.isImportDefaultSpecifier()) {
993
+ const importDecl = bindingPath.parentPath;
994
+ if (importDecl?.isImportDeclaration()) return importDecl.node.source.value === "pino";
995
+ }
996
+ if (bindingPath.isImportNamespaceSpecifier()) {
997
+ const importDecl = bindingPath.parentPath;
998
+ if (importDecl?.isImportDeclaration()) return importDecl.node.source.value === "pino";
999
+ }
1000
+ if (bindingPath.isImportSpecifier()) {
1001
+ const importDecl = bindingPath.parentPath;
1002
+ if (importDecl?.isImportDeclaration() && importDecl.node.source.value === "pino") {
1003
+ const imported = bindingPath.node.imported;
1004
+ if (types.isIdentifier(imported) && imported.name === "default") return true;
1005
+ if (types.isStringLiteral(imported) && imported.value === "default") return true;
1006
+ }
1007
+ return false;
1008
+ }
1009
+ if (bindingPath.isVariableDeclarator()) {
1010
+ const init = bindingPath.node.init;
1011
+ if (types.isCallExpression(init) && types.isIdentifier(init.callee, { name: "require" }) && init.arguments.length === 1 && types.isStringLiteral(init.arguments[0]) && init.arguments[0].value === "pino") return true;
1012
+ }
1013
+ return false;
1014
+ }
1015
+ /**
1016
+ * Check if a call expression is a pino.transport() call using scope analysis
1017
+ */
1018
+ function isPinoTransportCall(path) {
1019
+ const callee = path.node.callee;
1020
+ if (!types.isMemberExpression(callee)) return false;
1021
+ if (!types.isIdentifier(callee.property, { name: "transport" })) return false;
1022
+ if (types.isIdentifier(callee.object)) return isBindingFromPino(path, callee.object.name);
1023
+ if (types.isMemberExpression(callee.object) && types.isIdentifier(callee.object.object) && types.isIdentifier(callee.object.property, { name: "default" })) return isBindingFromPino(path, callee.object.object.name);
1024
+ return false;
1025
+ }
1026
+ /**
1027
+ * Extract transport targets from a pino.transport() argument
1028
+ */
1029
+ function extractTransportsFromArg(arg) {
1030
+ const targets = [];
1031
+ if (!types.isObjectExpression(arg)) return targets;
1032
+ for (const prop of arg.properties) {
1033
+ if (!types.isObjectProperty(prop)) continue;
1034
+ const key = prop.key;
1035
+ const keyName = types.isIdentifier(key) ? key.name : types.isStringLiteral(key) ? key.value : null;
1036
+ if (keyName === "target") {
1037
+ const value = getStringValue(prop.value);
1038
+ if (value) targets.push(value);
1039
+ } else if (keyName === "targets") {
1040
+ if (types.isArrayExpression(prop.value)) {
1041
+ for (const element of prop.value.elements) if (types.isObjectExpression(element)) for (const innerProp of element.properties) {
1042
+ const targetValue = extractTargetFromProperty(innerProp);
1043
+ if (targetValue) targets.push(targetValue);
1044
+ }
1045
+ }
1046
+ }
1047
+ }
1048
+ return targets;
1049
+ }
1050
+ /**
1051
+ * Babel plugin to detect pino transport targets in code.
1052
+ * Matches patterns like:
1053
+ * - pino.transport({ target: "package-name" })
1054
+ * - pino.transport({ targets: [{ target: "package-name" }] })
1055
+ * - variable.transport({ target: "..." }) where variable is assigned from pino import
1056
+ *
1057
+ * @param transports - Set to collect detected transport package names
1058
+ * @returns Babel plugin object
1059
+ */
1060
+ function detectPinoTransports(transports) {
1061
+ return {
1062
+ name: "detect-pino-transports",
1063
+ visitor: { CallExpression(path) {
1064
+ if (!isPinoTransportCall(path)) return;
1065
+ const firstArg = path.node.arguments[0];
1066
+ if (firstArg && !types.isSpreadElement(firstArg)) for (const target of extractTransportsFromArg(firstArg)) transports.add(target);
1067
+ } }
1068
+ };
1069
+ }
1070
+ //#endregion
1071
+ //#region src/build/analyze.ts
1072
+ function preferDependencyInfo(existing, incoming) {
1073
+ return {
1074
+ version: incoming.version ?? existing?.version,
1075
+ packageSpec: incoming.packageSpec ?? existing?.packageSpec
1076
+ };
1077
+ }
1078
+ async function resolveDependencyInfo(dep, existing, parentPaths) {
1079
+ if (existing?.version || existing?.packageSpec) return existing;
1080
+ const packageName = getPackageName(dep);
1081
+ const packageNames = [...new Set([dep, packageName].filter(Boolean))];
1082
+ for (const parentPath of parentPaths) for (const name of packageNames) {
1083
+ const metadata = await getPackageMetadata(name, parentPath);
1084
+ if (metadata.version || metadata.packageSpec) return preferDependencyInfo(existing, metadata);
1085
+ }
1086
+ for (const name of packageNames) {
1087
+ const metadata = await getPackageMetadata(name);
1088
+ if (metadata.version || metadata.packageSpec) return preferDependencyInfo(existing, metadata);
1089
+ }
1090
+ return existing ?? {};
1091
+ }
1092
+ function importerParentPaths(importerId, base) {
1093
+ if (!importerId || importerId.startsWith("\0") || !isAbsolute(importerId)) return base;
1094
+ return [.../* @__PURE__ */ new Set([importerId, ...base])];
1095
+ }
1096
+ function getLastConcreteModuleId(moduleIds) {
1097
+ return moduleIds.findLast((id) => !id.startsWith("\0") && isAbsolute(id));
1098
+ }
1099
+ function throwExternalDependencyError({ errorId, moduleName, packageName, messagePrefix }) {
1100
+ throw new MastraError({
1101
+ id: errorId,
1102
+ domain: ErrorDomain.DEPLOYER,
1103
+ category: ErrorCategory.USER,
1104
+ details: {
1105
+ importFile: moduleName,
1106
+ packageName
1107
+ },
1108
+ text: `${messagePrefix} \`${packageName}\` to your externals.
1109
+
1110
+ export const mastra = new Mastra({
1111
+ bundler: {
1112
+ externals: ["${packageName}"],
1113
+ }
1114
+ })`
1115
+ });
1116
+ }
1117
+ function getPackageNameFromBundledModuleName(moduleName) {
1118
+ if (moduleName.includes("__")) return moduleName.replaceAll("__", "/");
1119
+ const chunks = moduleName.split("-");
1120
+ if (!chunks.length) return moduleName;
1121
+ if (chunks[0]?.startsWith("@")) return chunks.slice(0, 2).join("/");
1122
+ return chunks[0];
1123
+ }
1124
+ function validateError(err, file, { binaryMapData, workspaceMap }) {
1125
+ let moduleName = null;
1126
+ let errorConfig = null;
1127
+ if (err instanceof ValidationError) {
1128
+ const parsedStack = import_stack_trace_parser_cjs.parse(err.stack);
1129
+ if (err.type === "TypeError") {
1130
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1131
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1132
+ if (stacktraceFrame) moduleName = stacktraceFrame.file.match(pkgNameRegex)?.[1] ?? getPackageNameFromBundledModuleName(basename(file.name));
1133
+ else moduleName = getPackageNameFromBundledModuleName(basename(file.name));
1134
+ errorConfig = {
1135
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1136
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1137
+ };
1138
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1139
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1140
+ const parentModuleName = getPackageNameFromBundledModuleName(basename(file.name));
1141
+ errorConfig = {
1142
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1143
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1144
+ };
1145
+ if (moduleName === parentModuleName) return;
1146
+ }
1147
+ }
1148
+ if (err.message.includes("No native build was found")) {
1149
+ const pkgName = getPackageNameFromBundledModuleName(basename(file.name));
1150
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1151
+ errorConfig = {
1152
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1153
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1154
+ };
1155
+ }
1156
+ if (moduleName && workspaceMap.has(moduleName)) throw new MastraError({
1157
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1158
+ domain: ErrorDomain.DEPLOYER,
1159
+ category: ErrorCategory.USER,
1160
+ details: { packageName: moduleName },
1161
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1162
+ Error: ${err.stack}`
1163
+ });
1164
+ if (errorConfig && moduleName) throwExternalDependencyError({
1165
+ errorId: errorConfig.id,
1166
+ moduleName,
1167
+ packageName: moduleName,
1168
+ messagePrefix: errorConfig.messagePrefix
1169
+ });
1170
+ }
1171
+ async function validateFile(root, file, { binaryMapData, moduleResolveMapLocation, logger, workspaceMap, stubbedExternals }) {
1172
+ try {
1173
+ if (!file.isDynamicEntry && file.isEntry) await validate(join(root, file.fileName), {
1174
+ moduleResolveMapLocation,
1175
+ injectESMShim: false,
1176
+ stubbedExternals
1177
+ });
1178
+ } catch (err) {
1179
+ let errorToHandle = err;
1180
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) try {
1181
+ await validate(join(root, file.fileName), {
1182
+ moduleResolveMapLocation,
1183
+ injectESMShim: true,
1184
+ stubbedExternals
1185
+ });
1186
+ errorToHandle = null;
1187
+ } catch (err) {
1188
+ errorToHandle = err;
1189
+ }
1190
+ if (errorToHandle instanceof Error) validateError(errorToHandle, file, {
1191
+ binaryMapData,
1192
+ logger,
1193
+ workspaceMap
1194
+ });
1195
+ }
1196
+ }
1197
+ /**
1198
+ * Validates the bundled output by attempting to import each generated module.
1199
+ * Tracks external dependencies that couldn't be bundled.
1200
+ *
1201
+ * @param output - Bundle output from rollup
1202
+ * @param reverseVirtualReferenceMap - Map to resolve virtual module names back to original deps
1203
+ * @param outputDir - Directory containing the bundled files
1204
+ * @param logger - Logger instance for debugging
1205
+ * @param workspaceMap - Map of workspace packages that gets directly passed through for later consumption
1206
+ * @returns Analysis result containing dependency mappings
1207
+ */
1208
+ async function validateOutput({ output, reverseVirtualReferenceMap, usedExternals, userExternals, outputDir, projectRoot, workspaceMap, depsVersionInfo }, logger) {
1209
+ const result = {
1210
+ dependencies: /* @__PURE__ */ new Map(),
1211
+ externalDependencies: /* @__PURE__ */ new Map(),
1212
+ workspaceMap
1213
+ };
1214
+ const externalMetadataParentPaths = [projectRoot, ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location)];
1215
+ for (const deps of Object.values(usedExternals)) for (const [dep, importerId] of Object.entries(deps)) {
1216
+ if (isExternalProtocolImport(dep)) continue;
1217
+ const pkgName = getPackageName(dep);
1218
+ if (pkgName) {
1219
+ const dependencyInfo = await resolveDependencyInfo(dep, depsVersionInfo.get(dep) || depsVersionInfo.get(pkgName), importerParentPaths(importerId, externalMetadataParentPaths));
1220
+ result.externalDependencies.set(pkgName, preferDependencyInfo(result.externalDependencies.get(pkgName), dependencyInfo));
1221
+ }
1222
+ }
1223
+ let binaryMapData = {};
1224
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1225
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1226
+ binaryMapData = JSON.parse(binaryMap);
1227
+ }
1228
+ const stubbedExternals = [.../* @__PURE__ */ new Set([
1229
+ ...GLOBAL_EXTERNALS,
1230
+ ...DEPS_TO_IGNORE,
1231
+ ...userExternals,
1232
+ ...result.externalDependencies.keys()
1233
+ ])];
1234
+ for (const file of output) {
1235
+ if (file.type === "asset") continue;
1236
+ logger.debug("Validating module", { fileName: file.fileName });
1237
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1238
+ await validateFile(projectRoot, file, {
1239
+ binaryMapData,
1240
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1241
+ logger,
1242
+ workspaceMap,
1243
+ stubbedExternals
1244
+ });
1245
+ }
1246
+ return result;
1247
+ }
1248
+ /**
1249
+ * Main bundle analysis function that orchestrates the three-step process:
1250
+ * 1. Analyze dependencies
1251
+ * 2. Bundle dependencies modules
1252
+ * 3. Validate generated bundles
1253
+ *
1254
+ * This helps identify which dependencies need to be externalized vs bundled.
1255
+ */
1256
+ async function analyzeBundle(entries, mastraEntry, { outputDir, projectRoot, platform, isDev = false, bundlerOptions }, logger) {
1257
+ const mastraConfig = await readFile(mastraEntry, "utf-8");
1258
+ const mastraConfigResult = { hasValidConfig: false };
1259
+ await transformAsync(mastraConfig, {
1260
+ filename: mastraEntry,
1261
+ presets: [import.meta.resolve("@babel/preset-typescript")],
1262
+ plugins: [() => checkConfigExport(mastraConfigResult)]
1263
+ });
1264
+ if (!mastraConfigResult.hasValidConfig) logger.warn("Invalid Mastra config", { details: "Please make sure that your entry file looks like this:\nexport const mastra = new Mastra({\n // your options\n})\n\nIf you think your configuration is valid, please open an issue." });
1265
+ const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1266
+ let externalsPreset = false;
1267
+ const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
1268
+ const userDynamicPackages = bundlerOptions?.dynamicPackages ?? [];
1269
+ if (bundlerOptions?.externals === true) externalsPreset = true;
1270
+ let index = 0;
1271
+ const depsToOptimize = /* @__PURE__ */ new Map();
1272
+ const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
1273
+ const detectedPinoTransports = /* @__PURE__ */ new Set();
1274
+ logger.info("Analyzing dependencies...");
1275
+ const allUsedExternals = /* @__PURE__ */ new Map();
1276
+ const analyzeCache = /* @__PURE__ */ new Map();
1277
+ for (const entry of entries) {
1278
+ const analyzeResult = await analyzeEntry({
1279
+ entry,
1280
+ isVirtualFile: entry.includes("\n") || !existsSync(entry)
1281
+ }, mastraEntry, {
1282
+ logger,
1283
+ sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,
1284
+ workspaceMap,
1285
+ projectRoot,
1286
+ shouldCheckTransitiveDependencies: true,
1287
+ analyzeCache
1288
+ });
1289
+ transformSync(analyzeResult.output.code, {
1290
+ filename: "pino-detection.js",
1291
+ plugins: [() => detectPinoTransports(detectedPinoTransports)],
1292
+ configFile: false,
1293
+ babelrc: false,
1294
+ code: false
1295
+ });
1296
+ await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1297
+ for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1298
+ if (allExternals.some((external) => isDependencyPartOfPackage(dep, external)) || externalsPreset && !metadata.isWorkspace) {
1299
+ const pkgName = getPackageName(dep);
1300
+ if (pkgName) allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), metadata));
1301
+ continue;
1302
+ }
1303
+ if (depsToOptimize.has(dep)) {
1304
+ const existingEntry = depsToOptimize.get(dep);
1305
+ depsToOptimize.set(dep, {
1306
+ ...existingEntry,
1307
+ version: metadata.version ?? existingEntry.version,
1308
+ packageSpec: metadata.packageSpec ?? existingEntry.packageSpec,
1309
+ exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...metadata.exports])]
1310
+ });
1311
+ } else depsToOptimize.set(dep, metadata);
1312
+ }
1313
+ }
1314
+ const depsVersionInfo = /* @__PURE__ */ new Map();
1315
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1316
+ const pkgName = getPackageName(dep);
1317
+ if (pkgName && (metadata.version || metadata.packageSpec)) depsVersionInfo.set(pkgName, preferDependencyInfo(depsVersionInfo.get(pkgName), metadata));
1318
+ if (metadata.version || metadata.packageSpec) depsVersionInfo.set(dep, preferDependencyInfo(depsVersionInfo.get(dep), metadata));
1319
+ }
1320
+ /**
1321
+ * Only during `mastra dev` we want to optimize workspace packages. In previous steps we might have added dependencies that are not workspace packages, so we gotta remove them again.
1322
+ */
1323
+ if (isDev || externalsPreset) {
1324
+ for (const [dep, metadata] of depsToOptimize.entries()) if (!metadata.isWorkspace) depsToOptimize.delete(dep);
1325
+ }
1326
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1327
+ logger.info("Optimizing dependencies...");
1328
+ logger.debug("Sorted dependencies", { deps: sortedDeps });
1329
+ const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1330
+ bundlerOptions: {
1331
+ ...bundlerOptions,
1332
+ externals: bundlerOptions?.externals ?? allExternals,
1333
+ isDev
1334
+ },
1335
+ projectRoot,
1336
+ workspaceRoot,
1337
+ workspaceMap,
1338
+ platform
1339
+ });
1340
+ const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map((pkgInfo) => slash(relative(workspaceRoot || projectRoot, pkgInfo.location)));
1341
+ for (const o of output) {
1342
+ if (o.type === "asset") continue;
1343
+ const importerId = getLastConcreteModuleId(o.moduleIds);
1344
+ for (const i of o.imports) {
1345
+ if (isBuiltinModule(i)) continue;
1346
+ if (i.startsWith(".") || i.startsWith("/")) continue;
1347
+ if (!isBareModuleSpecifier(i) || isExternalProtocolImport(i)) continue;
1348
+ if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) continue;
1349
+ const pkgName = getPackageName(i);
1350
+ if (pkgName && workspaceMap.has(pkgName)) continue;
1351
+ if (pkgName) {
1352
+ const dependencyInfo = await resolveDependencyInfo(i, depsVersionInfo.get(i) || depsVersionInfo.get(pkgName), importerParentPaths(importerId, [projectRoot, ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location)]));
1353
+ allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), dependencyInfo));
1354
+ }
1355
+ }
1356
+ }
1357
+ const result = await validateOutput({
1358
+ output,
1359
+ reverseVirtualReferenceMap: fileNameToDependencyMap,
1360
+ usedExternals,
1361
+ userExternals,
1362
+ outputDir,
1363
+ projectRoot: workspaceRoot || projectRoot,
1364
+ workspaceMap,
1365
+ depsVersionInfo
1366
+ }, logger);
1367
+ /**
1368
+ * Build the final set of external dependencies from four sources:
1369
+ * 1. result.externalDependencies - externals discovered during bundle validation
1370
+ * 2. allUsedExternals - packages detected via static analysis that matched the externals config
1371
+ * 3. detectedPinoTransports - pino transports detected by the plugin during bundling
1372
+ * 4. userDynamicPackages - user-specified packages loaded dynamically at runtime
1373
+ *
1374
+ * Prefer entries with version info over entries without
1375
+ */
1376
+ const mergedExternalDeps = new Map(result.externalDependencies);
1377
+ for (const [dep, info] of allUsedExternals) {
1378
+ if (isExternalProtocolImport(dep)) continue;
1379
+ mergedExternalDeps.set(dep, preferDependencyInfo(mergedExternalDeps.get(dep), info));
1380
+ }
1381
+ const externalMetadataParentPaths = [
1382
+ projectRoot,
1383
+ ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location),
1384
+ import.meta.dirname
1385
+ ];
1386
+ for (const [dep, info] of mergedExternalDeps) if (!info.version && !info.packageSpec) mergedExternalDeps.set(dep, await resolveDependencyInfo(dep, info, externalMetadataParentPaths));
1387
+ for (const transport of detectedPinoTransports) if (!mergedExternalDeps.has(transport)) mergedExternalDeps.set(transport, await resolveDependencyInfo(transport, void 0, externalMetadataParentPaths));
1388
+ for (const pkg of userDynamicPackages) if (!mergedExternalDeps.has(pkg)) mergedExternalDeps.set(pkg, await resolveDependencyInfo(pkg, void 0, externalMetadataParentPaths));
1389
+ return {
1390
+ ...result,
1391
+ externalDependencies: mergedExternalDeps,
1392
+ /**
1393
+ * Workspace deps that were optimized (after isDev/externalsPreset pruning).
1394
+ * Used by the watcher to re-run optimization when workspace sources change.
1395
+ */
1396
+ depsToOptimize,
1397
+ workspaceRoot,
1398
+ outputDir,
1399
+ ...mastraConfigResult.projectType ? { projectType: mastraConfigResult.projectType } : {}
1400
+ };
1401
+ }
1402
+ //#endregion
1403
+ export { collectTransitiveWorkspaceDependencies as a, aliasHono as i, checkConfigExport as n, getWorkspaceInformation as o, bundleExternals as r, packWorkspaceDependencies as s, analyzeBundle as t };
1404
+
1405
+ //# sourceMappingURL=analyze-7xxwhB5F.js.map