@mastra/deployer 1.54.0-alpha.0 → 1.54.0-alpha.2

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 (211) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/analyze-C2q7jxbN.js +1308 -0
  3. package/dist/analyze-C2q7jxbN.js.map +1 -0
  4. package/dist/analyze-DhDZW9TS.cjs +1318 -0
  5. package/dist/analyze-DhDZW9TS.cjs.map +1 -0
  6. package/dist/arktype-aI7TBD0R-BsgjPZ4a.cjs +8 -0
  7. package/dist/arktype-aI7TBD0R-BsgjPZ4a.cjs.map +1 -0
  8. package/dist/arktype-aI7TBD0R-_UZl-wsH.js +8 -0
  9. package/dist/arktype-aI7TBD0R-_UZl-wsH.js.map +1 -0
  10. package/dist/build/analyze/constants.d.ts.map +1 -1
  11. package/dist/build/analyze.cjs +3 -12
  12. package/dist/build/analyze.js +2 -3
  13. package/dist/build/bundler.cjs +6 -24
  14. package/dist/build/bundler.js +2 -3
  15. package/dist/build/index.cjs +29 -101
  16. package/dist/build/index.js +7 -8
  17. package/dist/build-De4AZhfJ.cjs +908 -0
  18. package/dist/build-De4AZhfJ.cjs.map +1 -0
  19. package/dist/build-KCOeHd4N.js +834 -0
  20. package/dist/build-KCOeHd4N.js.map +1 -0
  21. package/dist/bundler/index.cjs +318 -13
  22. package/dist/bundler/index.cjs.map +1 -1
  23. package/dist/bundler/index.js +314 -2
  24. package/dist/bundler/index.js.map +1 -1
  25. package/dist/bundler-BqrDXofn.cjs +792 -0
  26. package/dist/bundler-BqrDXofn.cjs.map +1 -0
  27. package/dist/bundler-D86rFu2J.js +705 -0
  28. package/dist/bundler-D86rFu2J.js.map +1 -0
  29. package/dist/bundlerOptions-aFsEi86t.js +180 -0
  30. package/dist/bundlerOptions-aFsEi86t.js.map +1 -0
  31. package/dist/bundlerOptions-rBmtSyGe.cjs +194 -0
  32. package/dist/bundlerOptions-rBmtSyGe.cjs.map +1 -0
  33. package/dist/core-D0wEgdn3.cjs +790 -0
  34. package/dist/core-D0wEgdn3.cjs.map +1 -0
  35. package/dist/core-DF65PJXc.js +790 -0
  36. package/dist/core-DF65PJXc.js.map +1 -0
  37. package/dist/dist-BauTimif.js +532 -0
  38. package/dist/dist-BauTimif.js.map +1 -0
  39. package/dist/dist-Cv-mAEtr.cjs +532 -0
  40. package/dist/dist-Cv-mAEtr.cjs.map +1 -0
  41. package/dist/docs/SKILL.md +1 -1
  42. package/dist/docs/assets/SOURCE_MAP.json +2 -23
  43. package/dist/docs/references/docs-deployment-cloud-providers.md +1 -0
  44. package/dist/docs/references/docs-deployment-overview.md +1 -0
  45. package/dist/effect-QlVUlMFu-CwFnyS-g.cjs +14 -0
  46. package/dist/effect-QlVUlMFu-CwFnyS-g.cjs.map +1 -0
  47. package/dist/effect-QlVUlMFu-gyLQRCtQ.js +14 -0
  48. package/dist/effect-QlVUlMFu-gyLQRCtQ.js.map +1 -0
  49. package/dist/esm-BX-weMyC.js +4634 -0
  50. package/dist/esm-BX-weMyC.js.map +1 -0
  51. package/dist/esm-D81PZ_wJ.cjs +4634 -0
  52. package/dist/esm-D81PZ_wJ.cjs.map +1 -0
  53. package/dist/index-CLddUTqr-B5mOP6DC.cjs +145 -0
  54. package/dist/index-CLddUTqr-B5mOP6DC.cjs.map +1 -0
  55. package/dist/index-CLddUTqr-CkS6Y_hA.js +140 -0
  56. package/dist/index-CLddUTqr-CkS6Y_hA.js.map +1 -0
  57. package/dist/index.cjs +35 -48
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.js +29 -30
  60. package/dist/index.js.map +1 -1
  61. package/dist/rolldown-runtime-emK7D4bc.cjs +35 -0
  62. package/dist/server/index.cjs +3141 -3874
  63. package/dist/server/index.cjs.map +1 -1
  64. package/dist/server/index.d.ts.map +1 -1
  65. package/dist/server/index.js +3131 -3842
  66. package/dist/server/index.js.map +1 -1
  67. package/dist/server/types.d.ts +1 -0
  68. package/dist/server/types.d.ts.map +1 -1
  69. package/dist/services/index.cjs +5 -20
  70. package/dist/services/index.js +2 -3
  71. package/dist/services-BxYMLS9-.cjs +430 -0
  72. package/dist/services-BxYMLS9-.cjs.map +1 -0
  73. package/dist/services-CLi56qqe.js +391 -0
  74. package/dist/services-CLi56qqe.js.map +1 -0
  75. package/dist/sury-CWZTCd75-B85M6878.js +14 -0
  76. package/dist/sury-CWZTCd75-B85M6878.js.map +1 -0
  77. package/dist/sury-CWZTCd75-DTj5HlK_.cjs +14 -0
  78. package/dist/sury-CWZTCd75-DTj5HlK_.cjs.map +1 -0
  79. package/dist/typebox-Dei93FPO-BeuT13_G.cjs +8 -0
  80. package/dist/typebox-Dei93FPO-BeuT13_G.cjs.map +1 -0
  81. package/dist/typebox-Dei93FPO-DovwMlVl.js +8 -0
  82. package/dist/typebox-Dei93FPO-DovwMlVl.js.map +1 -0
  83. package/dist/utils-FVOUvj-I.js +190 -0
  84. package/dist/utils-FVOUvj-I.js.map +1 -0
  85. package/dist/utils-O98BGdnP.cjs +267 -0
  86. package/dist/utils-O98BGdnP.cjs.map +1 -0
  87. package/dist/valibot--1zFm7rT-BqJHja5B.cjs +14 -0
  88. package/dist/valibot--1zFm7rT-BqJHja5B.cjs.map +1 -0
  89. package/dist/valibot--1zFm7rT-Y4Fhea0w.js +14 -0
  90. package/dist/valibot--1zFm7rT-Y4Fhea0w.js.map +1 -0
  91. package/dist/validator/custom-resolver.cjs +71 -73
  92. package/dist/validator/custom-resolver.cjs.map +1 -1
  93. package/dist/validator/custom-resolver.js +70 -71
  94. package/dist/validator/custom-resolver.js.map +1 -1
  95. package/dist/validator/loader.cjs +6 -7
  96. package/dist/validator/loader.cjs.map +1 -1
  97. package/dist/validator/loader.js +8 -4
  98. package/dist/validator/loader.js.map +1 -1
  99. package/dist/zod-Bwrt9trS-2JL6_UI_.cjs +23 -0
  100. package/dist/zod-Bwrt9trS-2JL6_UI_.cjs.map +1 -0
  101. package/dist/zod-Bwrt9trS-rVHICsmp.js +23 -0
  102. package/dist/zod-Bwrt9trS-rVHICsmp.js.map +1 -0
  103. package/package.json +7 -7
  104. package/dist/arktype-aI7TBD0R-K3QZAVE2.js +0 -8
  105. package/dist/arktype-aI7TBD0R-K3QZAVE2.js.map +0 -1
  106. package/dist/arktype-aI7TBD0R-WK5AZZMC.cjs +0 -10
  107. package/dist/arktype-aI7TBD0R-WK5AZZMC.cjs.map +0 -1
  108. package/dist/build/analyze.cjs.map +0 -1
  109. package/dist/build/analyze.js.map +0 -1
  110. package/dist/build/bundler.cjs.map +0 -1
  111. package/dist/build/bundler.js.map +0 -1
  112. package/dist/build/index.cjs.map +0 -1
  113. package/dist/build/index.js.map +0 -1
  114. package/dist/chunk-36AWZH7Z.cjs +0 -252
  115. package/dist/chunk-36AWZH7Z.cjs.map +0 -1
  116. package/dist/chunk-3XIMK24X.cjs +0 -765
  117. package/dist/chunk-3XIMK24X.cjs.map +0 -1
  118. package/dist/chunk-46M65MQG.cjs +0 -95
  119. package/dist/chunk-46M65MQG.cjs.map +0 -1
  120. package/dist/chunk-4ZNTNJ6T.js +0 -6
  121. package/dist/chunk-4ZNTNJ6T.js.map +0 -1
  122. package/dist/chunk-5PORNUPF.js +0 -739
  123. package/dist/chunk-5PORNUPF.js.map +0 -1
  124. package/dist/chunk-743HRNWT.cjs +0 -1546
  125. package/dist/chunk-743HRNWT.cjs.map +0 -1
  126. package/dist/chunk-AEQ7JHDB.cjs +0 -412
  127. package/dist/chunk-AEQ7JHDB.cjs.map +0 -1
  128. package/dist/chunk-E5SBYHQK.js +0 -244
  129. package/dist/chunk-E5SBYHQK.js.map +0 -1
  130. package/dist/chunk-FKKJQUGR.cjs +0 -497
  131. package/dist/chunk-FKKJQUGR.cjs.map +0 -1
  132. package/dist/chunk-FQHUOYYL.js +0 -1514
  133. package/dist/chunk-FQHUOYYL.js.map +0 -1
  134. package/dist/chunk-G7MIMGMX.js +0 -14
  135. package/dist/chunk-G7MIMGMX.js.map +0 -1
  136. package/dist/chunk-HZC3PTK2.cjs +0 -16
  137. package/dist/chunk-HZC3PTK2.cjs.map +0 -1
  138. package/dist/chunk-JZRFRUGM.cjs +0 -158
  139. package/dist/chunk-JZRFRUGM.cjs.map +0 -1
  140. package/dist/chunk-L45X3DJX.js +0 -385
  141. package/dist/chunk-L45X3DJX.js.map +0 -1
  142. package/dist/chunk-PC25XSK7.cjs +0 -8
  143. package/dist/chunk-PC25XSK7.cjs.map +0 -1
  144. package/dist/chunk-PZ5AY32C.js +0 -9
  145. package/dist/chunk-PZ5AY32C.js.map +0 -1
  146. package/dist/chunk-Q7SFCCGT.cjs +0 -11
  147. package/dist/chunk-Q7SFCCGT.cjs.map +0 -1
  148. package/dist/chunk-T4UT2QX7.js +0 -3
  149. package/dist/chunk-T4UT2QX7.js.map +0 -1
  150. package/dist/chunk-UBIDJOJA.js +0 -93
  151. package/dist/chunk-UBIDJOJA.js.map +0 -1
  152. package/dist/chunk-V3EKV6QB.cjs +0 -162
  153. package/dist/chunk-V3EKV6QB.cjs.map +0 -1
  154. package/dist/chunk-WHD2QQ3N.js +0 -783
  155. package/dist/chunk-WHD2QQ3N.js.map +0 -1
  156. package/dist/chunk-WP65JQAT.js +0 -144
  157. package/dist/chunk-WP65JQAT.js.map +0 -1
  158. package/dist/chunk-YO5OFXPN.cjs +0 -819
  159. package/dist/chunk-YO5OFXPN.cjs.map +0 -1
  160. package/dist/chunk-YUBKHO52.js +0 -465
  161. package/dist/chunk-YUBKHO52.js.map +0 -1
  162. package/dist/chunk-YWMYXUHX.cjs +0 -4
  163. package/dist/chunk-YWMYXUHX.cjs.map +0 -1
  164. package/dist/chunk-ZKZOVNT4.js +0 -159
  165. package/dist/chunk-ZKZOVNT4.js.map +0 -1
  166. package/dist/core-XIDAXLRB.js +0 -11866
  167. package/dist/core-XIDAXLRB.js.map +0 -1
  168. package/dist/core-XJNQ4AY6.cjs +0 -12141
  169. package/dist/core-XJNQ4AY6.cjs.map +0 -1
  170. package/dist/default-u_dwuiYb-HGUAHA6N.cjs +0 -9
  171. package/dist/default-u_dwuiYb-HGUAHA6N.cjs.map +0 -1
  172. package/dist/default-u_dwuiYb-MVPTVDCE.js +0 -3
  173. package/dist/default-u_dwuiYb-MVPTVDCE.js.map +0 -1
  174. package/dist/dist-UEE5OLII.cjs +0 -521
  175. package/dist/dist-UEE5OLII.cjs.map +0 -1
  176. package/dist/dist-X75F2Q36.js +0 -515
  177. package/dist/dist-X75F2Q36.js.map +0 -1
  178. package/dist/effect-QlVUlMFu-QNLZLGWO.js +0 -15
  179. package/dist/effect-QlVUlMFu-QNLZLGWO.js.map +0 -1
  180. package/dist/effect-QlVUlMFu-XUD6EH23.cjs +0 -17
  181. package/dist/effect-QlVUlMFu-XUD6EH23.cjs.map +0 -1
  182. package/dist/esm-DFCHSIJZ.cjs +0 -1589
  183. package/dist/esm-DFCHSIJZ.cjs.map +0 -1
  184. package/dist/esm-PXGQ5WB4.js +0 -1542
  185. package/dist/esm-PXGQ5WB4.js.map +0 -1
  186. package/dist/services/index.cjs.map +0 -1
  187. package/dist/services/index.js.map +0 -1
  188. package/dist/sury-CWZTCd75-3KQQJ22C.cjs +0 -17
  189. package/dist/sury-CWZTCd75-3KQQJ22C.cjs.map +0 -1
  190. package/dist/sury-CWZTCd75-DZQHKAZF.js +0 -15
  191. package/dist/sury-CWZTCd75-DZQHKAZF.js.map +0 -1
  192. package/dist/typebox-Dei93FPO-GOYJ5OUT.js +0 -8
  193. package/dist/typebox-Dei93FPO-GOYJ5OUT.js.map +0 -1
  194. package/dist/typebox-Dei93FPO-M7J7E57W.cjs +0 -10
  195. package/dist/typebox-Dei93FPO-M7J7E57W.cjs.map +0 -1
  196. package/dist/valibot--1zFm7rT-NVM3G3TI.cjs +0 -17
  197. package/dist/valibot--1zFm7rT-NVM3G3TI.cjs.map +0 -1
  198. package/dist/valibot--1zFm7rT-ZVGQI7WV.js +0 -15
  199. package/dist/valibot--1zFm7rT-ZVGQI7WV.js.map +0 -1
  200. package/dist/valibot-D_HTw1Gn-UCPEGDL7.cjs +0 -45
  201. package/dist/valibot-D_HTw1Gn-UCPEGDL7.cjs.map +0 -1
  202. package/dist/valibot-D_HTw1Gn-XPR4F6VS.js +0 -43
  203. package/dist/valibot-D_HTw1Gn-XPR4F6VS.js.map +0 -1
  204. package/dist/zod-Bwrt9trS-GN7ZXBMN.js +0 -29
  205. package/dist/zod-Bwrt9trS-GN7ZXBMN.js.map +0 -1
  206. package/dist/zod-Bwrt9trS-OVKARV6W.cjs +0 -31
  207. package/dist/zod-Bwrt9trS-OVKARV6W.cjs.map +0 -1
  208. package/dist/zod-DSgpEGAE-E7YZZ7VC.js +0 -37
  209. package/dist/zod-DSgpEGAE-E7YZZ7VC.js.map +0 -1
  210. package/dist/zod-DSgpEGAE-UNQNGL2W.cjs +0 -39
  211. package/dist/zod-DSgpEGAE-UNQNGL2W.cjs.map +0 -1
