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