@mastra/deployer 0.24.7-alpha.2 → 0.24.7-alpha.4

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 (68) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/build/analyze/bundleExternals.d.ts.map +1 -1
  3. package/dist/build/analyze.cjs +2 -2
  4. package/dist/build/analyze.d.ts +1 -1
  5. package/dist/build/analyze.d.ts.map +1 -1
  6. package/dist/build/analyze.js +1 -1
  7. package/dist/build/bundler.cjs +3 -3
  8. package/dist/build/bundler.d.ts.map +1 -1
  9. package/dist/build/bundler.js +1 -1
  10. package/dist/build/index.cjs +12 -12
  11. package/dist/build/index.js +4 -4
  12. package/dist/build/plugins/module-resolve-map.d.ts +3 -0
  13. package/dist/build/plugins/module-resolve-map.d.ts.map +1 -0
  14. package/dist/build/plugins/node-gyp-detector.d.ts +3 -0
  15. package/dist/build/plugins/node-gyp-detector.d.ts.map +1 -0
  16. package/dist/build/plugins/subpath-externals-resolver.d.ts +3 -0
  17. package/dist/build/plugins/subpath-externals-resolver.d.ts.map +1 -0
  18. package/dist/build/plugins/tsconfig-paths.d.ts +8 -0
  19. package/dist/build/plugins/tsconfig-paths.d.ts.map +1 -1
  20. package/dist/build/utils.d.ts +1 -0
  21. package/dist/build/utils.d.ts.map +1 -1
  22. package/dist/bundler/index.cjs +2 -2
  23. package/dist/bundler/index.d.ts +1 -1
  24. package/dist/bundler/index.js +1 -1
  25. package/dist/{chunk-53B6GOCH.cjs → chunk-3EKA4UZF.cjs} +13 -21
  26. package/dist/chunk-3EKA4UZF.cjs.map +1 -0
  27. package/dist/chunk-3GJSIS6L.cjs +69 -0
  28. package/dist/chunk-3GJSIS6L.cjs.map +1 -0
  29. package/dist/{chunk-7VIDVYTY.js → chunk-7US52JKZ.js} +6 -14
  30. package/dist/chunk-7US52JKZ.js.map +1 -0
  31. package/dist/{chunk-K7JCMIZW.cjs → chunk-D2YCDWUL.cjs} +17 -16
  32. package/dist/chunk-D2YCDWUL.cjs.map +1 -0
  33. package/dist/{chunk-MYLM6HSI.js → chunk-FHL5J54L.js} +5 -4
  34. package/dist/chunk-FHL5J54L.js.map +1 -0
  35. package/dist/chunk-NEGQTTJS.js +62 -0
  36. package/dist/chunk-NEGQTTJS.js.map +1 -0
  37. package/dist/{chunk-6R73ZVZX.cjs → chunk-Q5FR6PUS.cjs} +441 -166
  38. package/dist/chunk-Q5FR6PUS.cjs.map +1 -0
  39. package/dist/{chunk-KLIBX4WB.js → chunk-RVBHN7SB.js} +6 -5
  40. package/dist/chunk-RVBHN7SB.js.map +1 -0
  41. package/dist/{chunk-UWCXK7X6.cjs → chunk-VQLBK6M5.cjs} +15 -14
  42. package/dist/chunk-VQLBK6M5.cjs.map +1 -0
  43. package/dist/{chunk-PHZK4P6J.js → chunk-X5SEG2FP.js} +427 -151
  44. package/dist/chunk-X5SEG2FP.js.map +1 -0
  45. package/dist/{chunk-FHZKTDSF.cjs → chunk-XJ42VWDB.cjs} +5 -5
  46. package/dist/{chunk-FHZKTDSF.cjs.map → chunk-XJ42VWDB.cjs.map} +1 -1
  47. package/dist/{chunk-KEU3VV3H.js → chunk-ZFUUBCEJ.js} +3 -3
  48. package/dist/{chunk-KEU3VV3H.js.map → chunk-ZFUUBCEJ.js.map} +1 -1
  49. package/dist/index.cjs +5 -5
  50. package/dist/index.js +2 -2
  51. package/dist/server/handlers/routes/scores/handlers.d.ts +4 -0
  52. package/dist/server/handlers/routes/scores/handlers.d.ts.map +1 -1
  53. package/dist/validator/custom-resolver.cjs +20 -12
  54. package/dist/validator/custom-resolver.cjs.map +1 -1
  55. package/dist/validator/custom-resolver.d.ts.map +1 -1
  56. package/dist/validator/custom-resolver.js +18 -10
  57. package/dist/validator/custom-resolver.js.map +1 -1
  58. package/dist/validator/validate.d.ts +15 -1
  59. package/dist/validator/validate.d.ts.map +1 -1
  60. package/package.json +7 -7
  61. package/dist/chunk-53B6GOCH.cjs.map +0 -1
  62. package/dist/chunk-6R73ZVZX.cjs.map +0 -1
  63. package/dist/chunk-7VIDVYTY.js.map +0 -1
  64. package/dist/chunk-K7JCMIZW.cjs.map +0 -1
  65. package/dist/chunk-KLIBX4WB.js.map +0 -1
  66. package/dist/chunk-MYLM6HSI.js.map +0 -1
  67. package/dist/chunk-PHZK4P6J.js.map +0 -1
  68. package/dist/chunk-UWCXK7X6.cjs.map +0 -1
