@mastra/deployer 0.0.0-error-handler-fix-20251020202607 → 0.0.0-execa-dynamic-import-20260304221256

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 (283) hide show
  1. package/CHANGELOG.md +1850 -5
  2. package/LICENSE.md +15 -0
  3. package/dist/arktype-aI7TBD0R-MD6ESOAI.js +8 -0
  4. package/dist/arktype-aI7TBD0R-MD6ESOAI.js.map +1 -0
  5. package/dist/arktype-aI7TBD0R-MS2OLT4Z.cjs +10 -0
  6. package/dist/arktype-aI7TBD0R-MS2OLT4Z.cjs.map +1 -0
  7. package/dist/build/analyze/analyzeEntry.d.ts +8 -4
  8. package/dist/build/analyze/analyzeEntry.d.ts.map +1 -1
  9. package/dist/build/analyze/bundleExternals.d.ts +8 -7
  10. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  11. package/dist/build/analyze/constants.d.ts.map +1 -1
  12. package/dist/build/analyze.cjs +2 -2
  13. package/dist/build/analyze.d.ts +7 -7
  14. package/dist/build/analyze.d.ts.map +1 -1
  15. package/dist/build/analyze.js +1 -1
  16. package/dist/build/babel/remove-all-options-except.d.ts +1 -1
  17. package/dist/build/babel/remove-all-options-except.d.ts.map +1 -1
  18. package/dist/build/babel/remove-deployer.d.ts.map +1 -1
  19. package/dist/build/bundler.cjs +3 -3
  20. package/dist/build/bundler.d.ts +5 -3
  21. package/dist/build/bundler.d.ts.map +1 -1
  22. package/dist/build/bundler.js +1 -1
  23. package/dist/build/bundlerOptions.d.ts +1 -1
  24. package/dist/build/bundlerOptions.d.ts.map +1 -1
  25. package/dist/build/deployer.d.ts +1 -1
  26. package/dist/build/deployer.d.ts.map +1 -1
  27. package/dist/build/index.cjs +31 -22
  28. package/dist/build/index.d.ts +2 -1
  29. package/dist/build/index.d.ts.map +1 -1
  30. package/dist/build/index.js +6 -5
  31. package/dist/build/package-info.d.ts +9 -0
  32. package/dist/build/package-info.d.ts.map +1 -0
  33. package/dist/build/plugins/esm-shim.d.ts +14 -0
  34. package/dist/build/plugins/esm-shim.d.ts.map +1 -0
  35. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  36. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  37. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  38. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  39. package/dist/build/plugins/node-modules-extension-resolver.d.ts +7 -0
  40. package/dist/build/plugins/node-modules-extension-resolver.d.ts.map +1 -1
  41. package/dist/build/plugins/pino.d.ts.map +1 -1
  42. package/dist/build/plugins/remove-all-except.d.ts +10 -0
  43. package/dist/build/plugins/remove-all-except.d.ts.map +1 -0
  44. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  45. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  46. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  47. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  48. package/dist/build/serverOptions.d.ts +1 -1
  49. package/dist/build/serverOptions.d.ts.map +1 -1
  50. package/dist/build/shared/extract-mastra-option.d.ts +5 -9
  51. package/dist/build/shared/extract-mastra-option.d.ts.map +1 -1
  52. package/dist/build/types.d.ts +18 -0
  53. package/dist/build/types.d.ts.map +1 -1
  54. package/dist/build/utils.d.ts +79 -4
  55. package/dist/build/utils.d.ts.map +1 -1
  56. package/dist/build/watcher.d.ts +4 -1
  57. package/dist/build/watcher.d.ts.map +1 -1
  58. package/dist/bundler/index.cjs +6 -2
  59. package/dist/bundler/index.d.ts +13 -10
  60. package/dist/bundler/index.d.ts.map +1 -1
  61. package/dist/bundler/index.js +1 -1
  62. package/dist/chunk-32UHMKRP.cjs +95 -0
  63. package/dist/chunk-32UHMKRP.cjs.map +1 -0
  64. package/dist/chunk-6UIXBIO6.js +1322 -0
  65. package/dist/chunk-6UIXBIO6.js.map +1 -0
  66. package/dist/chunk-73SEUI3W.cjs +1353 -0
  67. package/dist/chunk-73SEUI3W.cjs.map +1 -0
  68. package/dist/chunk-ANF3UFZ3.js +318 -0
  69. package/dist/chunk-ANF3UFZ3.js.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-EBHDMP6N.cjs +122 -0
  73. package/dist/chunk-EBHDMP6N.cjs.map +1 -0
  74. package/dist/{chunk-WAWEQ3DP.js → chunk-EZBW45SX.js} +72 -32
  75. package/dist/chunk-EZBW45SX.js.map +1 -0
  76. package/dist/chunk-G7R456H2.cjs +108 -0
  77. package/dist/chunk-G7R456H2.cjs.map +1 -0
  78. package/dist/chunk-IMLDKOVJ.js +98 -0
  79. package/dist/chunk-IMLDKOVJ.js.map +1 -0
  80. package/dist/chunk-JNSGICDP.js +159 -0
  81. package/dist/chunk-JNSGICDP.js.map +1 -0
  82. package/dist/{chunk-3JYRSECU.cjs → chunk-JVBCN3RH.cjs} +4 -4
  83. package/dist/chunk-JVBCN3RH.cjs.map +1 -0
  84. package/dist/{chunk-LGC3GUMR.cjs → chunk-MEHKYO3L.cjs} +89 -153
  85. package/dist/chunk-MEHKYO3L.cjs.map +1 -0
  86. package/dist/chunk-NQTC7BHX.cjs +4 -0
  87. package/dist/chunk-NQTC7BHX.cjs.map +1 -0
  88. package/dist/chunk-O73YCD6A.js +262 -0
  89. package/dist/chunk-O73YCD6A.js.map +1 -0
  90. package/dist/chunk-PF6MO6L3.cjs +162 -0
  91. package/dist/chunk-PF6MO6L3.cjs.map +1 -0
  92. package/dist/{chunk-HMMDNIEQ.cjs → chunk-R2SYO6PH.cjs} +79 -39
  93. package/dist/chunk-R2SYO6PH.cjs.map +1 -0
  94. package/dist/chunk-TFSGAJE4.cjs +16 -0
  95. package/dist/chunk-TFSGAJE4.cjs.map +1 -0
  96. package/dist/chunk-UCL7MHBL.js +93 -0
  97. package/dist/chunk-UCL7MHBL.js.map +1 -0
  98. package/dist/chunk-UPVHAZ5Q.cjs +288 -0
  99. package/dist/chunk-UPVHAZ5Q.cjs.map +1 -0
  100. package/dist/chunk-UQZFTY5Q.cjs +8 -0
  101. package/dist/chunk-UQZFTY5Q.cjs.map +1 -0
  102. package/dist/{chunk-465ZVXAK.js → chunk-USX4L64H.js} +83 -146
  103. package/dist/chunk-USX4L64H.js.map +1 -0
  104. package/dist/chunk-V3HWDUN7.js +6 -0
  105. package/dist/chunk-V3HWDUN7.js.map +1 -0
  106. package/dist/chunk-WGU72NH4.js +14 -0
  107. package/dist/chunk-WGU72NH4.js.map +1 -0
  108. package/dist/chunk-XN3FKMO6.js +97 -0
  109. package/dist/chunk-XN3FKMO6.js.map +1 -0
  110. package/dist/chunk-YEOQZ6LM.js +3 -0
  111. package/dist/chunk-YEOQZ6LM.js.map +1 -0
  112. package/dist/chunk-YIUDHDPS.cjs +351 -0
  113. package/dist/chunk-YIUDHDPS.cjs.map +1 -0
  114. package/dist/default-u_dwuiYb-BOJNVDPF.js +3 -0
  115. package/dist/default-u_dwuiYb-BOJNVDPF.js.map +1 -0
  116. package/dist/default-u_dwuiYb-HYOFMURU.cjs +9 -0
  117. package/dist/default-u_dwuiYb-HYOFMURU.cjs.map +1 -0
  118. package/dist/deploy/log.d.ts +1 -1
  119. package/dist/deploy/log.d.ts.map +1 -1
  120. package/dist/docs/SKILL.md +31 -0
  121. package/dist/docs/assets/SOURCE_MAP.json +27 -0
  122. package/dist/docs/references/docs-deployment-cloud-providers.md +15 -0
  123. package/dist/docs/references/docs-deployment-mastra-server.md +122 -0
  124. package/dist/docs/references/docs-deployment-monorepo.md +142 -0
  125. package/dist/docs/references/docs-deployment-overview.md +62 -0
  126. package/dist/docs/references/docs-deployment-web-framework.md +52 -0
  127. package/dist/docs/references/docs-deployment-workflow-runners.md +9 -0
  128. package/dist/docs/references/reference-deployer.md +100 -0
  129. package/dist/effect-QlVUlMFu-FWNF43NY.cjs +17 -0
  130. package/dist/effect-QlVUlMFu-FWNF43NY.cjs.map +1 -0
  131. package/dist/effect-QlVUlMFu-UDX7FFQO.js +15 -0
  132. package/dist/effect-QlVUlMFu-UDX7FFQO.js.map +1 -0
  133. package/dist/esm-6PM2YB3Y.cjs +1336 -0
  134. package/dist/esm-6PM2YB3Y.cjs.map +1 -0
  135. package/dist/esm-CAB7GAHT.js +1289 -0
  136. package/dist/esm-CAB7GAHT.js.map +1 -0
  137. package/dist/index.cjs +11 -22
  138. package/dist/index.cjs.map +1 -1
  139. package/dist/index.js +5 -16
  140. package/dist/index.js.map +1 -1
  141. package/dist/server/handlers/a2a.d.ts +1 -1
  142. package/dist/server/handlers/health.d.ts +5 -0
  143. package/dist/server/handlers/health.d.ts.map +1 -0
  144. package/dist/server/handlers/restart-active-runs.d.ts +3 -0
  145. package/dist/server/handlers/restart-active-runs.d.ts.map +1 -0
  146. package/dist/server/handlers/utils/query-parsers.d.ts +15 -0
  147. package/dist/server/handlers/utils/query-parsers.d.ts.map +1 -1
  148. package/dist/server/handlers/utils.d.ts +0 -7
  149. package/dist/server/handlers/utils.d.ts.map +1 -1
  150. package/dist/server/index.cjs +2983 -10849
  151. package/dist/server/index.cjs.map +1 -1
  152. package/dist/server/index.d.ts +3 -12
  153. package/dist/server/index.d.ts.map +1 -1
  154. package/dist/server/index.js +2983 -10850
  155. package/dist/server/index.js.map +1 -1
  156. package/dist/server/types.d.ts +1 -1
  157. package/dist/server/types.d.ts.map +1 -1
  158. package/dist/server/welcome.d.ts +1 -1
  159. package/dist/server/welcome.d.ts.map +1 -1
  160. package/dist/services/index.cjs +4 -4
  161. package/dist/services/index.js +1 -1
  162. package/dist/sury-CWZTCd75-2U3FQUNZ.cjs +17 -0
  163. package/dist/sury-CWZTCd75-2U3FQUNZ.cjs.map +1 -0
  164. package/dist/sury-CWZTCd75-52HHC6OD.js +15 -0
  165. package/dist/sury-CWZTCd75-52HHC6OD.js.map +1 -0
  166. package/dist/typebox-Dei93FPO-EBJ4ULZC.cjs +10 -0
  167. package/dist/typebox-Dei93FPO-EBJ4ULZC.cjs.map +1 -0
  168. package/dist/typebox-Dei93FPO-TURR2FV5.js +8 -0
  169. package/dist/typebox-Dei93FPO-TURR2FV5.js.map +1 -0
  170. package/dist/valibot--1zFm7rT-KH26NMFX.cjs +17 -0
  171. package/dist/valibot--1zFm7rT-KH26NMFX.cjs.map +1 -0
  172. package/dist/valibot--1zFm7rT-O4VBDBTD.js +15 -0
  173. package/dist/valibot--1zFm7rT-O4VBDBTD.js.map +1 -0
  174. package/dist/valibot-D_HTw1Gn-EVIH6VOI.js +43 -0
  175. package/dist/valibot-D_HTw1Gn-EVIH6VOI.js.map +1 -0
  176. package/dist/valibot-D_HTw1Gn-YHTB53Q2.cjs +45 -0
  177. package/dist/valibot-D_HTw1Gn-YHTB53Q2.cjs.map +1 -0
  178. package/dist/validator/custom-resolver.cjs +46 -12
  179. package/dist/validator/custom-resolver.cjs.map +1 -1
  180. package/dist/validator/custom-resolver.d.ts +15 -1
  181. package/dist/validator/custom-resolver.d.ts.map +1 -1
  182. package/dist/validator/custom-resolver.js +44 -11
  183. package/dist/validator/custom-resolver.js.map +1 -1
  184. package/dist/validator/validate.d.ts +16 -1
  185. package/dist/validator/validate.d.ts.map +1 -1
  186. package/dist/zod-Bwrt9trS-SFESLKHY.cjs +31 -0
  187. package/dist/zod-Bwrt9trS-SFESLKHY.cjs.map +1 -0
  188. package/dist/zod-Bwrt9trS-UDJPKIQS.js +29 -0
  189. package/dist/zod-Bwrt9trS-UDJPKIQS.js.map +1 -0
  190. package/dist/zod-DSgpEGAE-3CP5FXLX.cjs +39 -0
  191. package/dist/zod-DSgpEGAE-3CP5FXLX.cjs.map +1 -0
  192. package/dist/zod-DSgpEGAE-EQI5QBJK.js +37 -0
  193. package/dist/zod-DSgpEGAE-EQI5QBJK.js.map +1 -0
  194. package/package.json +34 -35
  195. package/dist/build/babel/get-deployer.d.ts +0 -3
  196. package/dist/build/babel/get-deployer.d.ts.map +0 -1
  197. package/dist/build/babel/remove-all-options-bundler.d.ts +0 -5
  198. package/dist/build/babel/remove-all-options-bundler.d.ts.map +0 -1
  199. package/dist/build/babel/remove-all-options-deployer.d.ts +0 -5
  200. package/dist/build/babel/remove-all-options-deployer.d.ts.map +0 -1
  201. package/dist/build/babel/remove-all-options-server.d.ts +0 -5
  202. package/dist/build/babel/remove-all-options-server.d.ts.map +0 -1
  203. package/dist/build/babel/remove-all-options-telemetry.d.ts +0 -5
  204. package/dist/build/babel/remove-all-options-telemetry.d.ts.map +0 -1
  205. package/dist/build/customInstrumentation.d.ts +0 -10
  206. package/dist/build/customInstrumentation.d.ts.map +0 -1
  207. package/dist/build/telemetry.d.ts +0 -8
  208. package/dist/build/telemetry.d.ts.map +0 -1
  209. package/dist/chunk-3JYRSECU.cjs.map +0 -1
  210. package/dist/chunk-465ZVXAK.js.map +0 -1
  211. package/dist/chunk-5QFG6SCM.js.map +0 -1
  212. package/dist/chunk-CEXVMFUD.js +0 -1265
  213. package/dist/chunk-CEXVMFUD.js.map +0 -1
  214. package/dist/chunk-CKUCDCGI.js +0 -168
  215. package/dist/chunk-CKUCDCGI.js.map +0 -1
  216. package/dist/chunk-HMMDNIEQ.cjs.map +0 -1
  217. package/dist/chunk-LGC3GUMR.cjs.map +0 -1
  218. package/dist/chunk-MCDDO4WY.cjs +0 -1309
  219. package/dist/chunk-MCDDO4WY.cjs.map +0 -1
  220. package/dist/chunk-OYO2MJED.cjs +0 -195
  221. package/dist/chunk-OYO2MJED.cjs.map +0 -1
  222. package/dist/chunk-SBTEIZ3B.js +0 -26
  223. package/dist/chunk-SBTEIZ3B.js.map +0 -1
  224. package/dist/chunk-WAWEQ3DP.js.map +0 -1
  225. package/dist/chunk-WIQEFIRX.cjs +0 -28
  226. package/dist/chunk-WIQEFIRX.cjs.map +0 -1
  227. package/dist/server/handlers/auth/defaults.d.ts +0 -3
  228. package/dist/server/handlers/auth/defaults.d.ts.map +0 -1
  229. package/dist/server/handlers/auth/helpers.d.ts +0 -11
  230. package/dist/server/handlers/auth/helpers.d.ts.map +0 -1
  231. package/dist/server/handlers/auth/index.d.ts +0 -11
  232. package/dist/server/handlers/auth/index.d.ts.map +0 -1
  233. package/dist/server/handlers/prompt.d.ts +0 -3
  234. package/dist/server/handlers/prompt.d.ts.map +0 -1
  235. package/dist/server/handlers/routes/agent-builder/handlers.d.ts +0 -17
  236. package/dist/server/handlers/routes/agent-builder/handlers.d.ts.map +0 -1
  237. package/dist/server/handlers/routes/agent-builder/router.d.ts +0 -4
  238. package/dist/server/handlers/routes/agent-builder/router.d.ts.map +0 -1
  239. package/dist/server/handlers/routes/agents/handlers.d.ts +0 -363
  240. package/dist/server/handlers/routes/agents/handlers.d.ts.map +0 -1
  241. package/dist/server/handlers/routes/agents/router.d.ts +0 -5
  242. package/dist/server/handlers/routes/agents/router.d.ts.map +0 -1
  243. package/dist/server/handlers/routes/agents/voice.d.ts +0 -18
  244. package/dist/server/handlers/routes/agents/voice.d.ts.map +0 -1
  245. package/dist/server/handlers/routes/logs/handlers.d.ts +0 -5
  246. package/dist/server/handlers/routes/logs/handlers.d.ts.map +0 -1
  247. package/dist/server/handlers/routes/logs/router.d.ts +0 -3
  248. package/dist/server/handlers/routes/logs/router.d.ts.map +0 -1
  249. package/dist/server/handlers/routes/mcp/handlers.d.ts +0 -139
  250. package/dist/server/handlers/routes/mcp/handlers.d.ts.map +0 -1
  251. package/dist/server/handlers/routes/mcp/router.d.ts +0 -4
  252. package/dist/server/handlers/routes/mcp/router.d.ts.map +0 -1
  253. package/dist/server/handlers/routes/memory/handlers.d.ts +0 -17
  254. package/dist/server/handlers/routes/memory/handlers.d.ts.map +0 -1
  255. package/dist/server/handlers/routes/memory/router.d.ts +0 -4
  256. package/dist/server/handlers/routes/memory/router.d.ts.map +0 -1
  257. package/dist/server/handlers/routes/observability/handlers.d.ts +0 -6
  258. package/dist/server/handlers/routes/observability/handlers.d.ts.map +0 -1
  259. package/dist/server/handlers/routes/observability/router.d.ts +0 -3
  260. package/dist/server/handlers/routes/observability/router.d.ts.map +0 -1
  261. package/dist/server/handlers/routes/scores/handlers.d.ts +0 -300
  262. package/dist/server/handlers/routes/scores/handlers.d.ts.map +0 -1
  263. package/dist/server/handlers/routes/scores/router.d.ts +0 -4
  264. package/dist/server/handlers/routes/scores/router.d.ts.map +0 -1
  265. package/dist/server/handlers/routes/telemetry/handlers.d.ts +0 -4
  266. package/dist/server/handlers/routes/telemetry/handlers.d.ts.map +0 -1
  267. package/dist/server/handlers/routes/telemetry/router.d.ts +0 -3
  268. package/dist/server/handlers/routes/telemetry/router.d.ts.map +0 -1
  269. package/dist/server/handlers/routes/tools/handlers.d.ts +0 -7
  270. package/dist/server/handlers/routes/tools/handlers.d.ts.map +0 -1
  271. package/dist/server/handlers/routes/tools/router.d.ts +0 -4
  272. package/dist/server/handlers/routes/tools/router.d.ts.map +0 -1
  273. package/dist/server/handlers/routes/vector/handlers.d.ts +0 -10
  274. package/dist/server/handlers/routes/vector/handlers.d.ts.map +0 -1
  275. package/dist/server/handlers/routes/vector/router.d.ts +0 -4
  276. package/dist/server/handlers/routes/vector/router.d.ts.map +0 -1
  277. package/dist/server/handlers/routes/workflows/handlers.d.ts +0 -20
  278. package/dist/server/handlers/routes/workflows/handlers.d.ts.map +0 -1
  279. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts +0 -11
  280. package/dist/server/handlers/routes/workflows/legacyWorkflows.d.ts.map +0 -1
  281. package/dist/server/handlers/routes/workflows/router.d.ts +0 -4
  282. package/dist/server/handlers/routes/workflows/router.d.ts.map +0 -1
  283. package/dist/templates/instrumentation-template.js +0 -172