@@ -1,1514 +0,0 @@
1
- import { getPackageMetadata, protocolExternalResolver, mastraInternalAliasPlugin, mastraToolsAliasPlugin, tsConfigPaths, esbuild, removeDeployer, getPackageRootPath, subpathExternalsResolver, esmShim } from './chunk-5PORNUPF.js';
2
- import { slash, isDependencyPartOfPackage, getPackageName, isBuiltinModule, isBareModuleSpecifier, isExternalProtocolImport, getCompiledDepCachePath, rollupSafeName, getNodeResolveOptions } from './chunk-WP65JQAT.js';
3
- import { existsSync } from 'fs';
4
- import { readFile, writeFile } from 'fs/promises';
5
- import * as path from 'path';
6
- import { dirname, join, relative, isAbsolute, basename as basename$1 } from 'path';
7
- import { types, transformAsync, transformSync } from '@babel/core';
8
- import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
9
- import * as pkg from 'empathic/package';
10
- import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
11
- import { spawn as spawn$1 } from 'child_process';
12
- import { fileURLToPath, pathToFileURL } from 'url';
13
- import commonjs from '@rollup/plugin-commonjs';
14
- import json from '@rollup/plugin-json';
15
- import virtual from '@rollup/plugin-virtual';
16
- import { rollup } from 'rollup';
17
- import { basename } from 'path/posix';
18
- import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
19
- import nodeResolve from '@rollup/plugin-node-resolve';
20
- import { getPackageInfo } from 'local-pkg';
21
- import * as resolve from 'resolve.exports';
22
-
23
- // ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/stacktrace-parser/0.1.11/63406bc765474556691ebd1b24eaa0c5b032f058a26bbaff13797a2780d98220/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
24
- var UNKNOWN_FUNCTION = "<unknown>";
25
- function parse(stackString) {
26
- var lines = stackString.split("\n");
27
- return lines.reduce(function(stack, line) {
28
- var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
29
- if (parseResult) {
30
- stack.push(parseResult);
31
- }
32
- return stack;
33
- }, []);
34
- }
35
- var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
36
- var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
37
- function parseChrome(line) {
38
- var parts = chromeRe.exec(line);
39
- if (!parts) {
40
- return null;
41
- }
42
- var isNative = parts[2] && parts[2].indexOf("native") === 0;
43
- var isEval = parts[2] && parts[2].indexOf("eval") === 0;
44
- var submatch = chromeEvalRe.exec(parts[2]);
45
- if (isEval && submatch != null) {
46
- parts[2] = submatch[1];
47
- parts[3] = submatch[2];
48
- parts[4] = submatch[3];
49
- }
50
- return {
51
- file: !isNative ? parts[2] : null,
52
- methodName: parts[1] || UNKNOWN_FUNCTION,
53
- arguments: isNative ? [parts[2]] : [],
54
- lineNumber: parts[3] ? +parts[3] : null,
55
- column: parts[4] ? +parts[4] : null
56
- };
57
- }
58
- var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
59
- function parseWinjs(line) {
60
- var parts = winjsRe.exec(line);
61
- if (!parts) {
62
- return null;
63
- }
64
- return {
65
- file: parts[2],
66
- methodName: parts[1] || UNKNOWN_FUNCTION,
67
- arguments: [],
68
- lineNumber: +parts[3],
69
- column: parts[4] ? +parts[4] : null
70
- };
71
- }
72
- var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
73
- var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
74
- function parseGecko(line) {
75
- var parts = geckoRe.exec(line);
76
- if (!parts) {
77
- return null;
78
- }
79
- var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
80
- var submatch = geckoEvalRe.exec(parts[3]);
81
- if (isEval && submatch != null) {
82
- parts[3] = submatch[1];
83
- parts[4] = submatch[2];
84
- parts[5] = null;
85
- }
86
- return {
87
- file: parts[3],
88
- methodName: parts[1] || UNKNOWN_FUNCTION,
89
- arguments: parts[2] ? parts[2].split(",") : [],
90
- lineNumber: parts[4] ? +parts[4] : null,
91
- column: parts[5] ? +parts[5] : null
92
- };
93
- }
94
- var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
95
- function parseJSC(line) {
96
- var parts = javaScriptCoreRe.exec(line);
97
- if (!parts) {
98
- return null;
99
- }
100
- return {
101
- file: parts[3],
102
- methodName: parts[1] || UNKNOWN_FUNCTION,
103
- arguments: [],
104
- lineNumber: +parts[4],
105
- column: parts[5] ? +parts[5] : null
106
- };
107
- }
108
- var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
109
- function parseNode(line) {
110
- var parts = nodeRe.exec(line);
111
- if (!parts) {
112
- return null;
113
- }
114
- return {
115
- file: parts[2],
116
- methodName: parts[1] || UNKNOWN_FUNCTION,
117
- arguments: [],
118
- lineNumber: +parts[3],
119
- column: parts[4] ? +parts[4] : null
120
- };
121
- }
122
- var workspacesCache = createWorkspacesCache();
123
- async function getWorkspaceInformation({
124
- dir = process.cwd(),
125
- mastraEntryFile
126
- }) {
127
- const closestPkgJson = pkg.up({ cwd: dirname(mastraEntryFile) });
128
- const location = closestPkgJson ? dirname(slash(closestPkgJson)) : slash(process.cwd());
129
- const workspaces = await findWorkspaces(dir, { cache: workspacesCache });
130
- const _workspaceMap = new Map(
131
- workspaces?.map((workspace) => [
132
- workspace.package.name,
133
- {
134
- location: workspace.location,
135
- dependencies: workspace.package.dependencies,
136
- version: workspace.package.version
137
- }
138
- ]) ?? []
139
- );
140
- const isWorkspacePackage = (workspaces ?? []).some((ws) => ws.location === location);
141
- const workspaceRoot = isWorkspacePackage ? findWorkspacesRoot(dir, { cache: workspacesCache })?.location : void 0;
142
- return {
143
- // If the current package is not part of the workspace, the bundling down the line shouldn't look at any workspace packages
144
- workspaceMap: isWorkspacePackage ? _workspaceMap : /* @__PURE__ */ new Map(),
145
- workspaceRoot,
146
- isWorkspacePackage
147
- };
148
- }
149
- var ValidationError = class extends Error {
150
- type;
151
- stack;
152
- constructor(args) {
153
- super(args.message);
154
- this.type = args.type;
155
- this.stack = args.stack;
156
- }
157
- };
158
- function spawn(command, args = [], options = {}) {
159
- return new Promise((resolve2, reject) => {
160
- let validationError = null;
161
- const childProcess = spawn$1(command, args, {
162
- stdio: ["ignore", "ignore", "pipe"],
163
- ...options
164
- });
165
- childProcess.on("error", (error) => {
166
- reject(error);
167
- });
168
- let stderr = "";
169
- childProcess.stderr?.on("data", (message) => {
170
- try {
171
- validationError = JSON.parse(message.toString());
172
- } catch {
173
- stderr += message;
174
- }
175
- });
176
- childProcess.on("close", (code) => {
177
- if (code === 0) {
178
- resolve2();
179
- } else {
180
- if (validationError) {
181
- reject(new ValidationError(validationError));
182
- } else {
183
- reject(new Error(stderr));
184
- }
185
- }
186
- });
187
- });
188
- }
189
- function validate(file, {
190
- injectESMShim = false,
191
- moduleResolveMapLocation,
192
- stubbedExternals = []
193
- }) {
194
- let prefixCode = "";
195
- if (injectESMShim) {
196
- prefixCode = `import { fileURLToPath } from 'url';
197
- import { dirname } from 'path';
198
-
199
- globalThis.__filename = fileURLToPath(import.meta.url);
200
- globalThis.__dirname = dirname(__filename);
201
- `;
202
- }
203
- function errorHandler(err) {
204
- console.error(
205
- JSON.stringify({
206
- type: err.name,
207
- message: err.message,
208
- stack: err.stack
209
- })
210
- );
211
- process.exit(1);
212
- }
213
- return spawn(
214
- process.execPath,
215
- [
216
- "--import",
217
- import.meta.resolve("@mastra/deployer/loader"),
218
- "--input-type=module",
219
- "--enable-source-maps",
220
- "-e",
221
- `${prefixCode};import('${pathToFileURL(file).href}').catch(err => {
222
- ${errorHandler.toString()}
223
- errorHandler(err);
224
- })`.replaceAll(/\n/g, "")
225
- ],
226
- {
227
- env: {
228
- ...process.env,
229
- MODULE_MAP: `${moduleResolveMapLocation}`,
230
- STUBBED_EXTERNALS: JSON.stringify(stubbedExternals)
231
- },
232
- cwd: dirname(file)
233
- }
234
- );
235
- }
236
-
237
- // src/build/analyze/constants.ts
238
- var DEPS_TO_IGNORE = ["#tools", "execa"];
239
- var GLOBAL_EXTERNALS = [
240
- "pino",
241
- "pino-pretty",
242
- "@libsql/client",
243
- "pg",
244
- "libsql",
245
- "#tools",
246
- "typescript",
247
- "undici",
248
- "readable-stream",
249
- "bufferutil",
250
- "utf-8-validate",
251
- "execa"
252
- ];
253
- var DEPRECATED_EXTERNALS = ["fastembed", "nodemailer", "jsdom", "sqlite3"];
254
-
255
- // src/build/analyze/analyzeEntry.ts
256
- function getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }) {
257
- let virtualPlugin = null;
258
- if (isVirtualFile) {
259
- virtualPlugin = virtual({
260
- "#entry": entry
261
- });
262
- entry = "#entry";
263
- }
264
- const plugins = [];
265
- if (virtualPlugin) {
266
- plugins.push(virtualPlugin);
267
- }
268
- plugins.push(
269
- ...[
270
- protocolExternalResolver(),
271
- mastraInternalAliasPlugin(mastraEntry),
272
- mastraToolsAliasPlugin(),
273
- tsConfigPaths(),
274
- json(),
275
- esbuild(),
276
- commonjs({
277
- strictRequires: "debug",
278
- ignoreTryCatch: false,
279
- transformMixedEsModules: true,
280
- extensions: [".js", ".ts"]
281
- }),
282
- removeDeployer(mastraEntry, {
283
- sourcemap: sourcemapEnabled
284
- }),
285
- esbuild()
286
- ]
287
- );
288
- return plugins;
289
- }
290
- async function captureDependenciesToOptimize(output, workspaceMap, projectRoot, {
291
- logger,
292
- shouldCheckTransitiveDependencies
293
- }) {
294
- const depsToOptimize = /* @__PURE__ */ new Map();
295
- if (!output.facadeModuleId) {
296
- throw new Error(
297
- "Something went wrong, we could not find the package name of the entry file. Please open an issue."
298
- );
299
- }
300
- let entryRootPath = projectRoot;
301
- if (!output.facadeModuleId.startsWith("\0virtual:")) {
302
- entryRootPath = await getPackageRootPath(output.facadeModuleId) || projectRoot;
303
- }
304
- for (const [dependency, bindings] of Object.entries(output.importedBindings)) {
305
- if (!isBareModuleSpecifier(dependency)) {
306
- continue;
307
- }
308
- const pkgName = getPackageName(dependency);
309
- let rootPath = null;
310
- let isWorkspace = false;
311
- let version;
312
- let packageSpec;
313
- if (pkgName) {
314
- const metadata = await getPackageMetadata(dependency, entryRootPath);
315
- rootPath = metadata.rootPath;
316
- version = metadata.version;
317
- packageSpec = metadata.packageSpec;
318
- isWorkspace = workspaceMap.has(pkgName);
319
- }
320
- const normalizedRootPath = rootPath ? slash(rootPath) : null;
321
- depsToOptimize.set(dependency, {
322
- exports: bindings,
323
- rootPath: normalizedRootPath,
324
- isWorkspace,
325
- version,
326
- packageSpec
327
- });
328
- }
329
- const processedWorkspaceDeps = /* @__PURE__ */ new Set();
330
- function checkTransitiveDependencies(maxDepth = 10, currentDepth = 0) {
331
- if (currentDepth >= maxDepth) {
332
- logger.warn("Maximum dependency depth reached while checking transitive dependencies.");
333
- return;
334
- }
335
- const depsSnapshot = new Map(depsToOptimize);
336
- let hasAddedDeps = false;
337
- for (const [dep, meta] of depsSnapshot) {
338
- const pkgName = getPackageName(dep);
339
- if (!pkgName || !meta.isWorkspace || processedWorkspaceDeps.has(pkgName)) {
340
- continue;
341
- }
342
- processedWorkspaceDeps.add(pkgName);
343
- const workspaceInfo = workspaceMap.get(pkgName);
344
- if (!workspaceInfo?.dependencies) {
345
- continue;
346
- }
347
- for (const [innerDep, _innerDepVersion] of Object.entries(workspaceInfo.dependencies)) {
348
- const innerWorkspaceInfo = workspaceMap.get(innerDep);
349
- if (!innerWorkspaceInfo) {
350
- continue;
351
- }
352
- const existingMeta = depsToOptimize.get(innerDep);
353
- if (existingMeta) {
354
- depsToOptimize.set(innerDep, {
355
- ...existingMeta,
356
- exports: existingMeta.exports.includes("*") ? existingMeta.exports : [...existingMeta.exports, "*"]
357
- });
358
- continue;
359
- }
360
- depsToOptimize.set(innerDep, {
361
- exports: ["*"],
362
- rootPath: slash(innerWorkspaceInfo.location),
363
- isWorkspace: true,
364
- version: innerWorkspaceInfo.version
365
- });
366
- hasAddedDeps = true;
367
- }
368
- }
369
- if (hasAddedDeps) {
370
- checkTransitiveDependencies(maxDepth, currentDepth + 1);
371
- }
372
- }
373
- if (shouldCheckTransitiveDependencies) {
374
- checkTransitiveDependencies();
375
- }
376
- const dynamicImports = output.dynamicImports.filter((d) => !DEPS_TO_IGNORE.includes(d));
377
- if (dynamicImports.length) {
378
- for (const dynamicImport of dynamicImports) {
379
- if (!depsToOptimize.has(dynamicImport) && isBareModuleSpecifier(dynamicImport)) {
380
- const pkgName = getPackageName(dynamicImport);
381
- let version;
382
- let packageSpec;
383
- let rootPath = null;
384
- if (pkgName) {
385
- const metadata = await getPackageMetadata(dynamicImport, entryRootPath);
386
- rootPath = metadata.rootPath;
387
- version = metadata.version;
388
- packageSpec = metadata.packageSpec;
389
- }
390
- depsToOptimize.set(dynamicImport, {
391
- exports: ["*"],
392
- rootPath: rootPath ? slash(rootPath) : null,
393
- isWorkspace: false,
394
- version,
395
- packageSpec
396
- });
397
- }
398
- }
399
- }
400
- return depsToOptimize;
401
- }
402
- async function analyzeEntry({
403
- entry,
404
- isVirtualFile
405
- }, mastraEntry, {
406
- logger,
407
- sourcemapEnabled,
408
- workspaceMap,
409
- projectRoot,
410
- shouldCheckTransitiveDependencies = false,
411
- analyzeCache
412
- }) {
413
- const cacheKey = isVirtualFile ? void 0 : slash(entry);
414
- if (cacheKey && analyzeCache?.has(cacheKey)) {
415
- return analyzeCache.get(cacheKey);
416
- }
417
- const optimizerBundler = await rollup({
418
- logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
419
- input: isVirtualFile ? "#entry" : entry,
420
- treeshake: false,
421
- preserveSymlinks: true,
422
- plugins: getInputPlugins({ entry, isVirtualFile }, mastraEntry, { sourcemapEnabled }),
423
- external: DEPS_TO_IGNORE
424
- });
425
- const { output } = await optimizerBundler.generate({
426
- format: "esm",
427
- inlineDynamicImports: true
428
- });
429
- await optimizerBundler.close();
430
- const depsToOptimize = await captureDependenciesToOptimize(output[0], workspaceMap, projectRoot, {
431
- logger,
432
- shouldCheckTransitiveDependencies
433
- });
434
- const result = {
435
- dependencies: depsToOptimize,
436
- output: {
437
- code: output[0].code,
438
- map: output[0].map
439
- }
440
- };
441
- if (cacheKey && analyzeCache) {
442
- analyzeCache.set(cacheKey, result);
443
- }
444
- return result;
445
- }
446
- function aliasHono() {
447
- return {
448
- name: "hono-alias",
449
- resolveId(id) {
450
- if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
451
- return;
452
- }
453
- const path2 = import.meta.resolve(id);
454
- return fileURLToPath(path2);
455
- }
456
- };
457
- }
458
- function moduleResolveMap(externals, projectRoot) {
459
- const importMap = /* @__PURE__ */ new Map();
460
- return {
461
- name: "module-resolve-map",
462
- moduleParsed(info) {
463
- if (info.importedIds.length === 0 || !info.id) {
464
- return;
465
- }
466
- for (const importedId of info.importedIds) {
467
- for (const external of externals) {
468
- if (isDependencyPartOfPackage(importedId, external)) {
469
- importMap.set(external, info.id);
470
- }
471
- }
472
- }
473
- },
474
- async generateBundle(options, bundle) {
475
- const resolveMap = /* @__PURE__ */ new Map();
476
- for (const [fileName, chunk] of Object.entries(bundle)) {
477
- if (chunk.type === "chunk") {
478
- for (const [external, resolvedFrom] of importMap) {
479
- if (chunk.moduleIds.includes(resolvedFrom)) {
480
- const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
481
- const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
482
- innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
483
- resolveMap.set(fullPath, innerMap);
484
- }
485
- }
486
- }
487
- }
488
- const resolveMapJson = Object.fromEntries(
489
- Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
490
- );
491
- this.emitFile({
492
- type: "asset",
493
- name: "module-resolve-map.json",
494
- source: `${JSON.stringify(resolveMapJson, null, 2)}`
495
- });
496
- }
497
- };
498
- }
499
- function nodeGypDetector() {
500
- const modulesToTrack = /* @__PURE__ */ new Set();
501
- const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
502
- return {
503
- name: "node-gyp-build-detector",
504
- moduleParsed(info) {
505
- if (!info.meta?.commonjs?.requires?.length) {
506
- return;
507
- }
508
- const hasNodeGypBuild = info.meta.commonjs.requires.some(
509
- (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
510
- );
511
- if (!hasNodeGypBuild) {
512
- return;
513
- }
514
- modulesToTrack.add(info.id);
515
- modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
516
- },
517
- async generateBundle(options, bundle) {
518
- const binaryMapByChunk = /* @__PURE__ */ new Map();
519
- for (const [fileName, chunk] of Object.entries(bundle)) {
520
- if (chunk.type === "chunk") {
521
- for (const moduleId of chunk.moduleIds) {
522
- if (modulesToTrackPackageInfo.has(moduleId)) {
523
- const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
524
- if (!binaryMapByChunk.has(fileName)) {
525
- binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
526
- }
527
- if (pkgInfo?.packageJson?.name) {
528
- binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
529
- }
530
- }
531
- }
532
- }
533
- }
534
- const binaryMapJson = Object.fromEntries(
535
- Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
536
- );
537
- this.emitFile({
538
- type: "asset",
539
- name: "binary-map.json",
540
- source: `${JSON.stringify(binaryMapJson, null, 2)}`
541
- });
542
- }
543
- };
544
- }
545
-
546
- // src/build/analyze/bundleExternals.ts
547
- function prepareEntryFileName(name, rootDir) {
548
- return rollupSafeName(name, rootDir);
549
- }
550
- function createVirtualDependencies(depsToOptimize, {
551
- projectRoot,
552
- workspaceRoot,
553
- outputDir,
554
- bundlerOptions
555
- }) {
556
- const { isDev = false, externalsPreset = false } = bundlerOptions || {};
557
- const fileNameToDependencyMap = /* @__PURE__ */ new Map();
558
- const optimizedDependencyEntries = /* @__PURE__ */ new Map();
559
- const rootDir = workspaceRoot || projectRoot;
560
- for (const [dep, { exports: exports2 }] of depsToOptimize.entries()) {
561
- const fileName = dep.replaceAll("/", "__");
562
- const virtualFile = [];
563
- const exportStringBuilder = [];
564
- for (const local of exports2) {
565
- if (local === "*") {
566
- virtualFile.push(`export * from '${dep}';`);
567
- continue;
568
- } else if (local === "default") {
569
- exportStringBuilder.push("default");
570
- } else {
571
- exportStringBuilder.push(local);
572
- }
573
- }
574
- const chunks = [];
575
- if (exportStringBuilder.length) {
576
- chunks.push(`{ ${exportStringBuilder.join(", ")} }`);
577
- }
578
- if (chunks.length) {
579
- virtualFile.push(`export ${chunks.join(", ")} from '${dep}';`);
580
- }
581
- let entryName = prepareEntryFileName(path.join(outputDir, fileName), rootDir);
582
- fileNameToDependencyMap.set(entryName, dep);
583
- optimizedDependencyEntries.set(dep, {
584
- name: entryName,
585
- virtual: virtualFile.join("\n")
586
- });
587
- }
588
- if (isDev || externalsPreset) {
589
- for (const [dep, { isWorkspace, rootPath }] of depsToOptimize.entries()) {
590
- if (!isWorkspace || !rootPath || !workspaceRoot) {
591
- continue;
592
- }
593
- const currentDepPath = optimizedDependencyEntries.get(dep);
594
- if (!currentDepPath) {
595
- continue;
596
- }
597
- const fileName = basename(currentDepPath.name);
598
- const entryName = prepareEntryFileName(getCompiledDepCachePath(rootPath, fileName), rootDir);
599
- fileNameToDependencyMap.set(entryName, dep);
600
- optimizedDependencyEntries.set(dep, {
601
- ...currentDepPath,
602
- name: entryName
603
- });
604
- }
605
- }
606
- return { optimizedDependencyEntries, fileNameToDependencyMap };
607
- }
608
- async function getInputPlugins2(virtualDependencies, {
609
- transpilePackages,
610
- workspaceMap,
611
- bundlerOptions,
612
- rootDir,
613
- externals,
614
- platform
615
- }) {
616
- const transpilePackagesMap = /* @__PURE__ */ new Map();
617
- for (const pkg2 of transpilePackages) {
618
- const dir = await getPackageRootPath(pkg2);
619
- if (dir) {
620
- transpilePackagesMap.set(pkg2, slash(dir));
621
- } else {
622
- transpilePackagesMap.set(pkg2, workspaceMap.get(pkg2)?.location ?? pkg2);
623
- }
624
- }
625
- return [
626
- virtual(
627
- Array.from(virtualDependencies.entries()).reduce(
628
- (acc, [dep, virtualDep]) => {
629
- acc[`#virtual-${dep}`] = virtualDep.virtual;
630
- return acc;
631
- },
632
- {}
633
- )
634
- ),
635
- tsConfigPaths(),
636
- protocolExternalResolver(),
637
- subpathExternalsResolver(externals),
638
- transpilePackagesMap.size ? esbuild({
639
- format: "esm",
640
- include: [
641
- // Match files from transpilePackages by their actual directory paths
642
- // but exclude any nested node_modules
643
- ...[...transpilePackagesMap.values()].map((p) => {
644
- if (path.isAbsolute(p)) {
645
- return new RegExp(`^${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
646
- } else {
647
- return new RegExp(`/${p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/(?!.*node_modules).*$`);
648
- }
649
- }),
650
- // Also match workspace packages resolved through node_modules symlinks
651
- // (common in pnpm workspaces). Match by package name in node_modules path.
652
- ...[...transpilePackagesMap.keys()].map((pkgName) => {
653
- const escapedPkgName = pkgName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
654
- return new RegExp(`/node_modules/${escapedPkgName}/(?!.*node_modules).*$`);
655
- })
656
- ],
657
- // Disable the default /node_modules/ exclusion from rollup-plugin-esbuild.
658
- // In pnpm workspaces, nodeResolve resolves workspace packages through node_modules
659
- // symlinks, so the resolved paths contain "node_modules". Without this, workspace
660
- // package .ts files won't be transpiled even if they match the include patterns.
661
- exclude: []
662
- }) : null,
663
- bundlerOptions.noBundling ? {
664
- name: "alias-optimized-deps",
665
- async resolveId(id, importer, options) {
666
- if (!virtualDependencies.has(id)) {
667
- return null;
668
- }
669
- const info = virtualDependencies.get(id);
670
- const packageRootPath = path.join(rootDir, path.dirname(path.dirname(path.dirname(info.name))));
671
- const pkgJsonBuffer = await readFile(path.join(packageRootPath, "package.json"), "utf-8");
672
- const pkgJson = JSON.parse(pkgJsonBuffer);
673
- if (!pkgJson) {
674
- return null;
675
- }
676
- const pkgName = pkgJson.name || "";
677
- let resolvedPath = resolve.exports(pkgJson, id.replace(pkgName, "."))?.[0];
678
- if (!resolvedPath) {
679
- resolvedPath = pkgJson.main ?? "index.js";
680
- }
681
- const resolved = await this.resolve(path.posix.join(packageRootPath, resolvedPath), importer, options);
682
- return resolved;
683
- }
684
- } : null,
685
- optimizeLodashImports({
686
- include: "**/*.{js,ts,mjs,cjs}"
687
- }),
688
- commonjs({
689
- strictRequires: "strict",
690
- transformMixedEsModules: true,
691
- ignoreTryCatch: false
692
- }),
693
- bundlerOptions.noBundling ? null : nodeResolve(getNodeResolveOptions(platform)),
694
- bundlerOptions.noBundling ? esmShim() : null,
695
- // hono is imported from deployer, so we need to resolve from here instead of the project root
696
- aliasHono(),
697
- json(),
698
- nodeGypDetector(),
699
- moduleResolveMap(externals, rootDir),
700
- {
701
- name: "not-found-resolver",
702
- resolveId: {
703
- order: "post",
704
- async handler(id, importer) {
705
- if (!importer) {
706
- return null;
707
- }
708
- if (!id.endsWith(".node")) {
709
- return null;
710
- }
711
- const pkgInfo = await getPackageInfo(importer);
712
- const packageName = pkgInfo?.packageJson?.name || id;
713
- throw new MastraBaseError({
714
- id: "DEPLOYER_BUNDLE_EXTERNALS_MISSING_NATIVE_BUILD",
715
- domain: ErrorDomain.DEPLOYER,
716
- category: ErrorCategory.USER,
717
- details: {
718
- importFile: importer,
719
- packageName
720
- },
721
- text: `We found a possible binary dependency in your bundle. ${id} was not found when imported at ${importer}.
722
-
723
- Please consider adding \`${packageName}\` to your externals, or updating this import to not end with ".node".
724
-
725
- export const mastra = new Mastra({
726
- bundler: {
727
- externals: ["${packageName}"],
728
- }
729
- })`
730
- });
731
- }
732
- }
733
- }
734
- ].filter(Boolean);
735
- }
736
- async function buildExternalDependencies(virtualDependencies, {
737
- externals,
738
- packagesToTranspile,
739
- workspaceMap,
740
- rootDir,
741
- outputDir,
742
- bundlerOptions,
743
- platform
744
- }) {
745
- if (virtualDependencies.size === 0) {
746
- return [];
747
- }
748
- const noBundling = bundlerOptions.isDev || bundlerOptions.externalsPreset;
749
- const plugins = await getInputPlugins2(virtualDependencies, {
750
- transpilePackages: packagesToTranspile,
751
- workspaceMap,
752
- bundlerOptions: {
753
- noBundling
754
- },
755
- rootDir,
756
- externals,
757
- platform
758
- });
759
- const bundler = await rollup({
760
- logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
761
- input: Array.from(virtualDependencies.entries()).reduce(
762
- (acc, [dep, virtualDep]) => {
763
- acc[virtualDep.name] = `#virtual-${dep}`;
764
- return acc;
765
- },
766
- {}
767
- ),
768
- external: externals,
769
- treeshake: noBundling ? false : "safest",
770
- plugins
771
- });
772
- const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
773
- const { output } = await bundler.write({
774
- format: "esm",
775
- dir: rootDir,
776
- entryFileNames: "[name].mjs",
777
- // used to get the filename of the actual error
778
- sourcemap: true,
779
- /**
780
- * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
781
- * So we want to write them to the `.mastra/output` folder as well.
782
- */
783
- chunkFileNames: (chunkInfo) => {
784
- if (noBundling) {
785
- const importedFromPackages = /* @__PURE__ */ new Set();
786
- for (const moduleId of chunkInfo.moduleIds) {
787
- const normalized = slash(moduleId);
788
- for (const [pkgName, pkgInfo] of workspaceMap.entries()) {
789
- const location = slash(pkgInfo.location);
790
- if (normalized.startsWith(location)) {
791
- importedFromPackages.add(pkgName);
792
- break;
793
- }
794
- }
795
- }
796
- if (importedFromPackages.size > 1) {
797
- throw new MastraBaseError({
798
- id: "DEPLOYER_BUNDLE_EXTERNALS_SHARED_CHUNK",
799
- domain: ErrorDomain.DEPLOYER,
800
- category: ErrorCategory.USER,
801
- details: {
802
- chunkName: chunkInfo.name,
803
- packages: JSON.stringify(Array.from(importedFromPackages))
804
- },
805
- text: `Please open an issue. We found a shared chunk "${chunkInfo.name}" used by multiple workspace packages: ${Array.from(importedFromPackages).join(", ")}.`
806
- });
807
- }
808
- if (importedFromPackages.size === 1) {
809
- const [pkgName] = importedFromPackages;
810
- const workspaceLocation = workspaceMap.get(pkgName).location;
811
- return prepareEntryFileName(getCompiledDepCachePath(workspaceLocation, "[name].mjs"), rootDir);
812
- }
813
- }
814
- return `${outputDirRelative}/[name].mjs`;
815
- },
816
- assetFileNames: `${outputDirRelative}/[name][extname]`,
817
- hoistTransitiveImports: false
818
- });
819
- await bundler.close();
820
- return output;
821
- }
822
- function findExternalImporter(module, external, allOutputs, visited = /* @__PURE__ */ new Set()) {
823
- if (visited.has(module.fileName)) {
824
- return null;
825
- }
826
- visited.add(module.fileName);
827
- const capturedFiles = /* @__PURE__ */ new Set();
828
- for (const id of [...module.imports, ...module.dynamicImports]) {
829
- if (isDependencyPartOfPackage(id, external)) {
830
- return module;
831
- } else {
832
- if (id.endsWith(".mjs")) {
833
- capturedFiles.add(id);
834
- }
835
- }
836
- }
837
- for (const file of capturedFiles) {
838
- const nextModule = allOutputs.find((o) => o.fileName === file);
839
- if (nextModule) {
840
- const importer = findExternalImporter(nextModule, external, allOutputs, visited);
841
- if (importer) {
842
- return importer;
843
- }
844
- }
845
- }
846
- return null;
847
- }
848
- async function bundleExternals(depsToOptimize, outputDir, options) {
849
- const {
850
- workspaceRoot = null,
851
- workspaceMap = /* @__PURE__ */ new Map(),
852
- projectRoot = outputDir,
853
- bundlerOptions = {},
854
- platform = "node"
855
- } = options;
856
- const { externals: customExternals = [], transpilePackages = [], isDev = false } = bundlerOptions || {};
857
- let externalsPreset = false;
858
- if (customExternals === true) {
859
- externalsPreset = true;
860
- }
861
- const externalsList = Array.isArray(customExternals) ? customExternals : [];
862
- const allExternals = [...GLOBAL_EXTERNALS, ...DEPRECATED_EXTERNALS, ...externalsList];
863
- const workspacePackagesNames = Array.from(workspaceMap.keys());
864
- const packagesToTranspile = /* @__PURE__ */ new Set([...transpilePackages, ...workspacePackagesNames]);
865
- const extractedExternals = /* @__PURE__ */ new Map();
866
- if (externalsPreset) {
867
- for (const [dep, metadata] of depsToOptimize.entries()) {
868
- if (!metadata.isWorkspace) {
869
- extractedExternals.set(dep, metadata.rootPath ?? dep);
870
- depsToOptimize.delete(dep);
871
- }
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 moduleResolveMap2 = /* @__PURE__ */ new Map();
896
- const filteredChunks = output.filter((o) => o.type === "chunk");
897
- for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
898
- for (const external of allExternals) {
899
- if (DEPS_TO_IGNORE.includes(external)) {
900
- continue;
901
- }
902
- const importer = findExternalImporter(o, external, filteredChunks);
903
- if (importer) {
904
- const fullPath = path.join(workspaceRoot || projectRoot, importer.fileName);
905
- let innerMap = moduleResolveMap2.get(fullPath);
906
- if (!innerMap) {
907
- innerMap = /* @__PURE__ */ new Map();
908
- moduleResolveMap2.set(fullPath, innerMap);
909
- }
910
- if (importer.moduleIds.length) {
911
- innerMap.set(
912
- external,
913
- importer.moduleIds[importer.moduleIds.length - 1]?.startsWith("\0virtual:#virtual") ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1]
914
- );
915
- }
916
- }
917
- }
918
- }
919
- const usedExternals = /* @__PURE__ */ Object.create(null);
920
- for (const [fullPath, innerMap] of moduleResolveMap2) {
921
- const innerObj = /* @__PURE__ */ Object.create(null);
922
- for (const [external, value] of innerMap) {
923
- innerObj[external] = value;
924
- }
925
- usedExternals[fullPath] = innerObj;
926
- }
927
- if (extractedExternals.size > 0) {
928
- const syntheticPath = path.join(workspaceRoot || projectRoot, "__externals__");
929
- const externalsObj = /* @__PURE__ */ Object.create(null);
930
- for (const [dep, rootPath] of extractedExternals) {
931
- externalsObj[dep] = rootPath;
932
- }
933
- usedExternals[syntheticPath] = externalsObj;
934
- }
935
- return { output, fileNameToDependencyMap, usedExternals };
936
- }
937
- function checkConfigExport(result) {
938
- const mastraVars = /* @__PURE__ */ new Set();
939
- return {
940
- visitor: {
941
- NewExpression(path2) {
942
- if (!types.isIdentifier(path2.node.callee)) {
943
- return;
944
- }
945
- const binding = path2.scope.getBinding(path2.node.callee.name);
946
- if (binding?.path.isImportSpecifier() && types.isIdentifier(binding.path.node.imported, { name: "MastraFactory" })) {
947
- result.projectType = "factory";
948
- }
949
- },
950
- ExportNamedDeclaration(path2) {
951
- const decl = path2.node.declaration;
952
- if (types.isVariableDeclaration(decl)) {
953
- const varDecl = decl.declarations[0];
954
- if (types.isIdentifier(varDecl?.id, { name: "mastra" }) && types.isNewExpression(varDecl.init) && types.isIdentifier(varDecl.init.callee, { name: "Mastra" })) {
955
- result.hasValidConfig = true;
956
- }
957
- }
958
- if (Array.isArray(path2.node.specifiers)) {
959
- for (const spec of path2.node.specifiers) {
960
- if (types.isExportSpecifier(spec) && types.isIdentifier(spec.exported, { name: "mastra" }) && types.isIdentifier(spec.local) && mastraVars.has(spec.local.name)) {
961
- result.hasValidConfig = true;
962
- }
963
- }
964
- }
965
- },
966
- // For cases 2-4 we need to track whether those variables are assigned to `new Mastra()`
967
- VariableDeclaration(path2) {
968
- for (const decl of path2.node.declarations) {
969
- if (types.isIdentifier(decl.id) && types.isNewExpression(decl.init) && types.isIdentifier(decl.init.callee, { name: "Mastra" })) {
970
- mastraVars.add(decl.id.name);
971
- }
972
- }
973
- }
974
- }
975
- };
976
- }
977
- function getStringValue(node) {
978
- if (!node) return null;
979
- if (types.isStringLiteral(node)) {
980
- return node.value;
981
- }
982
- if (types.isTemplateLiteral(node) && node.expressions.length === 0 && node.quasis.length === 1) {
983
- return node.quasis[0]?.value.cooked ?? null;
984
- }
985
- return null;
986
- }
987
- function extractTargetFromProperty(prop) {
988
- if (!types.isObjectProperty(prop)) return null;
989
- const key = prop.key;
990
- if (types.isIdentifier(key, { name: "target" }) || types.isStringLiteral(key) && key.value === "target") {
991
- return getStringValue(prop.value);
992
- }
993
- return null;
994
- }
995
- function isBindingFromPino(path2, identifierName) {
996
- const binding = path2.scope.getBinding(identifierName);
997
- if (!binding) {
998
- return identifierName === "pino";
999
- }
1000
- const bindingPath = binding.path;
1001
- if (bindingPath.isImportDefaultSpecifier()) {
1002
- const importDecl = bindingPath.parentPath;
1003
- if (importDecl?.isImportDeclaration()) {
1004
- return importDecl.node.source.value === "pino";
1005
- }
1006
- }
1007
- if (bindingPath.isImportNamespaceSpecifier()) {
1008
- const importDecl = bindingPath.parentPath;
1009
- if (importDecl?.isImportDeclaration()) {
1010
- return importDecl.node.source.value === "pino";
1011
- }
1012
- }
1013
- if (bindingPath.isImportSpecifier()) {
1014
- const importDecl = bindingPath.parentPath;
1015
- if (importDecl?.isImportDeclaration() && importDecl.node.source.value === "pino") {
1016
- const imported = bindingPath.node.imported;
1017
- if (types.isIdentifier(imported) && imported.name === "default") return true;
1018
- if (types.isStringLiteral(imported) && imported.value === "default") return true;
1019
- }
1020
- return false;
1021
- }
1022
- if (bindingPath.isVariableDeclarator()) {
1023
- const init = bindingPath.node.init;
1024
- if (types.isCallExpression(init) && types.isIdentifier(init.callee, { name: "require" }) && init.arguments.length === 1 && types.isStringLiteral(init.arguments[0]) && init.arguments[0].value === "pino") {
1025
- return true;
1026
- }
1027
- }
1028
- return false;
1029
- }
1030
- function isPinoTransportCall(path2) {
1031
- const callee = path2.node.callee;
1032
- if (!types.isMemberExpression(callee)) return false;
1033
- if (!types.isIdentifier(callee.property, { name: "transport" })) return false;
1034
- if (types.isIdentifier(callee.object)) {
1035
- return isBindingFromPino(path2, callee.object.name);
1036
- }
1037
- if (types.isMemberExpression(callee.object) && types.isIdentifier(callee.object.object) && types.isIdentifier(callee.object.property, { name: "default" })) {
1038
- return isBindingFromPino(path2, callee.object.object.name);
1039
- }
1040
- return false;
1041
- }
1042
- function extractTransportsFromArg(arg) {
1043
- const targets = [];
1044
- if (!types.isObjectExpression(arg)) return targets;
1045
- for (const prop of arg.properties) {
1046
- if (!types.isObjectProperty(prop)) continue;
1047
- const key = prop.key;
1048
- const keyName = types.isIdentifier(key) ? key.name : types.isStringLiteral(key) ? key.value : null;
1049
- if (keyName === "target") {
1050
- const value = getStringValue(prop.value);
1051
- if (value) {
1052
- targets.push(value);
1053
- }
1054
- } else if (keyName === "targets") {
1055
- if (types.isArrayExpression(prop.value)) {
1056
- for (const element of prop.value.elements) {
1057
- if (types.isObjectExpression(element)) {
1058
- for (const innerProp of element.properties) {
1059
- const targetValue = extractTargetFromProperty(innerProp);
1060
- if (targetValue) {
1061
- targets.push(targetValue);
1062
- }
1063
- }
1064
- }
1065
- }
1066
- }
1067
- }
1068
- }
1069
- return targets;
1070
- }
1071
- function detectPinoTransports(transports) {
1072
- return {
1073
- name: "detect-pino-transports",
1074
- visitor: {
1075
- CallExpression(path2) {
1076
- if (!isPinoTransportCall(path2)) return;
1077
- const firstArg = path2.node.arguments[0];
1078
- if (firstArg && !types.isSpreadElement(firstArg)) {
1079
- for (const target of extractTransportsFromArg(firstArg)) {
1080
- transports.add(target);
1081
- }
1082
- }
1083
- }
1084
- }
1085
- };
1086
- }
1087
-
1088
- // src/build/analyze.ts
1089
- function preferDependencyInfo(existing, incoming) {
1090
- return {
1091
- version: incoming.version ?? existing?.version,
1092
- packageSpec: incoming.packageSpec ?? existing?.packageSpec
1093
- };
1094
- }
1095
- async function resolveDependencyInfo(dep, existing, parentPaths) {
1096
- if (existing?.version || existing?.packageSpec) {
1097
- return existing;
1098
- }
1099
- const packageName = getPackageName(dep);
1100
- const packageNames = [...new Set([dep, packageName].filter(Boolean))];
1101
- for (const parentPath of parentPaths) {
1102
- for (const name of packageNames) {
1103
- const metadata = await getPackageMetadata(name, parentPath);
1104
- if (metadata.version || metadata.packageSpec) {
1105
- return preferDependencyInfo(existing, metadata);
1106
- }
1107
- }
1108
- }
1109
- for (const name of packageNames) {
1110
- const metadata = await getPackageMetadata(name);
1111
- if (metadata.version || metadata.packageSpec) {
1112
- return preferDependencyInfo(existing, metadata);
1113
- }
1114
- }
1115
- return existing ?? {};
1116
- }
1117
- function importerParentPaths(importerId, base) {
1118
- if (!importerId || importerId.startsWith("\0") || !isAbsolute(importerId)) {
1119
- return base;
1120
- }
1121
- return [.../* @__PURE__ */ new Set([importerId, ...base])];
1122
- }
1123
- function getLastConcreteModuleId(moduleIds) {
1124
- return moduleIds.findLast((id) => !id.startsWith("\0") && isAbsolute(id));
1125
- }
1126
- function throwExternalDependencyError({
1127
- errorId,
1128
- moduleName,
1129
- packageName,
1130
- messagePrefix
1131
- }) {
1132
- throw new MastraError({
1133
- id: errorId,
1134
- domain: ErrorDomain.DEPLOYER,
1135
- category: ErrorCategory.USER,
1136
- details: {
1137
- importFile: moduleName,
1138
- packageName
1139
- },
1140
- text: `${messagePrefix} \`${packageName}\` to your externals.
1141
-
1142
- export const mastra = new Mastra({
1143
- bundler: {
1144
- externals: ["${packageName}"],
1145
- }
1146
- })`
1147
- });
1148
- }
1149
- function getPackageNameFromBundledModuleName(moduleName) {
1150
- if (moduleName.includes("__")) {
1151
- return moduleName.replaceAll("__", "/");
1152
- }
1153
- const chunks = moduleName.split("-");
1154
- if (!chunks.length) {
1155
- return moduleName;
1156
- }
1157
- if (chunks[0]?.startsWith("@")) {
1158
- return chunks.slice(0, 2).join("/");
1159
- }
1160
- return chunks[0];
1161
- }
1162
- function validateError(err, file, {
1163
- binaryMapData,
1164
- workspaceMap
1165
- }) {
1166
- let moduleName = null;
1167
- let errorConfig = null;
1168
- if (err instanceof ValidationError) {
1169
- const parsedStack = parse(err.stack);
1170
- if (err.type === "TypeError") {
1171
- const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1172
- const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1173
- if (stacktraceFrame) {
1174
- const match = stacktraceFrame.file.match(pkgNameRegex);
1175
- moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1176
- } else {
1177
- moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1178
- }
1179
- errorConfig = {
1180
- id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1181
- messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1182
- };
1183
- } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1184
- moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1185
- const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1186
- errorConfig = {
1187
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1188
- messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1189
- };
1190
- if (moduleName === parentModuleName) {
1191
- return;
1192
- }
1193
- }
1194
- }
1195
- if (err.message.includes("No native build was found")) {
1196
- const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1197
- moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1198
- errorConfig = {
1199
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1200
- messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1201
- };
1202
- }
1203
- if (moduleName && workspaceMap.has(moduleName)) {
1204
- throw new MastraError({
1205
- id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1206
- domain: ErrorDomain.DEPLOYER,
1207
- category: ErrorCategory.USER,
1208
- details: {
1209
- // importFile: moduleName,
1210
- packageName: moduleName
1211
- },
1212
- text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1213
- Error: ${err.stack}`
1214
- });
1215
- }
1216
- if (errorConfig && moduleName) {
1217
- throwExternalDependencyError({
1218
- errorId: errorConfig.id,
1219
- moduleName,
1220
- packageName: moduleName,
1221
- messagePrefix: errorConfig.messagePrefix
1222
- });
1223
- }
1224
- }
1225
- async function validateFile(root, file, {
1226
- binaryMapData,
1227
- moduleResolveMapLocation,
1228
- logger,
1229
- workspaceMap,
1230
- stubbedExternals
1231
- }) {
1232
- try {
1233
- if (!file.isDynamicEntry && file.isEntry) {
1234
- await validate(join(root, file.fileName), {
1235
- moduleResolveMapLocation,
1236
- injectESMShim: false,
1237
- stubbedExternals
1238
- });
1239
- }
1240
- } catch (err) {
1241
- let errorToHandle = err;
1242
- if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1243
- try {
1244
- await validate(join(root, file.fileName), {
1245
- moduleResolveMapLocation,
1246
- injectESMShim: true,
1247
- stubbedExternals
1248
- });
1249
- errorToHandle = null;
1250
- } catch (err2) {
1251
- errorToHandle = err2;
1252
- }
1253
- }
1254
- if (errorToHandle instanceof Error) {
1255
- validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1256
- }
1257
- }
1258
- }
1259
- async function validateOutput({
1260
- output,
1261
- reverseVirtualReferenceMap,
1262
- usedExternals,
1263
- outputDir,
1264
- projectRoot,
1265
- workspaceMap,
1266
- depsVersionInfo
1267
- }, logger) {
1268
- const result = {
1269
- dependencies: /* @__PURE__ */ new Map(),
1270
- externalDependencies: /* @__PURE__ */ new Map(),
1271
- workspaceMap
1272
- };
1273
- const externalMetadataParentPaths = [
1274
- projectRoot,
1275
- ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location)
1276
- ];
1277
- for (const deps of Object.values(usedExternals)) {
1278
- for (const [dep, importerId] of Object.entries(deps)) {
1279
- if (isExternalProtocolImport(dep)) {
1280
- continue;
1281
- }
1282
- const pkgName = getPackageName(dep);
1283
- if (pkgName) {
1284
- const versionInfo = depsVersionInfo.get(dep) || depsVersionInfo.get(pkgName);
1285
- const dependencyInfo = await resolveDependencyInfo(
1286
- dep,
1287
- versionInfo,
1288
- importerParentPaths(importerId, externalMetadataParentPaths)
1289
- );
1290
- result.externalDependencies.set(
1291
- pkgName,
1292
- preferDependencyInfo(result.externalDependencies.get(pkgName), dependencyInfo)
1293
- );
1294
- }
1295
- }
1296
- }
1297
- let binaryMapData = {};
1298
- if (existsSync(join(outputDir, "binary-map.json"))) {
1299
- const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1300
- binaryMapData = JSON.parse(binaryMap);
1301
- }
1302
- for (const file of output) {
1303
- if (file.type === "asset") {
1304
- continue;
1305
- }
1306
- logger.debug("Validating module", { fileName: file.fileName });
1307
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1308
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1309
- }
1310
- await validateFile(projectRoot, file, {
1311
- binaryMapData,
1312
- moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1313
- logger,
1314
- workspaceMap,
1315
- stubbedExternals: [...GLOBAL_EXTERNALS, ...DEPS_TO_IGNORE]
1316
- });
1317
- }
1318
- return result;
1319
- }
1320
- async function analyzeBundle(entries, mastraEntry, {
1321
- outputDir,
1322
- projectRoot,
1323
- platform,
1324
- isDev = false,
1325
- bundlerOptions
1326
- }, logger) {
1327
- const mastraConfig = await readFile(mastraEntry, "utf-8");
1328
- const mastraConfigResult = { hasValidConfig: false };
1329
- await transformAsync(mastraConfig, {
1330
- filename: mastraEntry,
1331
- presets: [import.meta.resolve("@babel/preset-typescript")],
1332
- plugins: [() => checkConfigExport(mastraConfigResult)]
1333
- });
1334
- if (!mastraConfigResult.hasValidConfig) {
1335
- logger.warn("Invalid Mastra config", {
1336
- 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."
1337
- });
1338
- }
1339
- const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1340
- let externalsPreset = false;
1341
- const userExternals = Array.isArray(bundlerOptions?.externals) ? bundlerOptions?.externals : [];
1342
- const userDynamicPackages = bundlerOptions?.dynamicPackages ?? [];
1343
- if (bundlerOptions?.externals === true) {
1344
- externalsPreset = true;
1345
- }
1346
- let index = 0;
1347
- const depsToOptimize = /* @__PURE__ */ new Map();
1348
- const allExternals = [...GLOBAL_EXTERNALS, ...userExternals].filter(Boolean);
1349
- const detectedPinoTransports = /* @__PURE__ */ new Set();
1350
- logger.info("Analyzing dependencies...");
1351
- const allUsedExternals = /* @__PURE__ */ new Map();
1352
- const analyzeCache = /* @__PURE__ */ new Map();
1353
- for (const entry of entries) {
1354
- const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1355
- const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
1356
- logger,
1357
- sourcemapEnabled: bundlerOptions?.enableSourcemap ?? false,
1358
- workspaceMap,
1359
- projectRoot,
1360
- shouldCheckTransitiveDependencies: true,
1361
- analyzeCache
1362
- });
1363
- transformSync(analyzeResult.output.code, {
1364
- filename: "pino-detection.js",
1365
- plugins: [() => detectPinoTransports(detectedPinoTransports)],
1366
- configFile: false,
1367
- babelrc: false,
1368
- code: false
1369
- });
1370
- await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1371
- for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1372
- const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1373
- if (isPartOfExternals || externalsPreset && !metadata.isWorkspace) {
1374
- const pkgName = getPackageName(dep);
1375
- if (pkgName) {
1376
- allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), metadata));
1377
- }
1378
- continue;
1379
- }
1380
- if (depsToOptimize.has(dep)) {
1381
- const existingEntry = depsToOptimize.get(dep);
1382
- depsToOptimize.set(dep, {
1383
- ...existingEntry,
1384
- version: metadata.version ?? existingEntry.version,
1385
- packageSpec: metadata.packageSpec ?? existingEntry.packageSpec,
1386
- exports: [.../* @__PURE__ */ new Set([...existingEntry.exports, ...metadata.exports])]
1387
- });
1388
- } else {
1389
- depsToOptimize.set(dep, metadata);
1390
- }
1391
- }
1392
- }
1393
- const depsVersionInfo = /* @__PURE__ */ new Map();
1394
- for (const [dep, metadata] of depsToOptimize.entries()) {
1395
- const pkgName = getPackageName(dep);
1396
- if (pkgName && (metadata.version || metadata.packageSpec)) {
1397
- depsVersionInfo.set(pkgName, preferDependencyInfo(depsVersionInfo.get(pkgName), metadata));
1398
- }
1399
- if (metadata.version || metadata.packageSpec) {
1400
- depsVersionInfo.set(dep, preferDependencyInfo(depsVersionInfo.get(dep), metadata));
1401
- }
1402
- }
1403
- if (isDev || externalsPreset) {
1404
- for (const [dep, metadata] of depsToOptimize.entries()) {
1405
- if (!metadata.isWorkspace) {
1406
- depsToOptimize.delete(dep);
1407
- }
1408
- }
1409
- }
1410
- const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1411
- logger.info("Optimizing dependencies...");
1412
- logger.debug("Sorted dependencies", { deps: sortedDeps });
1413
- const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1414
- bundlerOptions: {
1415
- ...bundlerOptions,
1416
- externals: bundlerOptions?.externals ?? allExternals,
1417
- isDev
1418
- },
1419
- projectRoot,
1420
- workspaceRoot,
1421
- workspaceMap,
1422
- platform
1423
- });
1424
- const relativeWorkspaceFolderPaths = Array.from(workspaceMap.values()).map(
1425
- (pkgInfo) => slash(relative(workspaceRoot || projectRoot, pkgInfo.location))
1426
- );
1427
- for (const o of output) {
1428
- if (o.type === "asset") {
1429
- continue;
1430
- }
1431
- const importerId = getLastConcreteModuleId(o.moduleIds);
1432
- for (const i of o.imports) {
1433
- if (isBuiltinModule(i)) {
1434
- continue;
1435
- }
1436
- if (i.startsWith(".") || i.startsWith("/")) {
1437
- continue;
1438
- }
1439
- if (!isBareModuleSpecifier(i) || isExternalProtocolImport(i)) {
1440
- continue;
1441
- }
1442
- if (relativeWorkspaceFolderPaths.some((workspacePath) => i.startsWith(workspacePath))) {
1443
- continue;
1444
- }
1445
- const pkgName = getPackageName(i);
1446
- if (pkgName && workspaceMap.has(pkgName)) {
1447
- continue;
1448
- }
1449
- if (pkgName) {
1450
- const versionInfo = depsVersionInfo.get(i) || depsVersionInfo.get(pkgName);
1451
- const dependencyInfo = await resolveDependencyInfo(
1452
- i,
1453
- versionInfo,
1454
- importerParentPaths(importerId, [
1455
- projectRoot,
1456
- ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location)
1457
- ])
1458
- );
1459
- allUsedExternals.set(pkgName, preferDependencyInfo(allUsedExternals.get(pkgName), dependencyInfo));
1460
- }
1461
- }
1462
- }
1463
- const result = await validateOutput(
1464
- {
1465
- output,
1466
- reverseVirtualReferenceMap: fileNameToDependencyMap,
1467
- usedExternals,
1468
- outputDir,
1469
- projectRoot: workspaceRoot || projectRoot,
1470
- workspaceMap,
1471
- depsVersionInfo
1472
- },
1473
- logger
1474
- );
1475
- const mergedExternalDeps = new Map(result.externalDependencies);
1476
- for (const [dep, info] of allUsedExternals) {
1477
- if (isExternalProtocolImport(dep)) {
1478
- continue;
1479
- }
1480
- mergedExternalDeps.set(dep, preferDependencyInfo(mergedExternalDeps.get(dep), info));
1481
- }
1482
- const externalMetadataParentPaths = [
1483
- projectRoot,
1484
- ...Array.from(workspaceMap.values()).map((pkgInfo) => pkgInfo.location),
1485
- // Last resort: resolve from the deployer's own installed location. Some externals are
1486
- // discovered inside externalized packages (e.g. optional dynamic imports like
1487
- // `import('typescript')` in @mastra/core) without being installed in the user's project.
1488
- import.meta.dirname
1489
- ];
1490
- for (const [dep, info] of mergedExternalDeps) {
1491
- if (!info.version && !info.packageSpec) {
1492
- mergedExternalDeps.set(dep, await resolveDependencyInfo(dep, info, externalMetadataParentPaths));
1493
- }
1494
- }
1495
- for (const transport of detectedPinoTransports) {
1496
- if (!mergedExternalDeps.has(transport)) {
1497
- mergedExternalDeps.set(transport, await resolveDependencyInfo(transport, void 0, externalMetadataParentPaths));
1498
- }
1499
- }
1500
- for (const pkg2 of userDynamicPackages) {
1501
- if (!mergedExternalDeps.has(pkg2)) {
1502
- mergedExternalDeps.set(pkg2, await resolveDependencyInfo(pkg2, void 0, externalMetadataParentPaths));
1503
- }
1504
- }
1505
- return {
1506
- ...result,
1507
- externalDependencies: mergedExternalDeps,
1508
- ...mastraConfigResult.projectType ? { projectType: mastraConfigResult.projectType } : {}
1509
- };
1510
- }
1511
-
1512
- export { aliasHono, analyzeBundle, checkConfigExport, getWorkspaceInformation };
1513
- //# sourceMappingURL=chunk-FQHUOYYL.js.map
1514
- //# sourceMappingURL=chunk-FQHUOYYL.js.map