@mastra/deployer 0.0.0-a2a-20250421213654
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.
- package/LICENSE.md +46 -0
- package/README.md +159 -0
- package/dist/_tsup-dts-rollup.d.cts +548 -0
- package/dist/_tsup-dts-rollup.d.ts +548 -0
- package/dist/build/analyze.cjs +10 -0
- package/dist/build/analyze.d.cts +1 -0
- package/dist/build/analyze.d.ts +1 -0
- package/dist/build/analyze.js +1 -0
- package/dist/build/bundler.cjs +14 -0
- package/dist/build/bundler.d.cts +2 -0
- package/dist/build/bundler.d.ts +2 -0
- package/dist/build/bundler.js +1 -0
- package/dist/build/index.cjs +46 -0
- package/dist/build/index.d.cts +9 -0
- package/dist/build/index.d.ts +9 -0
- package/dist/build/index.js +5 -0
- package/dist/bundler/index.cjs +10 -0
- package/dist/bundler/index.d.cts +1 -0
- package/dist/bundler/index.d.ts +1 -0
- package/dist/bundler/index.js +1 -0
- package/dist/chunk-2ZPQX6BX.cjs +254 -0
- package/dist/chunk-4AYFLP6G.js +227 -0
- package/dist/chunk-4VC5Z4YR.cjs +391 -0
- package/dist/chunk-54KOF3NB.cjs +137 -0
- package/dist/chunk-5QD7CDGY.js +306 -0
- package/dist/chunk-6QMONK4A.cjs +2 -0
- package/dist/chunk-AOSWYZKN.js +138 -0
- package/dist/chunk-C4JT7CIH.js +1 -0
- package/dist/chunk-IMGVLBV7.cjs +149 -0
- package/dist/chunk-KTYDROLB.js +136 -0
- package/dist/chunk-LA6Y6GAB.cjs +312 -0
- package/dist/chunk-Q6OKTZNC.cjs +316 -0
- package/dist/chunk-USZDOFES.js +301 -0
- package/dist/chunk-UV4RQQ3R.js +359 -0
- package/dist/chunk-WVBUOQT6.js +111 -0
- package/dist/chunk-Z7KAM3CZ.cjs +164 -0
- package/dist/index.cjs +190 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +149 -0
- package/dist/server/index.cjs +3952 -0
- package/dist/server/index.d.cts +2 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +3944 -0
- package/dist/services/index.cjs +18 -0
- package/dist/services/index.d.cts +3 -0
- package/dist/services/index.d.ts +3 -0
- package/dist/services/index.js +1 -0
- package/dist/templates/instrumentation-template.js +89 -0
- package/dist/validator/custom-resolver.cjs +52 -0
- package/dist/validator/custom-resolver.d.cts +1 -0
- package/dist/validator/custom-resolver.d.ts +1 -0
- package/dist/validator/custom-resolver.js +50 -0
- package/dist/validator/loader.cjs +7 -0
- package/dist/validator/loader.d.cts +1 -0
- package/dist/validator/loader.d.ts +1 -0
- package/dist/validator/loader.js +4 -0
- package/package.json +140 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var chunk2ZPQX6BX_cjs = require('./chunk-2ZPQX6BX.cjs');
|
|
4
|
+
var chunkLA6Y6GAB_cjs = require('./chunk-LA6Y6GAB.cjs');
|
|
5
|
+
var chunkIMGVLBV7_cjs = require('./chunk-IMGVLBV7.cjs');
|
|
6
|
+
var chunk4VC5Z4YR_cjs = require('./chunk-4VC5Z4YR.cjs');
|
|
7
|
+
var fs = require('fs');
|
|
8
|
+
var promises = require('fs/promises');
|
|
9
|
+
var path = require('path');
|
|
10
|
+
var url = require('url');
|
|
11
|
+
var bundler = require('@mastra/core/bundler');
|
|
12
|
+
var virtual = require('@rollup/plugin-virtual');
|
|
13
|
+
var fsExtra = require('fs-extra/esm');
|
|
14
|
+
var resolveFrom = require('resolve-from');
|
|
15
|
+
var slugify = require('@sindresorhus/slugify');
|
|
16
|
+
var findWorkspaces = require('find-workspaces');
|
|
17
|
+
var fsExtra$1 = require('fs-extra');
|
|
18
|
+
|
|
19
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
20
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
21
|
+
|
|
22
|
+
var virtual__default = /*#__PURE__*/_interopDefault(virtual);
|
|
23
|
+
var fsExtra__default = /*#__PURE__*/_interopDefault(fsExtra);
|
|
24
|
+
var resolveFrom__default = /*#__PURE__*/_interopDefault(resolveFrom);
|
|
25
|
+
var slugify__default = /*#__PURE__*/_interopDefault(slugify);
|
|
26
|
+
|
|
27
|
+
var createWorkspacePackageMap = async () => {
|
|
28
|
+
const workspaces = await findWorkspaces.findWorkspaces();
|
|
29
|
+
const workspaceMap = new Map(
|
|
30
|
+
workspaces?.map((workspace) => [
|
|
31
|
+
workspace.package.name,
|
|
32
|
+
{
|
|
33
|
+
location: workspace.location,
|
|
34
|
+
dependencies: workspace.package.dependencies,
|
|
35
|
+
version: workspace.package.version
|
|
36
|
+
}
|
|
37
|
+
]) ?? []
|
|
38
|
+
);
|
|
39
|
+
return workspaceMap;
|
|
40
|
+
};
|
|
41
|
+
var collectTransitiveWorkspaceDependencies = ({
|
|
42
|
+
workspaceMap,
|
|
43
|
+
initialDependencies,
|
|
44
|
+
logger
|
|
45
|
+
}) => {
|
|
46
|
+
const usedWorkspacePackages = /* @__PURE__ */ new Set();
|
|
47
|
+
const queue = Array.from(initialDependencies);
|
|
48
|
+
const resolutions = {};
|
|
49
|
+
while (queue.length > 0) {
|
|
50
|
+
const len = queue.length;
|
|
51
|
+
for (let i = 0; i < len; i += 1) {
|
|
52
|
+
const pkgName = queue.shift();
|
|
53
|
+
if (!pkgName || usedWorkspacePackages.has(pkgName)) {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const dep = workspaceMap.get(pkgName);
|
|
57
|
+
if (!dep) continue;
|
|
58
|
+
const root = findWorkspaces.findWorkspacesRoot();
|
|
59
|
+
if (!root) {
|
|
60
|
+
throw new Error("Could not find workspace root");
|
|
61
|
+
}
|
|
62
|
+
const depsService = new chunk4VC5Z4YR_cjs.DepsService(root.location);
|
|
63
|
+
depsService.__setLogger(logger);
|
|
64
|
+
const sanitizedName = slugify__default.default(pkgName);
|
|
65
|
+
const tgzPath = depsService.getWorkspaceDependencyPath({
|
|
66
|
+
pkgName: sanitizedName,
|
|
67
|
+
version: dep.version
|
|
68
|
+
});
|
|
69
|
+
resolutions[pkgName] = tgzPath;
|
|
70
|
+
usedWorkspacePackages.add(pkgName);
|
|
71
|
+
for (const [depName, _depVersion] of Object.entries(dep?.dependencies ?? {})) {
|
|
72
|
+
if (!usedWorkspacePackages.has(depName) && workspaceMap.has(depName)) {
|
|
73
|
+
queue.push(depName);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return { resolutions, usedWorkspacePackages };
|
|
79
|
+
};
|
|
80
|
+
var packWorkspaceDependencies = async ({
|
|
81
|
+
workspaceMap,
|
|
82
|
+
usedWorkspacePackages,
|
|
83
|
+
bundleOutputDir,
|
|
84
|
+
logger
|
|
85
|
+
}) => {
|
|
86
|
+
const root = findWorkspaces.findWorkspacesRoot();
|
|
87
|
+
if (!root) {
|
|
88
|
+
throw new Error("Could not find workspace root");
|
|
89
|
+
}
|
|
90
|
+
const depsService = new chunk4VC5Z4YR_cjs.DepsService(root.location);
|
|
91
|
+
depsService.__setLogger(logger);
|
|
92
|
+
if (usedWorkspacePackages.size > 0) {
|
|
93
|
+
const workspaceDirPath = path.join(bundleOutputDir, "workspace-module");
|
|
94
|
+
await fsExtra$1.ensureDir(workspaceDirPath);
|
|
95
|
+
logger.info(`Packaging ${usedWorkspacePackages.size} workspace dependencies...`);
|
|
96
|
+
const batchSize = 5;
|
|
97
|
+
const packages = Array.from(usedWorkspacePackages.values());
|
|
98
|
+
for (let i = 0; i < packages.length; i += batchSize) {
|
|
99
|
+
const batch = packages.slice(i, i + batchSize);
|
|
100
|
+
logger.info(
|
|
101
|
+
`Packaging batch ${Math.floor(i / batchSize) + 1}/${Math.ceil(packages.length / batchSize)}: ${batch.join(", ")}`
|
|
102
|
+
);
|
|
103
|
+
await Promise.all(
|
|
104
|
+
batch.map(async (pkgName) => {
|
|
105
|
+
const dep = workspaceMap.get(pkgName);
|
|
106
|
+
if (!dep) return;
|
|
107
|
+
try {
|
|
108
|
+
await depsService.pack({ dir: dep.location, destination: workspaceDirPath });
|
|
109
|
+
} catch (error) {
|
|
110
|
+
logger.error(`Failed to package ${pkgName}: ${error}`);
|
|
111
|
+
}
|
|
112
|
+
})
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
logger.info(`Successfully packaged ${usedWorkspacePackages.size} workspace dependencies`);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// src/bundler/index.ts
|
|
120
|
+
var Bundler = class extends bundler.MastraBundler {
|
|
121
|
+
analyzeOutputDir = ".build";
|
|
122
|
+
outputDir = "output";
|
|
123
|
+
constructor(name, component = "BUNDLER") {
|
|
124
|
+
super({ name, component });
|
|
125
|
+
}
|
|
126
|
+
async prepare(outputDirectory) {
|
|
127
|
+
await fsExtra.emptyDir(outputDirectory);
|
|
128
|
+
await fsExtra.ensureDir(path.join(outputDirectory, this.analyzeOutputDir));
|
|
129
|
+
await fsExtra.ensureDir(path.join(outputDirectory, this.outputDir));
|
|
130
|
+
}
|
|
131
|
+
async writeInstrumentationFile(outputDirectory) {
|
|
132
|
+
const instrumentationFile = path.join(outputDirectory, "instrumentation.mjs");
|
|
133
|
+
const __dirname = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-Q6OKTZNC.cjs', document.baseURI).href))));
|
|
134
|
+
await fsExtra.copy(path.join(__dirname, "templates", "instrumentation-template.js"), instrumentationFile);
|
|
135
|
+
}
|
|
136
|
+
async writePackageJson(outputDirectory, dependencies, resolutions) {
|
|
137
|
+
this.logger.debug(`Writing project's package.json`);
|
|
138
|
+
await fsExtra.ensureDir(outputDirectory);
|
|
139
|
+
const pkgPath = path.join(outputDirectory, "package.json");
|
|
140
|
+
const dependenciesMap = /* @__PURE__ */ new Map();
|
|
141
|
+
for (const [key, value] of dependencies.entries()) {
|
|
142
|
+
if (key.startsWith("@")) {
|
|
143
|
+
const pkgChunks = key.split("/");
|
|
144
|
+
dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, value);
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
dependenciesMap.set(key, value);
|
|
148
|
+
}
|
|
149
|
+
dependenciesMap.set("@opentelemetry/instrumentation", "latest");
|
|
150
|
+
await promises.writeFile(
|
|
151
|
+
pkgPath,
|
|
152
|
+
JSON.stringify(
|
|
153
|
+
{
|
|
154
|
+
name: "server",
|
|
155
|
+
version: "1.0.0",
|
|
156
|
+
description: "",
|
|
157
|
+
type: "module",
|
|
158
|
+
main: "index.mjs",
|
|
159
|
+
scripts: {
|
|
160
|
+
start: "node ./index.mjs"
|
|
161
|
+
},
|
|
162
|
+
author: "Mastra",
|
|
163
|
+
license: "ISC",
|
|
164
|
+
dependencies: Object.fromEntries(dependenciesMap.entries()),
|
|
165
|
+
...Object.keys(resolutions ?? {}).length > 0 && { resolutions }
|
|
166
|
+
},
|
|
167
|
+
null,
|
|
168
|
+
2
|
|
169
|
+
)
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
createBundler(inputOptions, outputOptions) {
|
|
173
|
+
return chunkIMGVLBV7_cjs.createBundler(inputOptions, outputOptions);
|
|
174
|
+
}
|
|
175
|
+
async analyze(entry, mastraFile, outputDirectory) {
|
|
176
|
+
return await chunkLA6Y6GAB_cjs.analyzeBundle(entry, mastraFile, path.join(outputDirectory, this.analyzeOutputDir), "node", this.logger);
|
|
177
|
+
}
|
|
178
|
+
async installDependencies(outputDirectory, rootDir = process.cwd()) {
|
|
179
|
+
const deps = new chunk4VC5Z4YR_cjs.DepsService(rootDir);
|
|
180
|
+
deps.__setLogger(this.logger);
|
|
181
|
+
await deps.install({ dir: path.join(outputDirectory, this.outputDir) });
|
|
182
|
+
}
|
|
183
|
+
async copyPublic(mastraDir, outputDirectory) {
|
|
184
|
+
const publicDir = path.join(mastraDir, "public");
|
|
185
|
+
try {
|
|
186
|
+
await promises.stat(publicDir);
|
|
187
|
+
} catch {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
await fsExtra.copy(publicDir, path.join(outputDirectory, this.outputDir));
|
|
191
|
+
}
|
|
192
|
+
async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths) {
|
|
193
|
+
const inputOptions = await chunkIMGVLBV7_cjs.getInputOptions(mastraEntryFile, analyzedBundleInfo, "node", {
|
|
194
|
+
"process.env.NODE_ENV": JSON.stringify("production")
|
|
195
|
+
});
|
|
196
|
+
const isVirtual = serverFile.includes("\n") || fs.existsSync(serverFile);
|
|
197
|
+
const toolsInputOptions = await this.getToolsInputOptions(toolsPaths);
|
|
198
|
+
if (isVirtual) {
|
|
199
|
+
inputOptions.input = { index: "#entry", ...toolsInputOptions };
|
|
200
|
+
if (Array.isArray(inputOptions.plugins)) {
|
|
201
|
+
inputOptions.plugins.unshift(virtual__default.default({ "#entry": serverFile }));
|
|
202
|
+
} else {
|
|
203
|
+
inputOptions.plugins = [virtual__default.default({ "#entry": serverFile })];
|
|
204
|
+
}
|
|
205
|
+
} else {
|
|
206
|
+
inputOptions.input = { index: serverFile, ...toolsInputOptions };
|
|
207
|
+
}
|
|
208
|
+
return inputOptions;
|
|
209
|
+
}
|
|
210
|
+
async getToolsInputOptions(toolsPaths) {
|
|
211
|
+
const inputs = {};
|
|
212
|
+
for (const toolPath of toolsPaths) {
|
|
213
|
+
if (await fsExtra__default.default.pathExists(toolPath)) {
|
|
214
|
+
const fileService = new chunk4VC5Z4YR_cjs.FileService();
|
|
215
|
+
const entryFile = fileService.getFirstExistingFile([
|
|
216
|
+
path.join(toolPath, "index.ts"),
|
|
217
|
+
path.join(toolPath, "index.js"),
|
|
218
|
+
toolPath
|
|
219
|
+
// if toolPath itself is a file
|
|
220
|
+
]);
|
|
221
|
+
if (!entryFile || (await promises.stat(entryFile)).isDirectory()) {
|
|
222
|
+
this.logger.warn(`No entry file found in ${toolPath}, skipping...`);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const uniqueToolID = crypto.randomUUID();
|
|
226
|
+
inputs[`tools/${uniqueToolID}`] = entryFile;
|
|
227
|
+
} else {
|
|
228
|
+
this.logger.warn(`Tool path ${toolPath} does not exist, skipping...`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return inputs;
|
|
232
|
+
}
|
|
233
|
+
async _bundle(serverFile, mastraEntryFile, outputDirectory, toolsPaths = [], bundleLocation = path.join(outputDirectory, this.outputDir)) {
|
|
234
|
+
this.logger.info("Start bundling Mastra");
|
|
235
|
+
const analyzedBundleInfo = await chunkLA6Y6GAB_cjs.analyzeBundle(
|
|
236
|
+
serverFile,
|
|
237
|
+
mastraEntryFile,
|
|
238
|
+
path.join(outputDirectory, this.analyzeOutputDir),
|
|
239
|
+
"node",
|
|
240
|
+
this.logger
|
|
241
|
+
);
|
|
242
|
+
await chunk2ZPQX6BX_cjs.writeTelemetryConfig(mastraEntryFile, path.join(outputDirectory, this.outputDir));
|
|
243
|
+
const workspaceMap = await createWorkspacePackageMap();
|
|
244
|
+
const dependenciesToInstall = /* @__PURE__ */ new Map();
|
|
245
|
+
const workspaceDependencies = /* @__PURE__ */ new Set();
|
|
246
|
+
for (const dep of analyzedBundleInfo.externalDependencies) {
|
|
247
|
+
try {
|
|
248
|
+
const pkgPath = resolveFrom__default.default(mastraEntryFile, `${dep}/package.json`);
|
|
249
|
+
const pkg = await fsExtra.readJSON(pkgPath);
|
|
250
|
+
if (workspaceMap.has(pkg.name)) {
|
|
251
|
+
workspaceDependencies.add(pkg.name);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
dependenciesToInstall.set(dep, pkg.version);
|
|
255
|
+
} catch {
|
|
256
|
+
dependenciesToInstall.set(dep, "latest");
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
let resolutions = {};
|
|
260
|
+
if (workspaceDependencies.size > 0) {
|
|
261
|
+
try {
|
|
262
|
+
const result = collectTransitiveWorkspaceDependencies({
|
|
263
|
+
workspaceMap,
|
|
264
|
+
initialDependencies: workspaceDependencies,
|
|
265
|
+
logger: this.logger
|
|
266
|
+
});
|
|
267
|
+
resolutions = result.resolutions;
|
|
268
|
+
Object.entries(resolutions).forEach(([pkgName, tgzPath]) => {
|
|
269
|
+
dependenciesToInstall.set(pkgName, tgzPath);
|
|
270
|
+
});
|
|
271
|
+
await packWorkspaceDependencies({
|
|
272
|
+
workspaceMap,
|
|
273
|
+
usedWorkspacePackages: result.usedWorkspacePackages,
|
|
274
|
+
bundleOutputDir: path.join(outputDirectory, this.outputDir),
|
|
275
|
+
logger: this.logger
|
|
276
|
+
});
|
|
277
|
+
} catch (error) {
|
|
278
|
+
this.logger.error(`Failed to collect workspace dependencies: ${error}`);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (analyzedBundleInfo.externalDependencies.has("@mastra/memory") || analyzedBundleInfo.dependencies.has("@mastra/memory")) {
|
|
283
|
+
dependenciesToInstall.set("fastembed", "latest");
|
|
284
|
+
}
|
|
285
|
+
await this.writePackageJson(path.join(outputDirectory, this.outputDir), dependenciesToInstall, resolutions);
|
|
286
|
+
await this.writeInstrumentationFile(path.join(outputDirectory, this.outputDir));
|
|
287
|
+
this.logger.info("Bundling Mastra application");
|
|
288
|
+
const inputOptions = await this.getBundlerOptions(
|
|
289
|
+
serverFile,
|
|
290
|
+
mastraEntryFile,
|
|
291
|
+
analyzedBundleInfo,
|
|
292
|
+
toolsPaths
|
|
293
|
+
);
|
|
294
|
+
const bundler = await this.createBundler(inputOptions, {
|
|
295
|
+
dir: bundleLocation,
|
|
296
|
+
manualChunks: {
|
|
297
|
+
mastra: ["#mastra"]
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
await bundler.write();
|
|
301
|
+
const toolsInputOptions = Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).map((key) => `./${key}.mjs`);
|
|
302
|
+
await promises.writeFile(
|
|
303
|
+
path.join(outputDirectory, this.outputDir, "tools.mjs"),
|
|
304
|
+
`export const tools = ${JSON.stringify(toolsInputOptions)};`
|
|
305
|
+
);
|
|
306
|
+
this.logger.info("Bundling Mastra done");
|
|
307
|
+
this.logger.info("Copying public files");
|
|
308
|
+
await this.copyPublic(path.dirname(mastraEntryFile), outputDirectory);
|
|
309
|
+
this.logger.info("Done copying public files");
|
|
310
|
+
this.logger.info("Installing dependencies");
|
|
311
|
+
await this.installDependencies(outputDirectory);
|
|
312
|
+
this.logger.info("Done installing dependencies");
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
exports.Bundler = Bundler;
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { tsConfigPaths, removeDeployer } from './chunk-WVBUOQT6.js';
|
|
2
|
+
import commonjs from '@rollup/plugin-commonjs';
|
|
3
|
+
import json from '@rollup/plugin-json';
|
|
4
|
+
import nodeResolve from '@rollup/plugin-node-resolve';
|
|
5
|
+
import virtual from '@rollup/plugin-virtual';
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { rollup } from 'rollup';
|
|
9
|
+
import esbuild from 'rollup-plugin-esbuild';
|
|
10
|
+
import { builtinModules } from 'node:module';
|
|
11
|
+
import { join, dirname } from 'node:path';
|
|
12
|
+
import { spawn as spawn$1 } from 'node:child_process';
|
|
13
|
+
import { writeFile } from 'node:fs/promises';
|
|
14
|
+
|
|
15
|
+
function isNodeBuiltin(dep) {
|
|
16
|
+
const [pkg] = dep.split("/");
|
|
17
|
+
return dep.startsWith("node:") || builtinModules.includes(dep) || builtinModules.includes(pkg);
|
|
18
|
+
}
|
|
19
|
+
function aliasHono() {
|
|
20
|
+
return {
|
|
21
|
+
name: "hono-alias",
|
|
22
|
+
resolveId(id) {
|
|
23
|
+
if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const path = import.meta.resolve(id);
|
|
27
|
+
return fileURLToPath(path);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function spawn(command, args = [], options = {}) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
const childProcess = spawn$1(command, args, {
|
|
34
|
+
// stdio: 'inherit',
|
|
35
|
+
...options
|
|
36
|
+
});
|
|
37
|
+
childProcess.on("error", (error) => {
|
|
38
|
+
reject(error);
|
|
39
|
+
});
|
|
40
|
+
let stderr = "";
|
|
41
|
+
childProcess.stderr?.on("data", (message) => {
|
|
42
|
+
stderr += message;
|
|
43
|
+
});
|
|
44
|
+
childProcess.on("close", (code) => {
|
|
45
|
+
if (code === 0) {
|
|
46
|
+
resolve();
|
|
47
|
+
} else {
|
|
48
|
+
reject(new Error(stderr));
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function validate(file) {
|
|
54
|
+
return spawn(
|
|
55
|
+
"node",
|
|
56
|
+
[
|
|
57
|
+
"--import",
|
|
58
|
+
import.meta.resolve("@mastra/deployer/loader"),
|
|
59
|
+
"--input-type=module",
|
|
60
|
+
"-e",
|
|
61
|
+
`import('file://${file.replaceAll("\\", "/")}')`
|
|
62
|
+
],
|
|
63
|
+
{
|
|
64
|
+
cwd: dirname(file)
|
|
65
|
+
}
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
var globalExternals = ["pino", "pino-pretty", "@libsql/client", "pg", "libsql", "jsdom", "sqlite3"];
|
|
69
|
+
function findExternalImporter(module, external, allOutputs) {
|
|
70
|
+
const capturedFiles = /* @__PURE__ */ new Set();
|
|
71
|
+
for (const id of module.imports) {
|
|
72
|
+
if (id === external) {
|
|
73
|
+
return module;
|
|
74
|
+
} else {
|
|
75
|
+
if (id.endsWith(".mjs")) {
|
|
76
|
+
capturedFiles.add(id);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
for (const file of capturedFiles) {
|
|
81
|
+
const nextModule = allOutputs.find((o) => o.fileName === file);
|
|
82
|
+
if (nextModule) {
|
|
83
|
+
const importer = findExternalImporter(nextModule, external, allOutputs);
|
|
84
|
+
if (importer) {
|
|
85
|
+
return importer;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
async function analyze(entry, mastraEntry, isVirtualFile, platform, logger) {
|
|
92
|
+
logger.info("Analyzing dependencies...");
|
|
93
|
+
let virtualPlugin = null;
|
|
94
|
+
if (isVirtualFile) {
|
|
95
|
+
virtualPlugin = virtual({
|
|
96
|
+
"#entry": entry
|
|
97
|
+
});
|
|
98
|
+
entry = "#entry";
|
|
99
|
+
}
|
|
100
|
+
const normalizedMastraEntry = mastraEntry.replaceAll("\\", "/");
|
|
101
|
+
const optimizerBundler = await rollup({
|
|
102
|
+
logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
|
|
103
|
+
input: isVirtualFile ? "#entry" : entry,
|
|
104
|
+
treeshake: "smallest",
|
|
105
|
+
preserveSymlinks: true,
|
|
106
|
+
plugins: [
|
|
107
|
+
virtualPlugin,
|
|
108
|
+
tsConfigPaths(),
|
|
109
|
+
{
|
|
110
|
+
name: "custom-alias-resolver",
|
|
111
|
+
resolveId(id) {
|
|
112
|
+
if (id === "#server") {
|
|
113
|
+
return fileURLToPath(import.meta.resolve("@mastra/deployer/server")).replaceAll("\\", "/");
|
|
114
|
+
}
|
|
115
|
+
if (id === "#mastra") {
|
|
116
|
+
return normalizedMastraEntry;
|
|
117
|
+
}
|
|
118
|
+
if (id.startsWith("@mastra/server")) {
|
|
119
|
+
return fileURLToPath(import.meta.resolve(id));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
json(),
|
|
124
|
+
esbuild({
|
|
125
|
+
target: "node20",
|
|
126
|
+
platform,
|
|
127
|
+
minify: false
|
|
128
|
+
}),
|
|
129
|
+
commonjs({
|
|
130
|
+
strictRequires: "debug",
|
|
131
|
+
ignoreTryCatch: false,
|
|
132
|
+
transformMixedEsModules: true,
|
|
133
|
+
extensions: [".js", ".ts"]
|
|
134
|
+
}),
|
|
135
|
+
removeDeployer(normalizedMastraEntry),
|
|
136
|
+
esbuild({
|
|
137
|
+
target: "node20",
|
|
138
|
+
platform,
|
|
139
|
+
minify: false
|
|
140
|
+
})
|
|
141
|
+
].filter(Boolean)
|
|
142
|
+
});
|
|
143
|
+
const { output } = await optimizerBundler.generate({
|
|
144
|
+
format: "esm",
|
|
145
|
+
inlineDynamicImports: true
|
|
146
|
+
});
|
|
147
|
+
await optimizerBundler.close();
|
|
148
|
+
const depsToOptimize = new Map(Object.entries(output[0].importedBindings));
|
|
149
|
+
for (const dep of depsToOptimize.keys()) {
|
|
150
|
+
if (isNodeBuiltin(dep)) {
|
|
151
|
+
depsToOptimize.delete(dep);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return depsToOptimize;
|
|
155
|
+
}
|
|
156
|
+
async function bundleExternals(depsToOptimize, outputDir, logger) {
|
|
157
|
+
logger.info("Optimizing dependencies...");
|
|
158
|
+
logger.debug(
|
|
159
|
+
`${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
|
|
160
|
+
);
|
|
161
|
+
const reverseVirtualReferenceMap = /* @__PURE__ */ new Map();
|
|
162
|
+
const virtualDependencies = /* @__PURE__ */ new Map();
|
|
163
|
+
for (const [dep, exports] of depsToOptimize.entries()) {
|
|
164
|
+
const name = dep.replaceAll("/", "-");
|
|
165
|
+
reverseVirtualReferenceMap.set(name, dep);
|
|
166
|
+
const virtualFile = [];
|
|
167
|
+
let exportStringBuilder = [];
|
|
168
|
+
for (const local of exports) {
|
|
169
|
+
if (local === "*") {
|
|
170
|
+
virtualFile.push(`export * from '${dep}';`);
|
|
171
|
+
} else if (local === "default") {
|
|
172
|
+
virtualFile.push(`export { default } from '${dep}';`);
|
|
173
|
+
} else {
|
|
174
|
+
exportStringBuilder.push(local);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (exportStringBuilder.length > 0) {
|
|
178
|
+
virtualFile.push(`export { ${exportStringBuilder.join(", ")} } from '${dep}';`);
|
|
179
|
+
}
|
|
180
|
+
virtualDependencies.set(dep, {
|
|
181
|
+
name,
|
|
182
|
+
virtual: virtualFile.join("\n")
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
const bundler = await rollup({
|
|
186
|
+
logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
|
|
187
|
+
input: Array.from(virtualDependencies.entries()).reduce(
|
|
188
|
+
(acc, [dep, virtualDep]) => {
|
|
189
|
+
acc[virtualDep.name] = `#virtual-${dep}`;
|
|
190
|
+
return acc;
|
|
191
|
+
},
|
|
192
|
+
{}
|
|
193
|
+
),
|
|
194
|
+
// this dependency breaks the build, so we need to exclude it
|
|
195
|
+
// TODO actually fix this so we don't need to exclude it
|
|
196
|
+
external: globalExternals,
|
|
197
|
+
treeshake: "smallest",
|
|
198
|
+
plugins: [
|
|
199
|
+
virtual(
|
|
200
|
+
Array.from(virtualDependencies.entries()).reduce(
|
|
201
|
+
(acc, [dep, virtualDep]) => {
|
|
202
|
+
acc[`#virtual-${dep}`] = virtualDep.virtual;
|
|
203
|
+
return acc;
|
|
204
|
+
},
|
|
205
|
+
{}
|
|
206
|
+
)
|
|
207
|
+
),
|
|
208
|
+
commonjs({
|
|
209
|
+
strictRequires: "strict",
|
|
210
|
+
transformMixedEsModules: true,
|
|
211
|
+
ignoreTryCatch: false
|
|
212
|
+
}),
|
|
213
|
+
nodeResolve({
|
|
214
|
+
preferBuiltins: true,
|
|
215
|
+
exportConditions: ["node", "import", "require"],
|
|
216
|
+
mainFields: ["module", "main"]
|
|
217
|
+
}),
|
|
218
|
+
// hono is imported from deployer, so we need to resolve from here instead of the project root
|
|
219
|
+
aliasHono(),
|
|
220
|
+
json()
|
|
221
|
+
].filter(Boolean)
|
|
222
|
+
});
|
|
223
|
+
const { output } = await bundler.write({
|
|
224
|
+
format: "esm",
|
|
225
|
+
dir: outputDir,
|
|
226
|
+
entryFileNames: "[name].mjs",
|
|
227
|
+
chunkFileNames: "[name].mjs",
|
|
228
|
+
hoistTransitiveImports: false
|
|
229
|
+
});
|
|
230
|
+
const moduleResolveMap = {};
|
|
231
|
+
const filteredChunks = output.filter((o) => o.type === "chunk");
|
|
232
|
+
for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
|
|
233
|
+
for (const external of globalExternals) {
|
|
234
|
+
const importer = findExternalImporter(o, external, filteredChunks);
|
|
235
|
+
if (importer) {
|
|
236
|
+
const fullPath = join(outputDir, importer.fileName);
|
|
237
|
+
moduleResolveMap[fullPath] = moduleResolveMap[fullPath] || {};
|
|
238
|
+
if (importer.moduleIds.length) {
|
|
239
|
+
moduleResolveMap[fullPath][external] = importer.moduleIds[importer.moduleIds.length - 1]?.startsWith(
|
|
240
|
+
"\0virtual:#virtual"
|
|
241
|
+
) ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1];
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
await writeFile(join(outputDir, "module-resolve-map.json"), JSON.stringify(moduleResolveMap, null, 2));
|
|
247
|
+
await bundler.close();
|
|
248
|
+
return { output, reverseVirtualReferenceMap, usedExternals: moduleResolveMap };
|
|
249
|
+
}
|
|
250
|
+
async function validateOutput({
|
|
251
|
+
output,
|
|
252
|
+
reverseVirtualReferenceMap,
|
|
253
|
+
usedExternals,
|
|
254
|
+
outputDir
|
|
255
|
+
}, logger) {
|
|
256
|
+
const result = {
|
|
257
|
+
invalidChunks: /* @__PURE__ */ new Set(),
|
|
258
|
+
dependencies: /* @__PURE__ */ new Map(),
|
|
259
|
+
externalDependencies: /* @__PURE__ */ new Set()
|
|
260
|
+
};
|
|
261
|
+
for (const deps of Object.values(usedExternals)) {
|
|
262
|
+
for (const dep of Object.keys(deps)) {
|
|
263
|
+
result.externalDependencies.add(dep);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
for (const file of output) {
|
|
267
|
+
if (file.type === "asset") {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
try {
|
|
271
|
+
logger.debug(`Validating if ${file.fileName} is a valid module.`);
|
|
272
|
+
if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
|
|
273
|
+
result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
|
|
274
|
+
}
|
|
275
|
+
if (!file.isDynamicEntry && file.isEntry) {
|
|
276
|
+
await validate(join(outputDir, file.fileName));
|
|
277
|
+
}
|
|
278
|
+
} catch (err) {
|
|
279
|
+
result.invalidChunks.add(file.fileName);
|
|
280
|
+
if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
|
|
281
|
+
const reference = reverseVirtualReferenceMap.get(file.name);
|
|
282
|
+
const dep = reference.startsWith("@") ? reference.split("/").slice(0, 2).join("/") : reference.split("/")[0];
|
|
283
|
+
result.externalDependencies.add(dep);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return result;
|
|
288
|
+
}
|
|
289
|
+
async function analyzeBundle(entry, mastraEntry, outputDir, platform, logger) {
|
|
290
|
+
const isVirtualFile = entry.includes("\n") || !existsSync(entry);
|
|
291
|
+
const depsToOptimize = await analyze(entry, mastraEntry, isVirtualFile, platform, logger);
|
|
292
|
+
const { output, reverseVirtualReferenceMap, usedExternals } = await bundleExternals(
|
|
293
|
+
depsToOptimize,
|
|
294
|
+
outputDir,
|
|
295
|
+
logger
|
|
296
|
+
);
|
|
297
|
+
const result = await validateOutput({ output, reverseVirtualReferenceMap, usedExternals, outputDir }, logger);
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export { aliasHono, analyzeBundle };
|