@@ -0,0 +1,1322 @@
1
+ import { tsConfigPaths, esbuild, removeDeployer, getPackageRootPath, subpathExternalsResolver, esmShim } from './chunk-ANF3UFZ3.js';
2
+ import { slash, isDependencyPartOfPackage, getPackageName, isBuiltinModule, getCompiledDepCachePath, rollupSafeName, getNodeResolveOptions } from './chunk-XN3FKMO6.js';
3
+ import { existsSync } from 'fs';
4
+ import { readFile, writeFile } from 'fs/promises';
5
+ import * as path from 'path';
6
+ import { dirname, join, relative, basename as basename$1 } from 'path';
7
+ import * as babel from '@babel/core';
8
+ import babel__default from '@babel/core';
9
+ import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
10
+ import * as pkg from 'empathic/package';
11
+ import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
12
+ import { spawn as spawn$1 } from 'child_process';
13
+ import { fileURLToPath, pathToFileURL } from 'url';
14
+ import { noopLogger } from '@mastra/core/logger';
15
+ import commonjs from '@rollup/plugin-commonjs';
16
+ import json from '@rollup/plugin-json';
17
+ import virtual from '@rollup/plugin-virtual';
18
+ import { readJSON } from 'fs-extra/esm';
19
+ import { resolveModule, getPackageInfo } from 'local-pkg';
20
+ import { rollup } from 'rollup';
21
+ import { builtinModules } from 'module';
22
+ import { basename } from 'path/posix';
23
+ import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
24
+ import nodeResolve from '@rollup/plugin-node-resolve';
25
+ import * as resolve from 'resolve.exports';
26
+
27
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
28
+ var UNKNOWN_FUNCTION = "<unknown>";
29
+ function parse(stackString) {
30
+ var lines = stackString.split("\n");
31
+ return lines.reduce(function(stack, line) {
32
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
33
+ if (parseResult) {
34
+ stack.push(parseResult);
35
+ }
36
+ return stack;
37
+ }, []);
38
+ }
39
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
40
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
41
+ function parseChrome(line) {
42
+ var parts = chromeRe.exec(line);
43
+ if (!parts) {
44
+ return null;
45
+ }
46
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
47
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
48
+ var submatch = chromeEvalRe.exec(parts[2]);
49
+ if (isEval && submatch != null) {
50
+ parts[2] = submatch[1];
51
+ parts[3] = submatch[2];
52
+ parts[4] = submatch[3];
53
+ }
54
+ return {
55
+ file: !isNative ? parts[2] : null,
56
+ methodName: parts[1] || UNKNOWN_FUNCTION,
57
+ arguments: isNative ? [parts[2]] : [],
58
+ lineNumber: parts[3] ? +parts[3] : null,
59
+ column: parts[4] ? +parts[4] : null
60
+ };
61
+ }
62
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
63
+ function parseWinjs(line) {
64
+ var parts = winjsRe.exec(line);
65
+ if (!parts) {
66
+ return null;
67
+ }
68
+ return {
69
+ file: parts[2],
70
+ methodName: parts[1] || UNKNOWN_FUNCTION,
71
+ arguments: [],
72
+ lineNumber: +parts[3],
73
+ column: parts[4] ? +parts[4] : null
74
+ };
75
+ }
76
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
77
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
78
+ function parseGecko(line) {
79
+ var parts = geckoRe.exec(line);
80
+ if (!parts) {
81
+ return null;
82
+ }
83
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
84
+ var submatch = geckoEvalRe.exec(parts[3]);
85
+ if (isEval && submatch != null) {
86
+ parts[3] = submatch[1];
87
+ parts[4] = submatch[2];
88
+ parts[5] = null;
89
+ }
90
+ return {
91
+ file: parts[3],
92
+ methodName: parts[1] || UNKNOWN_FUNCTION,
93
+ arguments: parts[2] ? parts[2].split(",") : [],
94
+ lineNumber: parts[4] ? +parts[4] : null,
95
+ column: parts[5] ? +parts[5] : null
96
+ };
97
+ }
98
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
99
+ function parseJSC(line) {
100
+ var parts = javaScriptCoreRe.exec(line);
101
+ if (!parts) {
102
+ return null;
103
+ }
104
+ return {
105
+ file: parts[3],
106
+ methodName: parts[1] || UNKNOWN_FUNCTION,
107
+ arguments: [],
108
+ lineNumber: +parts[4],
109
+ column: parts[5] ? +parts[5] : null
110
+ };
111
+ }
112
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
113
+ function parseNode(line) {
114
+ var parts = nodeRe.exec(line);
115
+ if (!parts) {
116
+ return null;
117
+ }
118
+ return {
119
+ file: parts[2],
120
+ methodName: parts[1] || UNKNOWN_FUNCTION,
121
+ arguments: [],
122
+ lineNumber: +parts[3],
123
+ column: parts[4] ? +parts[4] : null
124
+ };
125
+ }
126
+ var workspacesCache = createWorkspacesCache();
127
+ async function getWorkspaceInformation({
128
+ dir = process.cwd(),
129
+ mastraEntryFile
130
+ }) {
131
+ const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });
132
+ const location = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());
133
+ const workspaces = await findWorkspaces(dir, { cache: workspacesCache });
134
+ const _workspaceMap = new Map(
135
+ workspaces?.map((workspace) => [
136
+ workspace.package.name,
137
+ {
138
+ location: workspace.location,
139
+ dependencies: workspace.package.dependencies,
140
+ version: workspace.package.version
141
+ }
142
+ ]) ?? []
143
+ );
144
+ const isWorkspacePackage = (workspaces ?? []).some((ws) => ws.location === location);
145
+ const workspaceRoot = isWorkspacePackage ? findWorkspacesRoot(dir, { cache: workspacesCache })?.location : void 0;
146
+ return {
147
+ // If the current package is not part of the workspace, the bundling down the line shouldn't look at any workspace packages
148
+ workspaceMap: isWorkspacePackage ? _workspaceMap : /* @__PURE__ */ new Map(),
149
+ workspaceRoot,
150
+ isWorkspacePackage
151
+ };
152
+ }
153
+ var ValidationError = class extends Error {
154
+ type;
155
+ stack;
156
+ constructor(args) {
157
+ super(args.message);
158
+ this.type = args.type;
159
+ this.stack = args.stack;
160
+ }
161
+ };
162
+ function spawn(command, args = [], options = {}) {
163
+ return new Promise((resolve2, reject) => {
164
+ let validationError = null;
165
+ const childProcess = spawn$1(command, args, {
166
+ // stdio: 'inherit',
167
+ ...options
168
+ });
169
+ childProcess.on("error", (error) => {
170
+ reject(error);
171
+ });
172
+ let stderr = "";
173
+ childProcess.stderr?.on("data", (message) => {
174
+ try {
175
+ validationError = JSON.parse(message.toString());
176
+ } catch {
177
+ stderr += message;
178
+ }
179
+ });
180
+ childProcess.on("close", (code) => {
181
+ if (code === 0) {
182
+ resolve2();
183
+ } else {
184
+ if (validationError) {
185
+ reject(new ValidationError(validationError));
186
+ } else {
187
+ reject(new Error(stderr));
188
+ }
189
+ }
190
+ });
191
+ });
192
+ }
193
+ function validate(file, {
194
+ injectESMShim = false,
195
+ moduleResolveMapLocation,
196
+ stubbedExternals = []
197
+ }) {
198
+ let prefixCode = "";
199
+ if (injectESMShim) {
200
+ prefixCode = `import { fileURLToPath } from 'url';
201
+ import { dirname } from 'path';
202
+
203
+ globalThis.__filename = fileURLToPath(import.meta.url);
204
+ globalThis.__dirname = dirname(__filename);
205
+ `;
206
+ }
207
+ function errorHandler(err) {
208
+ console.error(
209
+ JSON.stringify({
210
+ type: err.name,
211
+ message: err.message,
212
+ stack: err.stack
213
+ })
214
+ );
215
+ process.exit(1);
216
+ }
217
+ return spawn(
218
+ process.execPath,
219
+ [
220
+ "--import",
221
+ import.meta.resolve("@mastra/deployer/loader"),
222
+ "--input-type=module",
223
+ "--enable-source-maps",
224
+ "-e",
225
+ `${prefixCode};import('${pathToFileURL(file).href}').catch(err => {
226
+ ${errorHandler.toString()}
227
+ errorHandler(err);
228
+ })`.replaceAll(/\n/g, "")
229
+ ],
230
+ {
231
+ env: {
232
+ ...process.env,
233
+ MODULE_MAP: `${moduleResolveMapLocation}`,
234
+ STUBBED_EXTERNALS: JSON.stringify(stubbedExternals)
235
+ },
236
+ cwd: dirname(file)
237
+ }
238
+ );
239
+ }
240
+ function isNodeBuiltin(dep) {
241
+ const [pkg2] = dep.split("/");
242
+ return dep.startsWith("node:") || builtinModules.includes(dep) || builtinModules.includes(pkg2);
243
+ }
244
+
245
+ // src/build/analyze/constants.ts
246
+ var DEPS_TO_IGNORE = ["#tools", "execa"];
247
+ var GLOBAL_EXTERNALS = [
248
+ "pino",
249
+ "pino-pretty",
250
+ "@libsql/client",
251
+ "pg",
252
+ "libsql",
253
+ "#tools",
254
+ "typescript",
255
+ "undici",
256
+ "readable-stream",
257
+ "bufferutil",
258
+ "utf-8-validate",
259
+ "execa"
260
+ ];
261
+ var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
262
+
263
+ // src/build/analyze/analyzeEntry.ts
264
+ function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
265
+ const normalizedMastraEntry = slash(mastraEntry);
266
+ let virtualPlugin = null;
267
+ if (isVirtualFile) {
268
+ virtualPlugin = virtual({
269
+ "#entry": entry
270
+ });
271
+ entry = "#entry";
272
+ }
273
+ const plugins = [];
274
+ if (virtualPlugin) {
275
+ plugins.push(virtualPlugin);
276
+ }
277
+ plugins.push(
278
+ ...[
279
+ tsConfigPaths(),
280
+ {
281
+ name: "custom-alias-resolver",
282
+ resolveId(id) {
283
+ if (id === "#server") {
284
+ return slash(fileURLToPath(import.meta.resolve("@mastra/deployer/server")));
285
+ }
286
+ if (id === "#mastra") {
287
+ return normalizedMastraEntry;
288
+ }
289
+ if (id.startsWith("@mastra/server")) {
290
+ return fileURLToPath(import.meta.resolve(id));
291
+ }
292
+ }
293
+ },
294
+ json(),
295
+ esbuild(),
296
+ commonjs({
297
+ strictRequires: "debug",
298
+ ignoreTryCatch: false,
299
+ transformMixedEsModules: true,
300
+ extensions: [".js", ".ts"]
301
+ }),
302
+ removeDeployer(mastraEntry, {
303
+ sourcemap: sourcemapEnabled
304
+ }),
305
+ esbuild()
306
+ ]
307
+ );
308
+ return plugins;
309
+ }
310
+ async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, initialDepsToOptimize, {
311
+ logger,
312
+ shouldCheckTransitiveDependencies
313
+ }) {
314
+ const depsToOptimize = /* @__PURE__ */ new Map();
315
+ if (!output.facadeModuleId) {
316
+ throw new Error(
317
+ "Something went wrong, we could not find the package name of the entry file. Please open an issue."
318
+ );
319
+ }
320
+ let entryRootPath = projectRoot;
321
+ if (!output.facadeModuleId.startsWith("\0virtual:")) {
322
+ entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
323
+ }
324
+ for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
325
+ if (isNodeBuiltin(dependency) || dependency.startsWith("#")) {
326
+ continue;
327
+ }
328
+ const pkgName = getPackageName(dependency);
329
+ let rootPath = null;
330
+ let isWorkspace = false;
331
+ let version;
332
+ if (pkgName) {
333
+ rootPath = await getPackageRootPath(dependency, entryRootPath);
334
+ isWorkspace = workspaceMap.has(pkgName);
335
+ if (rootPath) {
336
+ try {
337
+ const pkgJson = await readJSON(`${rootPath}/package.json`);
338
+ version = pkgJson.version;
339
+ } catch {
340
+ }
341
+ }
342
+ }
343
+ const normalizedRootPath = rootPath ? slash(rootPath) : null;
344
+ depsToOptimize.set(dependency, {
345
+ exports: bindings,
346
+ rootPath: normalizedRootPath,
347
+ isWorkspace,
348
+ version
349
+ });
350
+ }
351
+ async function checkTransitiveDependencies(internalMap, maxDepth = 10, currentDepth = 0) {
352
+ if (currentDepth >= maxDepth) {
353
+ logger.warn("Maximum dependency depth reached while checking transitive dependencies.");
354
+ return;
355
+ }
356
+ const depsSnapshot = new Map(depsToOptimize);
357
+ let hasAddedDeps = false;
358
+ for (const [dep, meta] of depsSnapshot) {
359
+ if (!meta.isWorkspace || internalMap.has(dep)) {
360
+ continue;
361
+ }
362
+ try {
363
+ const importerPath = output.facadeModuleId ? pathToFileURL(output.facadeModuleId).href : pathToFileURL(projectRoot).href;
364
+ const resolvedPath = resolveModule(dep, {
365
+ paths: [importerPath]
366
+ });
367
+ if (!resolvedPath) {
368
+ logger.warn(`Could not resolve path for workspace dependency ${dep}`);
369
+ continue;
370
+ }
371
+ const analysis = await analyzeEntry({ entry: resolvedPath, isVirtualFile: false }, "", {
372
+ workspaceMap,
373
+ projectRoot,
374
+ logger: noopLogger,
375
+ sourcemapEnabled: false,
376
+ initialDepsToOptimize: depsToOptimize
377
+ });
378
+ if (!analysis?.dependencies) {
379
+ continue;
380
+ }
381
+ for (const [innerDep, innerMeta] of analysis.dependencies) {
382
+ if (innerMeta.isWorkspace && !internalMap.has(innerDep) && !depsToOptimize.has(innerDep)) {
383
+ depsToOptimize.set(innerDep, innerMeta);
384
+ internalMap.set(innerDep, innerMeta);
385
+ hasAddedDeps = true;
386
+ }
387
+ }
388
+ } catch (err) {
389
+ logger.error(`Failed to resolve or analyze dependency ${dep}: ${err.message}`);
390
+ }
391
+ }
392
+ if (hasAddedDeps) {
393
+ await checkTransitiveDependencies(internalMap, maxDepth, currentDepth + 1);
394
+ }
395
+ }
396
+ if (shouldCheckTransitiveDependencies) {
397
+ await checkTransitiveDependencies(initialDepsToOptimize);
398
+ }
399
+ const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
400
+ if (dynamicImports.length) {
401
+ for (const dynamicImport of dynamicImports) {
402
+ if (!depsToOptimize.has(dynamicImport) && !isNodeBuiltin(dynamicImport)) {
403
+ const pkgName = getPackageName(dynamicImport);
404
+ let version;
405
+ let rootPath = null;
406
+ if (pkgName) {
407
+ rootPath = await getPackageRootPath(dynamicImport, entryRootPath);
408
+ if (rootPath) {
409
+ try {
410
+ const pkgJson = await readJSON(`${rootPath}/package.json`);
411
+ version = pkgJson.version;
412
+ } catch {
413
+ }
414
+ }
415
+ }
416
+ depsToOptimize.set(dynamicImport, {
417
+ exports: ["*"],
418
+ rootPath: rootPath ? slash(rootPath) : null,
419
+ isWorkspace: false,
420
+ version
421
+ });
422
+ }
423
+ }
424
+ }
425
+ return depsToOptimize;
426
+ }
427
+ async function analyzeEntry({
428
+ entry,
429
+ isVirtualFile
430
+ }, mastraEntry, {
431
+ logger,
432
+ sourcemapEnabled,
433
+ workspaceMap,
434
+ projectRoot,
435
+ initialDepsToOptimize = /* @__PURE__ */ new Map(),
436
+ // used to avoid infinite recursion
437
+ shouldCheckTransitiveDependencies = false
438
+ }) {
439
+ const optimizerBundler = await rollup({
440
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
441
+ input: isVirtualFile ? "#entry" : entry,
442
+ treeshake: false,
443
+ preserveSymlinks: true,
444
+ plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
445
+ external: DEPS_TO_IGNORE
446
+ });
447
+ const { output } = await optimizerBundler.generate({
448
+ format: "esm",
449
+ inlineDynamicImports: true
450
+ });
451
+ await optimizerBundler.close();
452
+ const depsToOptimize = await captureDependenciesToOptimize(
453
+ output[0],
454
+ workspaceMap,
455
+ projectRoot,
456
+ initialDepsToOptimize,
457
+ {
458
+ logger,
459
+ shouldCheckTransitiveDependencies
460
+ }
461
+ );
462
+ return {
463
+ dependencies: depsToOptimize,
464
+ output: {
465
+ code: output[0].code,
466
+ map: output[0].map
467
+ }
468
+ };
469
+ }
470
+ function aliasHono() {
471
+ return {
472
+ name: "hono-alias",
473
+ resolveId(id) {
474
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
475
+ return;
476
+ }
477
+ const path2 = import.meta.resolve(id);
478
+ return fileURLToPath(path2);
479
+ }
480
+ };
481
+ }
482
+ function moduleResolveMap(externals, projectRoot) {
483
+ const importMap = /* @__PURE__ */ new Map();
484
+ return {
485
+ name: "module-resolve-map",
486
+ moduleParsed(info) {
487
+ if (info.importedIds.length === 0 || !info.id) {
488
+ return;
489
+ }
490
+ for (const importedId of info.importedIds) {
491
+ for (const external of externals) {
492
+ if (isDependencyPartOfPackage(importedId, external)) {
493
+ importMap.set(external, info.id);
494
+ }
495
+ }
496
+ }
497
+ },
498
+ async generateBundle(options, bundle) {
499
+ const resolveMap = /* @__PURE__ */ new Map();
500
+ for (const [fileName, chunk] of Object.entries(bundle)) {
501
+ if (chunk.type === "chunk") {
502
+ for (const [external, resolvedFrom] of importMap) {
503
+ if (chunk.moduleIds.includes(resolvedFrom)) {
504
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
505
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
506
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
507
+ resolveMap.set(fullPath, innerMap);
508
+ }
509
+ }
510
+ }
511
+ }
512
+ const resolveMapJson = Object.fromEntries(
513
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
514
+ );
515
+ this.emitFile({
516
+ type: "asset",
517
+ name: "module-resolve-map.json",
518
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
519
+ });
520
+ }
521
+ };
522
+ }
523
+ function nodeGypDetector() {
524
+ const modulesToTrack = /* @__PURE__ */ new Set();
525
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
526
+ return {
527
+ name: "node-gyp-build-detector",
528
+ moduleParsed(info) {
529
+ if (!info.meta?.commonjs?.requires?.length) {
530
+ return;
531
+ }
532
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
533
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
534
+ );
535
+ if (!hasNodeGypBuild) {
536
+ return;
537
+ }
538
+ modulesToTrack.add(info.id);
539
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
540
+ },
541
+ async generateBundle(options, bundle) {
542
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
543
+ for (const [fileName, chunk] of Object.entries(bundle)) {
544
+ if (chunk.type === "chunk") {
545
+ for (const moduleId of chunk.moduleIds) {
546
+ if (modulesToTrackPackageInfo.has(moduleId)) {
547
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
548
+ if (!binaryMapByChunk.has(fileName)) {
549
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
550
+ }
551
+ if (pkgInfo?.packageJson?.name) {
552
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
553
+ }
554
+ }
555
+ }
556
+ }
557
+ }
558
+ const binaryMapJson = Object.fromEntries(
559
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
560
+ );
561
+ this.emitFile({
562
+ type: "asset",
563
+ name: "binary-map.json",
564
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
565
+ });
566
+ }
567
+ };
568
+ }
569
+
570
+ // src/build/analyze/bundleExternals.ts
571
+ function prepareEntryFileName(name, rootDir) {
572
+ return rollupSafeName(name, rootDir);
573
+ }
574
+ function createVirtualDependencies(depsToOptimize, {
575
+ projectRoot,
576
+ workspaceRoot,
577
+ outputDir,
578
+ bundlerOptions
579
+ }) {
580
+ const { isDev = false, externalsPreset = false } = bundlerOptions || {};
581
+ const fileNameToDependencyMap = /* @__PURE__ */ new Map();
582
+ const optimizedDependencyEntries = /* @__PURE__ */ new Map();
583
+ const rootDir = workspaceRoot || projectRoot;
584
+ for (const [dep, { exports: exports2 }] of depsToOptimize.entries()) {
585
+ const fileName = dep.replaceAll("/", "__");
586
+ const virtualFile = [];
587
+ const exportStringBuilder = [];
588
+ for (const local of exports2) {
589
+ if (local === "*") {
590
+ virtualFile.push(`export * from '${dep}';`);
591
+ continue;
592
+ } else if (local === "default") {
593
+ exportStringBuilder.push("default");
594
+ } else {
595
+ exportStringBuilder.push(local);
596
+ }
597
+ }
598
+ const chunks = [];
599
+ if (exportStringBuilder.length) {
600
+ chunks.push(`{ ${exportStringBuilder.join(", ")} }`);
601
+ }
602
+ if (chunks.length) {
603
+ virtualFile.push(`export ${chunks.join(", ")} from '${dep}';`);
604
+ }
605
+ let entryName = prepareEntryFileName(path.join(outputDir, fileName), rootDir);
606
+ fileNameToDependencyMap.set(entryName, dep);
607
+ optimizedDependencyEntries.set(dep, {
608
+ name: entryName,
609
+ virtual: virtualFile.join("\n")
610
+ });
611
+ }
612
+ if (isDev || externalsPreset) {
613
+ for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
614
+ if (!isWorkspace || !rootPath || !workspaceRoot) {
615
+ continue;
616
+ }
617
+ const currentDepPath = optimizedDependencyEntries.get(dep);
618
+ if (!currentDepPath) {
619
+ continue;
620
+ }
621
+ const fileName = basename(currentDepPath.name);
622
+ const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir);
623
+ fileNameToDependencyMap.set(entryName, dep);
624
+ optimizedDependencyEntries.set(dep, {
625
+ ...currentDepPath,
626
+ name: entryName
627
+ });
628
+ }
629
+ }
630
+ return { optimizedDependencyEntries, fileNameToDependencyMap };
631
+ }
632
+ async function getInputPlugins2(virtualDependencies, {
633
+ transpilePackages,
634
+ workspaceMap,
635
+ bundlerOptions,
636
+ rootDir,
637
+ externals,
638
+ platform
639
+ }) {
640
+ const transpilePackagesMap = /* @__PURE__ */ new Map();
641
+ for (const pkg2 of transpilePackages) {
642
+ const dir = await getPackageRootPath(pkg2);
643
+ if (dir) {
644
+ transpilePackagesMap.set(pkg2, slash(dir));
645
+ } else {
646
+ transpilePackagesMap.set(pkg2, workspaceMap.get(pkg2)?.location ?? pkg2);
647
+ }
648
+ }
649
+ return [
650
+ virtual(
651
+ Array.from(virtualDependencies.entries()).reduce(
652
+ (acc, [dep, virtualDep]) => {
653
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
654
+ return acc;
655
+ },
656
+ {}
657
+ )
658
+ ),
659
+ tsConfigPaths(),
660
+ subpathExternalsResolver(externals),
661
+ transpilePackagesMap.size ? esbuild({
662
+ format: "esm",
663
+ include: [
664
+ // Match files from transpilePackages by their actual directory paths
665
+ // but exclude any nested node_modules
666
+ ...[...transpilePackagesMap.values()].map((p) => {
667
+ if (path.isAbsolute(p)) {
668
+ return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
669
+ } else {
670
+ return new RegExp(`/${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
671
+ }
672
+ }),
673
+ // Also match workspace packages resolved through node_modules symlinks
674
+ // (common in pnpm workspaces). Match by package name in node_modules path.
675
+ ...[...transpilePackagesMap.keys()].map((pkgName) => {
676
+ const escapedPkgName = pkgName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
677
+ return new RegExp(`/node_modules/${escapedPkgName}/(?!.*node_modules).*$`);
678
+ })
679
+ ],
680
+ // Disable the default /node_modules/ exclusion from rollup-plugin-esbuild.
681
+ // In pnpm workspaces, nodeResolve resolves workspace packages through node_modules
682
+ // symlinks, so the resolved paths contain "node_modules". Without this, workspace
683
+ // package .ts files won't be transpiled even if they match the include patterns.
684
+ exclude: []
685
+ }) : null,
686
+ bundlerOptions.noBundling ? {
687
+ name: "alias-optimized-deps",
688
+ async resolveId(id, importer, options) {
689
+ if (!virtualDependencies.has(id)) {
690
+ return null;
691
+ }
692
+ const info = virtualDependencies.get(id);
693
+ const packageRootPath = path.join(rootDir, path.dirname(path.dirname(path.dirname(info.name))));
694
+ const pkgJsonBuffer = await readFile(path.join(packageRootPath, "package.json"), "utf-8");
695
+ const pkgJson = JSON.parse(pkgJsonBuffer);
696
+ if (!pkgJson) {
697
+ return null;
698
+ }
699
+ const pkgName = pkgJson.name || "";
700
+ let resolvedPath = resolve.exports(pkgJson, id.replace(pkgName, "."))?.[0];
701
+ if (!resolvedPath) {
702
+ resolvedPath = pkgJson.main ?? "index.js";
703
+ }
704
+ const resolved = await this.resolve(path.posix.join(packageRootPath, resolvedPath), importer, options);
705
+ return resolved;
706
+ }
707
+ } : null,
708
+ optimizeLodashImports({
709
+ include: "**/*.{js,ts,mjs,cjs}"
710
+ }),
711
+ commonjs({
712
+ strictRequires: "strict",
713
+ transformMixedEsModules: true,
714
+ ignoreTryCatch: false
715
+ }),
716
+ bundlerOptions.noBundling ? null : nodeResolve(getNodeResolveOptions(platform)),
717
+ bundlerOptions.noBundling ? esmShim() : null,
718
+ // hono is imported from deployer, so we need to resolve from here instead of the project root
719
+ aliasHono(),
720
+ json(),
721
+ nodeGypDetector(),
722
+ moduleResolveMap(externals, rootDir),
723
+ {
724
+ name: "not-found-resolver",
725
+ resolveId: {
726
+ order: "post",
727
+ async handler(id, importer) {
728
+ if (!importer) {
729
+ return null;
730
+ }
731
+ if (!id.endsWith(".node")) {
732
+ return null;
733
+ }
734
+ const pkgInfo = await getPackageInfo(importer);
735
+ const packageName = pkgInfo?.packageJson?.name || id;
736
+ throw new MastraBaseError({
737
+ id: "DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD",
738
+ domain: ErrorDomain.DEPLOYER,
739
+ category: ErrorCategory.USER,
740
+ details: {
741
+ importFile: importer,
742
+ packageName
743
+ },
744
+ text: `We found a possible binary dependency in your bundle. ${id} was not found when imported at ${importer}.
745
+
746
+ Please consider adding \`${packageName}\` to your externals, or updating this import to not end with ".node".
747
+
748
+ export const mastra = new Mastra({
749
+ bundler: {
750
+ externals: ["${packageName}"],
751
+ }
752
+ })`
753
+ });
754
+ }
755
+ }
756
+ }
757
+ ].filter(Boolean);
758
+ }
759
+ async function buildExternalDependencies(virtualDependencies, {
760
+ externals,
761
+ packagesToTranspile,
762
+ workspaceMap,
763
+ rootDir,
764
+ outputDir,
765
+ bundlerOptions,
766
+ platform
767
+ }) {
768
+ if (virtualDependencies.size === 0) {
769
+ return [];
770
+ }
771
+ const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;
772
+ const plugins = await getInputPlugins2(virtualDependencies, {
773
+ transpilePackages: packagesToTranspile,
774
+ workspaceMap,
775
+ bundlerOptions: {
776
+ noBundling
777
+ },
778
+ rootDir,
779
+ externals,
780
+ platform
781
+ });
782
+ const bundler = await rollup({
783
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
784
+ input: Array.from(virtualDependencies.entries()).reduce(
785
+ (acc, [dep, virtualDep]) => {
786
+ acc[virtualDep.name] = `#virtual-${dep}`;
787
+ return acc;
788
+ },
789
+ {}
790
+ ),
791
+ external: externals,
792
+ treeshake: noBundling ? false : "safest",
793
+ plugins
794
+ });
795
+ const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
796
+ const { output } = await bundler.write({
797
+ format: "esm",
798
+ dir: rootDir,
799
+ entryFileNames: "[name].mjs",
800
+ // used to get the filename of the actual error
801
+ sourcemap: true,
802
+ /**
803
+ * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
804
+ * So we want to write them to the `.mastra/output` folder as well.
805
+ */
806
+ chunkFileNames: (chunkInfo) => {
807
+ if (noBundling) {
808
+ const importedFromPackages = /* @__PURE__ */ new Set();
809
+ for (const moduleId of chunkInfo.moduleIds) {
810
+ const normalized = slash(moduleId);
811
+ for (const [pkgName, pkgInfo] of workspaceMap.entries()) {
812
+ const location = slash(pkgInfo.location);
813
+ if (normalized.startsWith(location)) {
814
+ importedFromPackages.add(pkgName);
815
+ break;
816
+ }
817
+ }
818
+ }
819
+ if (importedFromPackages.size > 1) {
820
+ throw new MastraBaseError({
821
+ id: "DEPLOYER_BUNDLE_EXTERNALS_SHARED_CHUNK",
822
+ domain: ErrorDomain.DEPLOYER,
823
+ category: ErrorCategory.USER,
824
+ details: {
825
+ chunkName: chunkInfo.name,
826
+ packages: JSON.stringify(Array.from(importedFromPackages))
827
+ },
828
+ text: `Please open an issue. We found a shared chunk "${chunkInfo.name}" used by multiple workspace packages: ${Array.from(importedFromPackages).join(", ")}.`
829
+ });
830
+ }
831
+ if (importedFromPackages.size === 1) {
832
+ const [pkgName] = importedFromPackages;
833
+ const workspaceLocation = workspaceMap.get(pkgName).location;
834
+ return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
835
+ }
836
+ }
837
+ return `${outputDirRelative}/[name].mjs`;
838
+ },
839
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
840
+ hoistTransitiveImports: false
841
+ });
842
+ await bundler.close();
843
+ return output;
844
+ }
845
+ function findExternalImporter(module, external, allOutputs) {
846
+ const capturedFiles = /* @__PURE__ */ new Set();
847
+ for (const id of module.imports) {
848
+ if (isDependencyPartOfPackage(id, external)) {
849
+ return module;
850
+ } else {
851
+ if (id.endsWith(".mjs")) {
852
+ capturedFiles.add(id);
853
+ }
854
+ }
855
+ }
856
+ for (const file of capturedFiles) {
857
+ const nextModule = allOutputs.find((o) => o.fileName === file);
858
+ if (nextModule) {
859
+ const importer = findExternalImporter(nextModule, external, allOutputs);
860
+ if (importer) {
861
+ return importer;
862
+ }
863
+ }
864
+ }
865
+ return null;
866
+ }
867
+ async function bundleExternals(depsToOptimize, outputDir, options) {
868
+ const {
869
+ workspaceRoot = null,
870
+ workspaceMap = /* @__PURE__ */ new Map(),
871
+ projectRoot = outputDir,
872
+ bundlerOptions = {},
873
+ platform = "node"
874
+ } = options;
875
+ const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
876
+ let externalsPreset = false;
877
+ if (customExternals === true) {
878
+ externalsPreset = true;
879
+ }
880
+ const externalsList = Array.isArray(customExternals) ? customExternals : [];
881
+ const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...externalsList];
882
+ const workspacePackagesNames = Array.from(workspaceMap.keys());
883
+ const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
884
+ const extractedExternals = /* @__PURE__ */ new Map();
885
+ if (externalsPreset) {
886
+ for (const [dep, metadata] of depsToOptimize.entries()) {
887
+ if (!metadata.isWorkspace) {
888
+ extractedExternals.set(dep, metadata.rootPath ?? dep);
889
+ depsToOptimize.delete(dep);
890
+ }
891
+ }
892
+ }
893
+ const { optimizedDependencyEntries, fileNameToDependencyMap } = createVirtualDependencies(depsToOptimize, {
894
+ workspaceRoot,
895
+ outputDir,
896
+ projectRoot,
897
+ bundlerOptions: {
898
+ isDev,
899
+ externalsPreset
900
+ }
901
+ });
902
+ const output = await buildExternalDependencies(optimizedDependencyEntries, {
903
+ externals: allExternals,
904
+ packagesToTranspile,
905
+ workspaceMap,
906
+ rootDir: workspaceRoot || projectRoot,
907
+ outputDir,
908
+ bundlerOptions: {
909
+ isDev,
910
+ externalsPreset
911
+ },
912
+ platform
913
+ });
914
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
915
+ const filteredChunks = output.filter((o) => o.type === "chunk");
916
+ for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
917
+ for (const external of allExternals) {
918
+ if (DEPS_TO_IGNORE.includes(external)) {
919
+ continue;
920
+ }
921
+ const importer = findExternalImporter(o, external, filteredChunks);
922
+ if (importer) {
923
+ const fullPath = path.join(workspaceRoot || projectRoot, importer.fileName);
924
+ let innerMap = moduleResolveMap2.get(fullPath);
925
+ if (!innerMap) {
926
+ innerMap = /* @__PURE__ */ new Map();
927
+ moduleResolveMap2.set(fullPath, innerMap);
928
+ }
929
+ if (importer.moduleIds.length) {
930
+ innerMap.set(
931
+ external,
932
+ importer.moduleIds[importer.moduleIds.length - 1]?.startsWith("\0virtual:#virtual") ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1]
933
+ );
934
+ }
935
+ }
936
+ }
937
+ }
938
+ const usedExternals = /* @__PURE__ */ Object.create(null);
939
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
940
+ const innerObj = /* @__PURE__ */ Object.create(null);
941
+ for (const [external, value] of innerMap) {
942
+ innerObj[external] = value;
943
+ }
944
+ usedExternals[fullPath] = innerObj;
945
+ }
946
+ if (extractedExternals.size > 0) {
947
+ const syntheticPath = path.join(workspaceRoot || projectRoot, "__externals__");
948
+ const externalsObj = /* @__PURE__ */ Object.create(null);
949
+ for (const [dep, rootPath] of extractedExternals) {
950
+ externalsObj[dep] = rootPath;
951
+ }
952
+ usedExternals[syntheticPath] = externalsObj;
953
+ }
954
+ return { output, fileNameToDependencyMap, usedExternals };
955
+ }
956
+ function checkConfigExport(result) {
957
+ const t = babel__default.types;
958
+ const mastraVars = /* @__PURE__ */ new Set();
959
+ return {
960
+ visitor: {
961
+ ExportNamedDeclaration(path2) {
962
+ const decl = path2.node.declaration;
963
+ if (t.isVariableDeclaration(decl)) {
964
+ const varDecl = decl.declarations[0];
965
+ if (t.isIdentifier(varDecl?.id, { name: "mastra" }) && t.isNewExpression(varDecl.init) && t.isIdentifier(varDecl.init.callee, { name: "Mastra" })) {
966
+ result.hasValidConfig = true;
967
+ }
968
+ }
969
+ if (Array.isArray(path2.node.specifiers)) {
970
+ for (const spec of path2.node.specifiers) {
971
+ if (t.isExportSpecifier(spec) && t.isIdentifier(spec.exported, { name: "mastra" }) && t.isIdentifier(spec.local) && mastraVars.has(spec.local.name)) {
972
+ result.hasValidConfig = true;
973
+ }
974
+ }
975
+ }
976
+ },
977
+ // For cases 2-4 we need to track whether those variables are assigned to `new Mastra()`
978
+ VariableDeclaration(path2) {
979
+ for (const decl of path2.node.declarations) {
980
+ if (t.isIdentifier(decl.id) && t.isNewExpression(decl.init) && t.isIdentifier(decl.init.callee, { name: "Mastra" })) {
981
+ mastraVars.add(decl.id.name);
982
+ }
983
+ }
984
+ }
985
+ }
986
+ };
987
+ }
988
+
989
+ // src/build/analyze.ts
990
+ function throwExternalDependencyError({
991
+ errorId,
992
+ moduleName,
993
+ packageName,
994
+ messagePrefix
995
+ }) {
996
+ throw new MastraError({
997
+ id: errorId,
998
+ domain: ErrorDomain.DEPLOYER,
999
+ category: ErrorCategory.USER,
1000
+ details: {
1001
+ importFile: moduleName,
1002
+ packageName
1003
+ },
1004
+ text: `${messagePrefix} \`${packageName}\` to your externals.
1005
+
1006
+ export const mastra = new Mastra({
1007
+ bundler: {
1008
+ externals: ["${packageName}"],
1009
+ }
1010
+ })`
1011
+ });
1012
+ }
1013
+ function getPackageNameFromBundledModuleName(moduleName) {
1014
+ if (moduleName.includes("__")) {
1015
+ return moduleName.replaceAll("__", "/");
1016
+ }
1017
+ const chunks = moduleName.split("-");
1018
+ if (!chunks.length) {
1019
+ return moduleName;
1020
+ }
1021
+ if (chunks[0]?.startsWith("@")) {
1022
+ return chunks.slice(0, 2).join("/");
1023
+ }
1024
+ return chunks[0];
1025
+ }
1026
+ function validateError(err, file, {
1027
+ binaryMapData,
1028
+ workspaceMap
1029
+ }) {
1030
+ let moduleName = null;
1031
+ let errorConfig = null;
1032
+ if (err instanceof ValidationError) {
1033
+ const parsedStack = parse(err.stack);
1034
+ if (err.type === "TypeError") {
1035
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1036
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1037
+ if (stacktraceFrame) {
1038
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1039
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1040
+ } else {
1041
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1042
+ }
1043
+ errorConfig = {
1044
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1045
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1046
+ };
1047
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1048
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1049
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1050
+ errorConfig = {
1051
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1052
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1053
+ };
1054
+ if (moduleName === parentModuleName) {
1055
+ return;
1056
+ }
1057
+ }
1058
+ }
1059
+ if (err.message.includes("No native build was found")) {
1060
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1061
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1062
+ errorConfig = {
1063
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1064
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1065
+ };
1066
+ }
1067
+ if (moduleName && workspaceMap.has(moduleName)) {
1068
+ throw new MastraError({
1069
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1070
+ domain: ErrorDomain.DEPLOYER,
1071
+ category: ErrorCategory.USER,
1072
+ details: {
1073
+ // importFile: moduleName,
1074
+ packageName: moduleName
1075
+ },
1076
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1077
+ Error: ${err.stack}`
1078
+ });
1079
+ }
1080
+ if (errorConfig && moduleName) {
1081
+ throwExternalDependencyError({
1082
+ errorId: errorConfig.id,
1083
+ moduleName,
1084
+ packageName: moduleName,
1085
+ messagePrefix: errorConfig.messagePrefix
1086
+ });
1087
+ }
1088
+ }
1089
+ async function validateFile(root, file, {
1090
+ binaryMapData,
1091
+ moduleResolveMapLocation,
1092
+ logger,
1093
+ workspaceMap,
1094
+ stubbedExternals
1095
+ }) {
1096
+ try {
1097
+ if (!file.isDynamicEntry && file.isEntry) {
1098
+ await validate(join(root, file.fileName), {
1099
+ moduleResolveMapLocation,
1100
+ injectESMShim: false,
1101
+ stubbedExternals
1102
+ });
1103
+ }
1104
+ } catch (err) {
1105
+ let errorToHandle = err;
1106
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1107
+ try {
1108
+ await validate(join(root, file.fileName), {
1109
+ moduleResolveMapLocation,
1110
+ injectESMShim: true,
1111
+ stubbedExternals
1112
+ });
1113
+ errorToHandle = null;
1114
+ } catch (err2) {
1115
+ errorToHandle = err2;
1116
+ }
1117
+ }
1118
+ if (errorToHandle instanceof Error) {
1119
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1120
+ }
1121
+ }
1122
+ }
1123
+ async function validateOutput({
1124
+ output,
1125
+ reverseVirtualReferenceMap,
1126
+ usedExternals,
1127
+ outputDir,
1128
+ projectRoot,
1129
+ workspaceMap,
1130
+ depsVersionInfo
1131
+ }, logger) {
1132
+ const result = {
1133
+ dependencies: /* @__PURE__ */ new Map(),
1134
+ externalDependencies: /* @__PURE__ */ new Map(),
1135
+ workspaceMap
1136
+ };
1137
+ for (const deps of Object.values(usedExternals)) {
1138
+ for (const dep of Object.keys(deps)) {
1139
+ const pkgName = getPackageName(dep);
1140
+ if (pkgName) {
1141
+ const versionInfo = depsVersionInfo.get(dep) || depsVersionInfo.get(pkgName) || {};
1142
+ result.externalDependencies.set(pkgName, versionInfo);
1143
+ }
1144
+ }
1145
+ }
1146
+ let binaryMapData = {};
1147
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1148
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1149
+ binaryMapData = JSON.parse(binaryMap);
1150
+ }
1151
+ for (const file of output) {
1152
+ if (file.type === "asset") {
1153
+ continue;
1154
+ }
1155
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1156
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1157
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1158
+ }
1159
+ await validateFile(projectRoot, file, {
1160
+ binaryMapData,
1161
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1162
+ logger,
1163
+ workspaceMap,
1164
+ stubbedExternals: [...GLOBAL_EXTERNALS, ...DEPS_TO_IGNORE]
1165
+ });
1166
+ }
1167
+ return result;
1168
+ }
1169
+ async function analyzeBundle(entries, mastraEntry, {
1170
+ outputDir,
1171
+ projectRoot,
1172
+ platform,
1173
+ isDev = false,
1174
+ bundlerOptions
1175
+ }, logger) {
1176
+ const mastraConfig = await readFile(mastraEntry, "utf-8");
1177
+ const mastraConfigResult = {
1178
+ hasValidConfig: false
1179
+ };
1180
+ await babel.transformAsync(mastraConfig, {
1181
+ filename: mastraEntry,
1182
+ presets: [import.meta.resolve("@babel/preset-typescript")],
1183
+ plugins: [checkConfigExport(mastraConfigResult)]
1184
+ });
1185
+ if (!mastraConfigResult.hasValidConfig) {
1186
+ logger.warn(`Invalid Mastra config. Please make sure that your entry file looks like this:
1187
+ export const mastra = new Mastra({
1188
+ // your options
1189
+ })
1190
+
1191
+ If you think your configuration is valid, please open an issue.`);
1192
+ }
1193
+ const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1194
+ let externalsPreset = false;
1195
+ const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
1196
+ if (bundlerOptions?.externals === true) {
1197
+ externalsPreset = true;
1198
+ }
1199
+ let index = 0;
1200
+ const depsToOptimize = /* @__PURE__ */ new Map();
1201
+ const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
1202
+ logger.info("Analyzing dependencies...");
1203
+ const allUsedExternals = /* @__PURE__ */ new Map();
1204
+ for (const entry of entries) {
1205
+ const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1206
+ const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1207
+ logger,
1208
+ sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,
1209
+ workspaceMap,
1210
+ projectRoot,
1211
+ shouldCheckTransitiveDependencies: isDev || externalsPreset
1212
+ });
1213
+ await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1214
+ for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1215
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1216
+ if (isPartOfExternals || externalsPreset && !metadata.isWorkspace) {
1217
+ const pkgName = getPackageName(dep);
1218
+ if (pkgName && !allUsedExternals.has(pkgName)) {
1219
+ allUsedExternals.set(pkgName, {
1220
+ version: metadata.version
1221
+ });
1222
+ }
1223
+ continue;
1224
+ }
1225
+ if (depsToOptimize.has(dep)) {
1226
+ const existingEntry = depsToOptimize.get(dep);
1227
+ depsToOptimize.set(dep, {
1228
+ ...existingEntry,
1229
+ exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...metadata.exports])]
1230
+ });
1231
+ } else {
1232
+ depsToOptimize.set(dep, metadata);
1233
+ }
1234
+ }
1235
+ }
1236
+ if (isDev || externalsPreset) {
1237
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1238
+ if (!metadata.isWorkspace) {
1239
+ depsToOptimize.delete(dep);
1240
+ }
1241
+ }
1242
+ }
1243
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1244
+ logger.info("Optimizing dependencies...");
1245
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1246
+ const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1247
+ bundlerOptions: {
1248
+ ...bundlerOptions,
1249
+ externals: bundlerOptions?.externals ?? allExternals,
1250
+ isDev
1251
+ },
1252
+ projectRoot,
1253
+ workspaceRoot,
1254
+ workspaceMap,
1255
+ platform
1256
+ });
1257
+ const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map(
1258
+ (pkgInfo) => slash(relative(workspaceRoot || projectRoot, pkgInfo.location))
1259
+ );
1260
+ const depsVersionInfo = /* @__PURE__ */ new Map();
1261
+ for (const [dep, metadata] of depsToOptimize.entries()) {
1262
+ const pkgName = getPackageName(dep);
1263
+ if (pkgName && metadata.version) {
1264
+ depsVersionInfo.set(pkgName, {
1265
+ version: metadata.version
1266
+ });
1267
+ }
1268
+ if (metadata.version) {
1269
+ depsVersionInfo.set(dep, {
1270
+ version: metadata.version
1271
+ });
1272
+ }
1273
+ }
1274
+ for (const o of output) {
1275
+ if (o.type === "asset") {
1276
+ continue;
1277
+ }
1278
+ for (const i of o.imports) {
1279
+ if (isBuiltinModule(i)) {
1280
+ continue;
1281
+ }
1282
+ if (i.startsWith(".") || i.startsWith("/")) {
1283
+ continue;
1284
+ }
1285
+ if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) {
1286
+ continue;
1287
+ }
1288
+ const pkgName = getPackageName(i);
1289
+ if (pkgName && !allUsedExternals.has(pkgName)) {
1290
+ const versionInfo = depsVersionInfo.get(i) || depsVersionInfo.get(pkgName) || {};
1291
+ allUsedExternals.set(pkgName, versionInfo);
1292
+ }
1293
+ }
1294
+ }
1295
+ const result = await validateOutput(
1296
+ {
1297
+ output,
1298
+ reverseVirtualReferenceMap: fileNameToDependencyMap,
1299
+ usedExternals,
1300
+ outputDir,
1301
+ projectRoot: workspaceRoot || projectRoot,
1302
+ workspaceMap,
1303
+ depsVersionInfo
1304
+ },
1305
+ logger
1306
+ );
1307
+ const mergedExternalDeps = new Map(result.externalDependencies);
1308
+ for (const [dep, info] of allUsedExternals) {
1309
+ const existing = mergedExternalDeps.get(dep);
1310
+ if (!existing || !existing.version && info.version) {
1311
+ mergedExternalDeps.set(dep, info);
1312
+ }
1313
+ }
1314
+ return {
1315
+ ...result,
1316
+ externalDependencies: mergedExternalDeps
1317
+ };
1318
+ }
1319
+
1320
+ export { aliasHono, analyzeBundle, getWorkspaceInformation };
1321
+ //# sourceMappingURL=chunk-6UIXBIO6.js.map
1322
+ //# sourceMappingURL=chunk-6UIXBIO6.js.map