@@ -1,16 +1,16 @@
1
+ import { slash, isDependencyPartOfPackage, getPackageRootPath, getPackageName, getCompiledDepCachePath, rollupSafeName } from './chunk-NEGQTTJS.js';
1
2
  import * as babel from '@babel/core';
2
3
  import babel__default from '@babel/core';
3
4
  import fs, { existsSync } from 'fs';
4
5
  import { readFile, writeFile } from 'fs/promises';
5
6
  import * as path2 from 'path';
6
- import path2__default, { dirname, join, normalize, relative, basename as basename$1 } from 'path';
7
+ import path2__default, { dirname, join, normalize, basename as basename$1 } from 'path';
7
8
  import { spawn as spawn$1 } from 'child_process';
8
- import { getPackageInfo } from 'local-pkg';
9
- import { pathToFileURL, fileURLToPath } from 'url';
10
9
  import { rollup } from 'rollup';
11
10
  import originalEsbuild from 'rollup-plugin-esbuild';
12
11
  import commonjs from '@rollup/plugin-commonjs';
13
12
  import resolveFrom2 from 'resolve-from';
13
+ import stripJsonComments from 'strip-json-comments';
14
14
  import { createHandler } from 'typescript-paths';
15
15
  import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin';
16
16
  import json from '@rollup/plugin-json';
@@ -18,90 +18,27 @@ import * as pkg from 'empathic/package';
18
18
  import { createWorkspacesCache, findWorkspaces, findWorkspacesRoot } from 'find-workspaces';
19
19
  import { noopLogger } from '@mastra/core/logger';
20
20
  import virtual from '@rollup/plugin-virtual';
21
+ import { fileURLToPath, pathToFileURL } from 'url';
21
22
  import { builtinModules } from 'module';
22
23
  import nodeResolve from '@rollup/plugin-node-resolve';
23
24
  import originalEsmShim from '@rollup/plugin-esm-shim';
24
25
  import { basename } from 'path/posix';
25
26
  import * as resolve from 'resolve.exports';
27
+ import { getPackageInfo } from 'local-pkg';
26
28
  import { MastraBaseError, ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
27
29
 
28
- // src/build/analyze.ts
29
- function getPackageName(id) {
30
- const parts = id.split("/");
31
- if (id.startsWith("@")) {
32
- return parts.slice(0, 2).join("/");
30
+ var ValidationError = class extends Error {
31
+ type;
32
+ stack;
33
+ constructor(args) {
34
+ super(args.message);
35
+ this.type = args.type;
36
+ this.stack = args.stack;
33
37
  }
34
- return parts[0];
35
- }
36
- async function getPackageRootPath(packageName, parentPath) {
37
- let rootPath;
38
- try {
39
- let options = void 0;
40
- if (parentPath) {
41
- if (!parentPath.startsWith("file://")) {
42
- parentPath = pathToFileURL(parentPath).href;
43
- }
44
- options = {
45
- paths: [parentPath]
46
- };
47
- }
48
- const pkg2 = await getPackageInfo(packageName, options);
49
- rootPath = pkg2?.rootPath ?? null;
50
- } catch (e) {
51
- rootPath = null;
52
- }
53
- return rootPath;
54
- }
55
- function getCompiledDepCachePath(rootPath, packageName) {
56
- return slash(join(rootPath, "node_modules", ".cache", packageName));
57
- }
58
- function slash(path3) {
59
- const isExtendedLengthPath = path3.startsWith("\\\\?\\");
60
- if (isExtendedLengthPath) {
61
- return path3;
62
- }
63
- return path3.replaceAll("\\", "/");
64
- }
65
- function rollupSafeName(name, rootDir) {
66
- const rel = relative(rootDir, name);
67
- let entry = slash(rel);
68
- entry = entry.replace(/^(\.\.\/)+/, "");
69
- entry = entry.replace(/^\/+/, "");
70
- entry = entry.replace(/^[A-Za-z]:\//, "");
71
- if (!entry) {
72
- entry = slash(basename$1(name));
73
- }
74
- return entry;
75
- }
76
- var NATIVE_BINDING_LOADERS = [
77
- "node-gyp-build",
78
- "prebuild-install",
79
- "bindings",
80
- "node-addon-api",
81
- "node-pre-gyp",
82
- "nan"
83
- // Native Abstractions for Node.js
84
- ];
85
- function findNativePackageModule(moduleIds) {
86
- return moduleIds.find((id) => {
87
- if (id.startsWith("\0")) {
88
- return false;
89
- }
90
- if (!id.includes("/node_modules/")) {
91
- return false;
92
- }
93
- for (const loader of NATIVE_BINDING_LOADERS) {
94
- if (id.includes(`/${loader}/`) || id.includes(`/${loader}@`)) {
95
- return false;
96
- }
97
- }
98
- return true;
99
- });
100
- }
101
-
102
- // src/validator/validate.ts
38
+ };
103
39
  function spawn(command, args = [], options = {}) {
104
40
  return new Promise((resolve2, reject) => {
41
+ let validationError = null;
105
42
  const childProcess = spawn$1(command, args, {
106
43
  // stdio: 'inherit',
107
44
  ...options
@@ -111,28 +48,63 @@ function spawn(command, args = [], options = {}) {
111
48
  });
112
49
  let stderr = "";
113
50
  childProcess.stderr?.on("data", (message) => {
114
- stderr += message;
51
+ try {
52
+ validationError = JSON.parse(message.toString());
53
+ } catch {
54
+ stderr += message;
55
+ }
115
56
  });
116
57
  childProcess.on("close", (code) => {
117
58
  if (code === 0) {
118
59
  resolve2();
119
60
  } else {
120
- reject(new Error(stderr));
61
+ if (validationError) {
62
+ reject(new ValidationError(validationError));
63
+ } else {
64
+ reject(new Error(stderr));
65
+ }
121
66
  }
122
67
  });
123
68
  });
124
69
  }
125
- function validate(file) {
70
+ function validate(file, { injectESMShim = false, moduleResolveMapLocation }) {
71
+ let prefixCode = "";
72
+ if (injectESMShim) {
73
+ prefixCode = `import { fileURLToPath } from 'url';
74
+ import { dirname } from 'path';
75
+
76
+ globalThis.__filename = fileURLToPath(import.meta.url);
77
+ globalThis.__dirname = dirname(__filename);
78
+ `;
79
+ }
80
+ function errorHandler(err) {
81
+ console.error(
82
+ JSON.stringify({
83
+ type: err.name,
84
+ message: err.message,
85
+ stack: err.stack
86
+ })
87
+ );
88
+ process.exit(1);
89
+ }
126
90
  return spawn(
127
- "node",
91
+ process.execPath,
128
92
  [
129
93
  "--import",
130
94
  import.meta.resolve("@mastra/deployer/loader"),
131
95
  "--input-type=module",
96
+ "--enable-source-maps",
132
97
  "-e",
133
- `import('file://${slash(file)}')`
98
+ `${prefixCode};import('file://${slash(file)}').catch(err => {
99
+ ${errorHandler.toString()}
100
+ errorHandler(err);
101
+ })`.replaceAll(/\n/g, "")
134
102
  ],
135
103
  {
104
+ env: {
105
+ ...process.env,
106
+ MODULE_MAP: `${moduleResolveMapLocation}`
107
+ },
136
108
  cwd: dirname(file)
137
109
  }
138
110
  );
@@ -227,6 +199,15 @@ function esbuild(options = {}) {
227
199
  });
228
200
  }
229
201
  var PLUGIN_NAME = "tsconfig-paths";
202
+ function hasPaths(tsConfigPath) {
203
+ try {
204
+ const content = fs.readFileSync(tsConfigPath, "utf8");
205
+ const config = JSON.parse(stripJsonComments(content));
206
+ return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
230
211
  function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
231
212
  const handlerCache = /* @__PURE__ */ new Map();
232
213
  function findTsConfigForFile(filePath) {
@@ -249,14 +230,6 @@ function tsConfigPaths({ tsConfigPath, respectCoreModule, localResolve } = {}) {
249
230
  }
250
231
  return null;
251
232
  }
252
- function hasPaths(tsConfigPath2) {
253
- try {
254
- const config = JSON.parse(fs.readFileSync(tsConfigPath2, "utf8"));
255
- return !!(config.compilerOptions?.paths && Object.keys(config.compilerOptions.paths).length > 0);
256
- } catch {
257
- return false;
258
- }
259
- }
260
233
  function getHandlerForFile(filePath) {
261
234
  if (tsConfigPath && typeof tsConfigPath === "string") {
262
235
  if (!handlerCache.has(tsConfigPath)) {
@@ -897,6 +870,114 @@ function aliasHono() {
897
870
  }
898
871
  };
899
872
  }
873
+
874
+ // src/build/plugins/subpath-externals-resolver.ts
875
+ function subpathExternalsResolver(externals) {
876
+ return {
877
+ name: "subpath-externals-resolver",
878
+ resolveId(id) {
879
+ if (id.startsWith(".") || id.startsWith("/")) {
880
+ return null;
881
+ }
882
+ const isPartOfExternals = externals.some((external) => isDependencyPartOfPackage(id, external));
883
+ if (isPartOfExternals) {
884
+ return {
885
+ id,
886
+ external: true
887
+ };
888
+ }
889
+ }
890
+ };
891
+ }
892
+ function nodeGypDetector() {
893
+ const modulesToTrack = /* @__PURE__ */ new Set();
894
+ const modulesToTrackPackageInfo = /* @__PURE__ */ new Map();
895
+ return {
896
+ name: "node-gyp-build-detector",
897
+ moduleParsed(info) {
898
+ if (!info.meta?.commonjs?.requires?.length) {
899
+ return;
900
+ }
901
+ const hasNodeGypBuild = info.meta.commonjs.requires.some(
902
+ (m) => m?.resolved?.id.endsWith("node-gyp-build/index.js")
903
+ );
904
+ if (!hasNodeGypBuild) {
905
+ return;
906
+ }
907
+ modulesToTrack.add(info.id);
908
+ modulesToTrackPackageInfo.set(info.id, getPackageInfo(info.id));
909
+ },
910
+ async generateBundle(options, bundle) {
911
+ const binaryMapByChunk = /* @__PURE__ */ new Map();
912
+ for (const [fileName, chunk] of Object.entries(bundle)) {
913
+ if (chunk.type === "chunk") {
914
+ for (const moduleId of chunk.moduleIds) {
915
+ if (modulesToTrackPackageInfo.has(moduleId)) {
916
+ const pkgInfo = await modulesToTrackPackageInfo.get(moduleId);
917
+ if (!binaryMapByChunk.has(fileName)) {
918
+ binaryMapByChunk.set(fileName, /* @__PURE__ */ new Set());
919
+ }
920
+ if (pkgInfo?.packageJson?.name) {
921
+ binaryMapByChunk.get(fileName).add(pkgInfo.packageJson.name);
922
+ }
923
+ }
924
+ }
925
+ }
926
+ }
927
+ const binaryMapJson = Object.fromEntries(
928
+ Array.from(binaryMapByChunk.entries()).map(([key, value]) => [key, Array.from(value)])
929
+ );
930
+ this.emitFile({
931
+ type: "asset",
932
+ name: "binary-map.json",
933
+ source: `${JSON.stringify(binaryMapJson, null, 2)}`
934
+ });
935
+ }
936
+ };
937
+ }
938
+ function moduleResolveMap(externals, projectRoot) {
939
+ const importMap = /* @__PURE__ */ new Map();
940
+ return {
941
+ name: "module-resolve-map",
942
+ moduleParsed(info) {
943
+ if (info.importedIds.length === 0 || !info.id) {
944
+ return;
945
+ }
946
+ for (const importedId of info.importedIds) {
947
+ for (const external of externals) {
948
+ if (isDependencyPartOfPackage(importedId, external)) {
949
+ importMap.set(external, info.id);
950
+ }
951
+ }
952
+ }
953
+ },
954
+ async generateBundle(options, bundle) {
955
+ const resolveMap = /* @__PURE__ */ new Map();
956
+ for (const [fileName, chunk] of Object.entries(bundle)) {
957
+ if (chunk.type === "chunk") {
958
+ for (const [external, resolvedFrom] of importMap) {
959
+ if (chunk.moduleIds.includes(resolvedFrom)) {
960
+ const fullPath = pathToFileURL(slash(join(projectRoot, fileName))).toString();
961
+ const innerMap = resolveMap.get(fullPath) || /* @__PURE__ */ new Map();
962
+ innerMap.set(external, pathToFileURL(slash(resolvedFrom)).toString());
963
+ resolveMap.set(fullPath, innerMap);
964
+ }
965
+ }
966
+ }
967
+ }
968
+ const resolveMapJson = Object.fromEntries(
969
+ Array.from(resolveMap.entries()).map(([key, value]) => [key, Object.fromEntries(value.entries())])
970
+ );
971
+ this.emitFile({
972
+ type: "asset",
973
+ name: "module-resolve-map.json",
974
+ source: `${JSON.stringify(resolveMapJson, null, 2)}`
975
+ });
976
+ }
977
+ };
978
+ }
979
+
980
+ // src/build/analyze/bundleExternals.ts
900
981
  function prepareEntryFileName(name, rootDir) {
901
982
  return rollupSafeName(name, rootDir);
902
983
  }
@@ -962,7 +1043,8 @@ async function getInputPlugins2(virtualDependencies, {
962
1043
  transpilePackages,
963
1044
  workspaceMap,
964
1045
  bundlerOptions,
965
- rootDir
1046
+ rootDir,
1047
+ externals
966
1048
  }) {
967
1049
  const transpilePackagesMap = /* @__PURE__ */ new Map();
968
1050
  for (const pkg2 of transpilePackages) {
@@ -983,6 +1065,7 @@ async function getInputPlugins2(virtualDependencies, {
983
1065
  {}
984
1066
  )
985
1067
  ),
1068
+ subpathExternalsResolver(externals),
986
1069
  transpilePackagesMap.size ? esbuild({
987
1070
  format: "esm",
988
1071
  include: [...transpilePackagesMap.values()].map((p) => {
@@ -1011,7 +1094,8 @@ async function getInputPlugins2(virtualDependencies, {
1011
1094
  if (!resolvedPath) {
1012
1095
  resolvedPath = pkgJson.main ?? "index.js";
1013
1096
  }
1014
- return await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1097
+ const resolved = await this.resolve(path2.posix.join(packageRootPath, resolvedPath), importer, options);
1098
+ return resolved;
1015
1099
  }
1016
1100
  } : null,
1017
1101
  optimizeLodashImports({
@@ -1030,6 +1114,8 @@ async function getInputPlugins2(virtualDependencies, {
1030
1114
  // hono is imported from deployer, so we need to resolve from here instead of the project root
1031
1115
  aliasHono(),
1032
1116
  json(),
1117
+ nodeGypDetector(),
1118
+ moduleResolveMap(externals, rootDir),
1033
1119
  {
1034
1120
  name: "not-found-resolver",
1035
1121
  resolveId: {
@@ -1087,12 +1173,13 @@ async function buildExternalDependencies(virtualDependencies, {
1087
1173
  {}
1088
1174
  ),
1089
1175
  external: externals,
1090
- treeshake: "safest",
1176
+ treeshake: bundlerOptions.isDev ? false : "safest",
1091
1177
  plugins: getInputPlugins2(virtualDependencies, {
1092
1178
  transpilePackages: packagesToTranspile,
1093
1179
  workspaceMap,
1094
1180
  bundlerOptions,
1095
- rootDir
1181
+ rootDir,
1182
+ externals
1096
1183
  })
1097
1184
  });
1098
1185
  const outputDirRelative = prepareEntryFileName(outputDir, rootDir);
@@ -1100,6 +1187,8 @@ async function buildExternalDependencies(virtualDependencies, {
1100
1187
  format: "esm",
1101
1188
  dir: rootDir,
1102
1189
  entryFileNames: "[name].mjs",
1190
+ // used to get the filename of the actual error
1191
+ sourcemap: true,
1103
1192
  /**
1104
1193
  * Rollup creates chunks for common dependencies, but these chunks are by default written to the root directory instead of respecting the entryFileNames structure.
1105
1194
  * So we want to write them to the `.mastra/output` folder as well.
@@ -1137,6 +1226,7 @@ async function buildExternalDependencies(virtualDependencies, {
1137
1226
  }
1138
1227
  return `${outputDirRelative}/[name].mjs`;
1139
1228
  },
1229
+ assetFileNames: `${outputDirRelative}/[name][extname]`,
1140
1230
  hoistTransitiveImports: false
1141
1231
  });
1142
1232
  await bundler.close();
@@ -1145,7 +1235,7 @@ async function buildExternalDependencies(virtualDependencies, {
1145
1235
  function findExternalImporter(module, external, allOutputs) {
1146
1236
  const capturedFiles = /* @__PURE__ */ new Set();
1147
1237
  for (const id of module.imports) {
1148
- if (id === external) {
1238
+ if (isDependencyPartOfPackage(id, external)) {
1149
1239
  return module;
1150
1240
  } else {
1151
1241
  if (id.endsWith(".mjs")) {
@@ -1191,7 +1281,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1191
1281
  isDev
1192
1282
  }
1193
1283
  });
1194
- const moduleResolveMap = /* @__PURE__ */ new Map();
1284
+ const moduleResolveMap2 = /* @__PURE__ */ new Map();
1195
1285
  const filteredChunks = output.filter((o) => o.type === "chunk");
1196
1286
  for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
1197
1287
  for (const external of allExternals) {
@@ -1201,10 +1291,10 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1201
1291
  const importer = findExternalImporter(o, external, filteredChunks);
1202
1292
  if (importer) {
1203
1293
  const fullPath = path2.join(workspaceRoot || projectRoot, importer.fileName);
1204
- let innerMap = moduleResolveMap.get(fullPath);
1294
+ let innerMap = moduleResolveMap2.get(fullPath);
1205
1295
  if (!innerMap) {
1206
1296
  innerMap = /* @__PURE__ */ new Map();
1207
- moduleResolveMap.set(fullPath, innerMap);
1297
+ moduleResolveMap2.set(fullPath, innerMap);
1208
1298
  }
1209
1299
  if (importer.moduleIds.length) {
1210
1300
  innerMap.set(
@@ -1216,7 +1306,7 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1216
1306
  }
1217
1307
  }
1218
1308
  const usedExternals = /* @__PURE__ */ Object.create(null);
1219
- for (const [fullPath, innerMap] of moduleResolveMap) {
1309
+ for (const [fullPath, innerMap] of moduleResolveMap2) {
1220
1310
  const innerObj = /* @__PURE__ */ Object.create(null);
1221
1311
  for (const [external, value] of innerMap) {
1222
1312
  innerObj[external] = value;
@@ -1225,6 +1315,108 @@ async function bundleExternals(depsToOptimize, outputDir, options) {
1225
1315
  }
1226
1316
  return { output, fileNameToDependencyMap, usedExternals };
1227
1317
  }
1318
+
1319
+ // ../../node_modules/.pnpm/stacktrace-parser@0.1.11/node_modules/stacktrace-parser/dist/stack-trace-parser.esm.js
1320
+ var UNKNOWN_FUNCTION = "<unknown>";
1321
+ function parse(stackString) {
1322
+ var lines = stackString.split("\n");
1323
+ return lines.reduce(function(stack, line) {
1324
+ var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
1325
+ if (parseResult) {
1326
+ stack.push(parseResult);
1327
+ }
1328
+ return stack;
1329
+ }, []);
1330
+ }
1331
+ var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1332
+ var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1333
+ function parseChrome(line) {
1334
+ var parts = chromeRe.exec(line);
1335
+ if (!parts) {
1336
+ return null;
1337
+ }
1338
+ var isNative = parts[2] && parts[2].indexOf("native") === 0;
1339
+ var isEval = parts[2] && parts[2].indexOf("eval") === 0;
1340
+ var submatch = chromeEvalRe.exec(parts[2]);
1341
+ if (isEval && submatch != null) {
1342
+ parts[2] = submatch[1];
1343
+ parts[3] = submatch[2];
1344
+ parts[4] = submatch[3];
1345
+ }
1346
+ return {
1347
+ file: !isNative ? parts[2] : null,
1348
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1349
+ arguments: isNative ? [parts[2]] : [],
1350
+ lineNumber: parts[3] ? +parts[3] : null,
1351
+ column: parts[4] ? +parts[4] : null
1352
+ };
1353
+ }
1354
+ var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1355
+ function parseWinjs(line) {
1356
+ var parts = winjsRe.exec(line);
1357
+ if (!parts) {
1358
+ return null;
1359
+ }
1360
+ return {
1361
+ file: parts[2],
1362
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1363
+ arguments: [],
1364
+ lineNumber: +parts[3],
1365
+ column: parts[4] ? +parts[4] : null
1366
+ };
1367
+ }
1368
+ var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
1369
+ var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1370
+ function parseGecko(line) {
1371
+ var parts = geckoRe.exec(line);
1372
+ if (!parts) {
1373
+ return null;
1374
+ }
1375
+ var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1376
+ var submatch = geckoEvalRe.exec(parts[3]);
1377
+ if (isEval && submatch != null) {
1378
+ parts[3] = submatch[1];
1379
+ parts[4] = submatch[2];
1380
+ parts[5] = null;
1381
+ }
1382
+ return {
1383
+ file: parts[3],
1384
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1385
+ arguments: parts[2] ? parts[2].split(",") : [],
1386
+ lineNumber: parts[4] ? +parts[4] : null,
1387
+ column: parts[5] ? +parts[5] : null
1388
+ };
1389
+ }
1390
+ var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
1391
+ function parseJSC(line) {
1392
+ var parts = javaScriptCoreRe.exec(line);
1393
+ if (!parts) {
1394
+ return null;
1395
+ }
1396
+ return {
1397
+ file: parts[3],
1398
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1399
+ arguments: [],
1400
+ lineNumber: +parts[4],
1401
+ column: parts[5] ? +parts[5] : null
1402
+ };
1403
+ }
1404
+ var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1405
+ function parseNode(line) {
1406
+ var parts = nodeRe.exec(line);
1407
+ if (!parts) {
1408
+ return null;
1409
+ }
1410
+ return {
1411
+ file: parts[2],
1412
+ methodName: parts[1] || UNKNOWN_FUNCTION,
1413
+ arguments: [],
1414
+ lineNumber: +parts[3],
1415
+ column: parts[4] ? +parts[4] : null
1416
+ };
1417
+ }
1418
+
1419
+ // src/build/analyze.ts
1228
1420
  function throwExternalDependencyError({
1229
1421
  errorId,
1230
1422
  moduleName,
@@ -1248,6 +1440,110 @@ export const mastra = new Mastra({
1248
1440
  })`
1249
1441
  });
1250
1442
  }
1443
+ function getPackageNameFromBundledModuleName(moduleName) {
1444
+ const chunks = moduleName.split("-");
1445
+ if (!chunks.length) {
1446
+ return moduleName;
1447
+ }
1448
+ if (chunks[0]?.startsWith("@")) {
1449
+ return chunks.slice(0, 2).join("/");
1450
+ }
1451
+ return chunks[0];
1452
+ }
1453
+ function validateError(err, file, {
1454
+ binaryMapData,
1455
+ workspaceMap
1456
+ }) {
1457
+ let moduleName = null;
1458
+ let errorConfig = null;
1459
+ if (err instanceof ValidationError) {
1460
+ const parsedStack = parse(err.stack);
1461
+ if (err.type === "TypeError") {
1462
+ const pkgNameRegex = /.*node_modules\/([^\/]+)\//;
1463
+ const stacktraceFrame = parsedStack.find((frame) => frame.file && pkgNameRegex.test(frame.file));
1464
+ if (stacktraceFrame) {
1465
+ const match = stacktraceFrame.file.match(pkgNameRegex);
1466
+ moduleName = match?.[1] ?? getPackageNameFromBundledModuleName(basename$1(file.name));
1467
+ } else {
1468
+ moduleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1469
+ }
1470
+ errorConfig = {
1471
+ id: "DEPLOYER_ANALYZE_TYPE_ERROR",
1472
+ messagePrefix: `Mastra wasn't able to bundle "${moduleName}", might be an older commonJS module. Please add`
1473
+ };
1474
+ } else if (err.stack?.includes?.("[ERR_MODULE_NOT_FOUND]")) {
1475
+ moduleName = err.message.match(/Cannot find package '([^']+)'/)?.[1];
1476
+ const parentModuleName = getPackageNameFromBundledModuleName(basename$1(file.name));
1477
+ errorConfig = {
1478
+ id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1479
+ messagePrefix: `Mastra wasn't able to build your project, We couldn't load "${moduleName}" from "${parentModuleName}". Make sure "${moduleName}" is installed or add`
1480
+ };
1481
+ if (moduleName === parentModuleName) {
1482
+ return;
1483
+ }
1484
+ }
1485
+ }
1486
+ if (err.message.includes("No native build was found")) {
1487
+ const pkgName = getPackageNameFromBundledModuleName(basename$1(file.name));
1488
+ moduleName = binaryMapData[file.fileName]?.[0] ?? pkgName;
1489
+ errorConfig = {
1490
+ id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1491
+ messagePrefix: "We found a binary dependency in your bundle but we cannot bundle it yet. Please add"
1492
+ };
1493
+ }
1494
+ if (moduleName && workspaceMap.has(moduleName)) {
1495
+ throw new MastraError({
1496
+ id: "DEPLOYER_ANALYZE_ERROR_IN_WORKSPACE",
1497
+ domain: ErrorDomain.DEPLOYER,
1498
+ category: ErrorCategory.USER,
1499
+ details: {
1500
+ // importFile: moduleName,
1501
+ packageName: moduleName
1502
+ },
1503
+ text: `We found an error in the ${moduleName} workspace package. Please find the offending package and fix the error.
1504
+ Error: ${err.stack}`
1505
+ });
1506
+ }
1507
+ if (errorConfig && moduleName) {
1508
+ throwExternalDependencyError({
1509
+ errorId: errorConfig.id,
1510
+ moduleName,
1511
+ packageName: moduleName,
1512
+ messagePrefix: errorConfig.messagePrefix
1513
+ });
1514
+ }
1515
+ }
1516
+ async function validateFile(root, file, {
1517
+ binaryMapData,
1518
+ moduleResolveMapLocation,
1519
+ logger,
1520
+ workspaceMap
1521
+ }) {
1522
+ try {
1523
+ if (!file.isDynamicEntry && file.isEntry) {
1524
+ await validate(join(root, file.fileName), {
1525
+ moduleResolveMapLocation,
1526
+ injectESMShim: false
1527
+ });
1528
+ }
1529
+ } catch (err) {
1530
+ let errorToHandle = err;
1531
+ if (err instanceof ValidationError && err.type === "ReferenceError" && (err.message.startsWith("__dirname") || err.message.startsWith("__filename"))) {
1532
+ try {
1533
+ await validate(join(root, file.fileName), {
1534
+ moduleResolveMapLocation,
1535
+ injectESMShim: true
1536
+ });
1537
+ errorToHandle = null;
1538
+ } catch (err2) {
1539
+ errorToHandle = err2;
1540
+ }
1541
+ }
1542
+ if (errorToHandle instanceof Error) {
1543
+ validateError(errorToHandle, file, { binaryMapData, workspaceMap });
1544
+ }
1545
+ }
1546
+ }
1251
1547
  async function validateOutput({
1252
1548
  output,
1253
1549
  reverseVirtualReferenceMap,
@@ -1261,60 +1557,30 @@ async function validateOutput({
1261
1557
  externalDependencies: /* @__PURE__ */ new Set(),
1262
1558
  workspaceMap
1263
1559
  };
1264
- await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(usedExternals, null, 2));
1265
1560
  for (const deps of Object.values(usedExternals)) {
1266
1561
  for (const dep of Object.keys(deps)) {
1267
1562
  result.externalDependencies.add(dep);
1268
1563
  }
1269
1564
  }
1565
+ let binaryMapData = {};
1566
+ if (existsSync(join(outputDir, "binary-map.json"))) {
1567
+ const binaryMap = await readFile(join(outputDir, "binary-map.json"), "utf-8");
1568
+ binaryMapData = JSON.parse(binaryMap);
1569
+ }
1270
1570
  for (const file of output) {
1271
1571
  if (file.type === "asset") {
1272
1572
  continue;
1273
1573
  }
1274
- try {
1275
- logger.debug(`Validating if ${file.fileName} is a valid module.`);
1276
- if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1277
- result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1278
- }
1279
- if (!file.isDynamicEntry && file.isEntry) {
1280
- await validate(join(projectRoot, file.fileName));
1281
- }
1282
- } catch (err) {
1283
- if (err instanceof Error) {
1284
- let moduleName = null;
1285
- let errorConfig = null;
1286
- if (err.message.includes("[ERR_MODULE_NOT_FOUND]")) {
1287
- const moduleIdName = file.moduleIds.length >= 2 ? file.moduleIds[file.moduleIds.length - 2] : void 0;
1288
- const fallbackName = file.name.split("/").pop();
1289
- moduleName = moduleIdName ?? fallbackName;
1290
- errorConfig = {
1291
- id: "DEPLOYER_ANALYZE_MODULE_NOT_FOUND",
1292
- messagePrefix: "Mastra wasn't able to build your project. Please add"
1293
- };
1294
- } else if (err.message.includes("Error: No native build was found for ")) {
1295
- moduleName = findNativePackageModule(file.moduleIds);
1296
- errorConfig = {
1297
- id: "DEPLOYER_ANALYZE_MISSING_NATIVE_BUILD",
1298
- messagePrefix: "We found a binary dependency in your bundle. Please add"
1299
- };
1300
- }
1301
- if (moduleName && errorConfig) {
1302
- const pkgInfo = await getPackageInfo(moduleName);
1303
- const packageName = pkgInfo?.packageJson?.name;
1304
- if (packageName) {
1305
- throwExternalDependencyError({
1306
- errorId: errorConfig.id,
1307
- moduleName,
1308
- packageName,
1309
- messagePrefix: errorConfig.messagePrefix
1310
- });
1311
- } else {
1312
- logger.debug(`Could not determine the module name for file ${file.fileName}`);
1313
- }
1314
- }
1315
- logger.debug(`Error while validating module ${file.fileName}: ${err.message}`);
1316
- }
1574
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
1575
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
1576
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
1317
1577
  }
1578
+ await validateFile(projectRoot, file, {
1579
+ binaryMapData,
1580
+ moduleResolveMapLocation: join(outputDir, "module-resolve-map.json"),
1581
+ logger,
1582
+ workspaceMap
1583
+ });
1318
1584
  }
1319
1585
  return result;
1320
1586
  }
@@ -1346,7 +1612,10 @@ If you think your configuration is valid, please open an issue.`);
1346
1612
  const { workspaceMap, workspaceRoot } = await getWorkspaceInformation({ mastraEntryFile: mastraEntry });
1347
1613
  let index = 0;
1348
1614
  const depsToOptimize = /* @__PURE__ */ new Map();
1615
+ const { externals: customExternals = [] } = bundlerOptions || {};
1616
+ const allExternals = [...GLOBAL_EXTERNALS, ...customExternals];
1349
1617
  logger.info("Analyzing dependencies...");
1618
+ const allUsedExternals = /* @__PURE__ */ new Set();
1350
1619
  for (const entry of entries) {
1351
1620
  const isVirtualFile = entry.includes("\n") || !existsSync(entry);
1352
1621
  const analyzeResult = await analyzeEntry({ entry, isVirtualFile }, mastraEntry, {
@@ -1358,6 +1627,11 @@ If you think your configuration is valid, please open an issue.`);
1358
1627
  });
1359
1628
  await writeFile(join(outputDir, `entry-${index++}.mjs`), analyzeResult.output.code);
1360
1629
  for (const [dep, metadata] of analyzeResult.dependencies.entries()) {
1630
+ const isPartOfExternals = allExternals.some((external) => isDependencyPartOfPackage(dep, external));
1631
+ if (isPartOfExternals) {
1632
+ allUsedExternals.add(dep);
1633
+ continue;
1634
+ }
1361
1635
  if (depsToOptimize.has(dep)) {
1362
1636
  const existingEntry = depsToOptimize.get(dep);
1363
1637
  depsToOptimize.set(dep, {
@@ -1376,14 +1650,13 @@ If you think your configuration is valid, please open an issue.`);
1376
1650
  }
1377
1651
  }
1378
1652
  }
1379
- logger.debug(`Analyzed dependencies: ${Array.from(depsToOptimize.keys()).join(", ")}`);
1653
+ const sortedDeps = Array.from(depsToOptimize.keys()).sort();
1380
1654
  logger.info("Optimizing dependencies...");
1381
- logger.debug(
1382
- `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
1383
- );
1655
+ logger.debug(`${sortedDeps.map((key) => `- ${key}`).join("\n")}`);
1384
1656
  const { output, fileNameToDependencyMap, usedExternals } = await bundleExternals(depsToOptimize, outputDir, {
1385
1657
  bundlerOptions: {
1386
1658
  ...bundlerOptions,
1659
+ externals: allExternals,
1387
1660
  enableEsmShim,
1388
1661
  isDev
1389
1662
  },
@@ -1402,9 +1675,12 @@ If you think your configuration is valid, please open an issue.`);
1402
1675
  },
1403
1676
  logger
1404
1677
  );
1405
- return result;
1678
+ return {
1679
+ ...result,
1680
+ externalDependencies: /* @__PURE__ */ new Set([...result.externalDependencies, ...Array.from(allUsedExternals)])
1681
+ };
1406
1682
  }
1407
1683
 
1408
- export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getPackageName, getPackageRootPath, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, slash, tsConfigPaths };
1409
- //# sourceMappingURL=chunk-PHZK4P6J.js.map
1410
- //# sourceMappingURL=chunk-PHZK4P6J.js.map
1684
+ export { aliasHono, analyzeBundle, esbuild, esmShim, extractMastraOption, getBundlerOptions, getWorkspaceInformation, removeAllOptionsFromMastraExcept, removeDeployer2 as removeDeployer, subpathExternalsResolver, tsConfigPaths };
1685
+ //# sourceMappingURL=chunk-X5SEG2FP.js.map
1686
+ //# sourceMappingURL=chunk-X5SEG2FP.js.map