@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.
Files changed (58) hide show
  1. package/LICENSE.md +46 -0
  2. package/README.md +159 -0
  3. package/dist/_tsup-dts-rollup.d.cts +548 -0
  4. package/dist/_tsup-dts-rollup.d.ts +548 -0
  5. package/dist/build/analyze.cjs +10 -0
  6. package/dist/build/analyze.d.cts +1 -0
  7. package/dist/build/analyze.d.ts +1 -0
  8. package/dist/build/analyze.js +1 -0
  9. package/dist/build/bundler.cjs +14 -0
  10. package/dist/build/bundler.d.cts +2 -0
  11. package/dist/build/bundler.d.ts +2 -0
  12. package/dist/build/bundler.js +1 -0
  13. package/dist/build/index.cjs +46 -0
  14. package/dist/build/index.d.cts +9 -0
  15. package/dist/build/index.d.ts +9 -0
  16. package/dist/build/index.js +5 -0
  17. package/dist/bundler/index.cjs +10 -0
  18. package/dist/bundler/index.d.cts +1 -0
  19. package/dist/bundler/index.d.ts +1 -0
  20. package/dist/bundler/index.js +1 -0
  21. package/dist/chunk-2ZPQX6BX.cjs +254 -0
  22. package/dist/chunk-4AYFLP6G.js +227 -0
  23. package/dist/chunk-4VC5Z4YR.cjs +391 -0
  24. package/dist/chunk-54KOF3NB.cjs +137 -0
  25. package/dist/chunk-5QD7CDGY.js +306 -0
  26. package/dist/chunk-6QMONK4A.cjs +2 -0
  27. package/dist/chunk-AOSWYZKN.js +138 -0
  28. package/dist/chunk-C4JT7CIH.js +1 -0
  29. package/dist/chunk-IMGVLBV7.cjs +149 -0
  30. package/dist/chunk-KTYDROLB.js +136 -0
  31. package/dist/chunk-LA6Y6GAB.cjs +312 -0
  32. package/dist/chunk-Q6OKTZNC.cjs +316 -0
  33. package/dist/chunk-USZDOFES.js +301 -0
  34. package/dist/chunk-UV4RQQ3R.js +359 -0
  35. package/dist/chunk-WVBUOQT6.js +111 -0
  36. package/dist/chunk-Z7KAM3CZ.cjs +164 -0
  37. package/dist/index.cjs +190 -0
  38. package/dist/index.d.cts +6 -0
  39. package/dist/index.d.ts +6 -0
  40. package/dist/index.js +149 -0
  41. package/dist/server/index.cjs +3952 -0
  42. package/dist/server/index.d.cts +2 -0
  43. package/dist/server/index.d.ts +2 -0
  44. package/dist/server/index.js +3944 -0
  45. package/dist/services/index.cjs +18 -0
  46. package/dist/services/index.d.cts +3 -0
  47. package/dist/services/index.d.ts +3 -0
  48. package/dist/services/index.js +1 -0
  49. package/dist/templates/instrumentation-template.js +89 -0
  50. package/dist/validator/custom-resolver.cjs +52 -0
  51. package/dist/validator/custom-resolver.d.cts +1 -0
  52. package/dist/validator/custom-resolver.d.ts +1 -0
  53. package/dist/validator/custom-resolver.js +50 -0
  54. package/dist/validator/loader.cjs +7 -0
  55. package/dist/validator/loader.d.cts +1 -0
  56. package/dist/validator/loader.d.ts +1 -0
  57. package/dist/validator/loader.js +4 -0
  58. package/package.json +140 -0
@@ -0,0 +1,136 @@
1
+ import { recursiveRemoveNonReferencedNodes, removeAllOptionsFromMastraExcept } from './chunk-4AYFLP6G.js';
2
+ import { aliasHono } from './chunk-USZDOFES.js';
3
+ import { getInputOptions } from './chunk-AOSWYZKN.js';
4
+ import { tsConfigPaths } from './chunk-WVBUOQT6.js';
5
+ import { watch, rollup } from 'rollup';
6
+ import * as babel from '@babel/core';
7
+ import esbuild from 'rollup-plugin-esbuild';
8
+ import commonjs from '@rollup/plugin-commonjs';
9
+
10
+ async function getInputOptions2(entryFile, platform, env) {
11
+ const inputOptions = await getInputOptions(
12
+ entryFile,
13
+ {
14
+ dependencies: /* @__PURE__ */ new Map(),
15
+ externalDependencies: /* @__PURE__ */ new Set(),
16
+ invalidChunks: /* @__PURE__ */ new Set()
17
+ },
18
+ platform,
19
+ env
20
+ );
21
+ if (Array.isArray(inputOptions.plugins)) {
22
+ inputOptions.plugins = inputOptions.plugins.filter(
23
+ // @ts-ignore
24
+ (plugin) => !plugin || !plugin?.name || plugin.name !== "node-resolve"
25
+ );
26
+ inputOptions.plugins.push(aliasHono());
27
+ }
28
+ return inputOptions;
29
+ }
30
+ async function createWatcher(inputOptions, outputOptions) {
31
+ const watcher = await watch({
32
+ ...inputOptions,
33
+ output: {
34
+ ...outputOptions,
35
+ format: "esm",
36
+ entryFileNames: "[name].mjs",
37
+ chunkFileNames: "[name].mjs"
38
+ }
39
+ });
40
+ return watcher;
41
+ }
42
+
43
+ // src/build/babel/remove-all-options-server.ts
44
+ function removeAllOptionsExceptServer(result) {
45
+ return removeAllOptionsFromMastraExcept(result, "server");
46
+ }
47
+ function getServerOptionsBundler(entryFile, result) {
48
+ return rollup({
49
+ logLevel: "silent",
50
+ input: {
51
+ "server-config": entryFile
52
+ },
53
+ treeshake: "smallest",
54
+ plugins: [
55
+ tsConfigPaths(),
56
+ // transpile typescript to something we understand
57
+ esbuild({
58
+ target: "node20",
59
+ platform: "node",
60
+ minify: false
61
+ }),
62
+ commonjs({
63
+ extensions: [".js", ".ts"],
64
+ strictRequires: "strict",
65
+ transformMixedEsModules: true,
66
+ ignoreTryCatch: false
67
+ }),
68
+ {
69
+ name: "get-server-config",
70
+ transform(code, id) {
71
+ if (id !== entryFile) {
72
+ return;
73
+ }
74
+ return new Promise((resolve, reject) => {
75
+ babel.transform(
76
+ code,
77
+ {
78
+ babelrc: false,
79
+ configFile: false,
80
+ filename: id,
81
+ plugins: [removeAllOptionsExceptServer(result)]
82
+ },
83
+ (err, result2) => {
84
+ if (err) {
85
+ return reject(err);
86
+ }
87
+ resolve({
88
+ code: result2.code,
89
+ map: result2.map
90
+ });
91
+ }
92
+ );
93
+ });
94
+ }
95
+ },
96
+ // let esbuild remove all unused imports
97
+ esbuild({
98
+ target: "node20",
99
+ platform: "node",
100
+ minify: false
101
+ }),
102
+ {
103
+ name: "cleanup",
104
+ transform(code, id) {
105
+ if (id !== entryFile) {
106
+ return;
107
+ }
108
+ return recursiveRemoveNonReferencedNodes(code);
109
+ }
110
+ },
111
+ // let esbuild remove all unused imports
112
+ esbuild({
113
+ target: "node20",
114
+ platform: "node",
115
+ minify: false
116
+ })
117
+ ]
118
+ });
119
+ }
120
+ async function getServerOptions(entryFile, outputDir) {
121
+ const result = {
122
+ hasCustomConfig: false
123
+ };
124
+ const bundle = await getServerOptionsBundler(entryFile, result);
125
+ await bundle.write({
126
+ dir: outputDir,
127
+ format: "es",
128
+ entryFileNames: "[name].mjs"
129
+ });
130
+ if (result.hasCustomConfig) {
131
+ return (await import(`file:${outputDir}/server-config.mjs`)).server;
132
+ }
133
+ return null;
134
+ }
135
+
136
+ export { createWatcher, getInputOptions2 as getInputOptions, getServerOptions };
@@ -0,0 +1,312 @@
1
+ 'use strict';
2
+
3
+ var chunk54KOF3NB_cjs = require('./chunk-54KOF3NB.cjs');
4
+ var commonjs = require('@rollup/plugin-commonjs');
5
+ var json = require('@rollup/plugin-json');
6
+ var nodeResolve = require('@rollup/plugin-node-resolve');
7
+ var virtual = require('@rollup/plugin-virtual');
8
+ var fs = require('fs');
9
+ var url = require('url');
10
+ var rollup = require('rollup');
11
+ var esbuild = require('rollup-plugin-esbuild');
12
+ var module$1 = require('module');
13
+ var path = require('path');
14
+ var child_process = require('child_process');
15
+ var promises = require('fs/promises');
16
+
17
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
+
19
+ var commonjs__default = /*#__PURE__*/_interopDefault(commonjs);
20
+ var json__default = /*#__PURE__*/_interopDefault(json);
21
+ var nodeResolve__default = /*#__PURE__*/_interopDefault(nodeResolve);
22
+ var virtual__default = /*#__PURE__*/_interopDefault(virtual);
23
+ var esbuild__default = /*#__PURE__*/_interopDefault(esbuild);
24
+
25
+ function isNodeBuiltin(dep) {
26
+ const [pkg] = dep.split("/");
27
+ return dep.startsWith("node:") || module$1.builtinModules.includes(dep) || module$1.builtinModules.includes(pkg);
28
+ }
29
+ function aliasHono() {
30
+ return {
31
+ name: "hono-alias",
32
+ resolveId(id) {
33
+ if (!id.startsWith("@hono/") && !id.startsWith("hono/") && id !== "hono" && id !== "hono-openapi") {
34
+ return;
35
+ }
36
+ const path = undefined(id);
37
+ return url.fileURLToPath(path);
38
+ }
39
+ };
40
+ }
41
+ function spawn(command, args = [], options = {}) {
42
+ return new Promise((resolve, reject) => {
43
+ const childProcess = child_process.spawn(command, args, {
44
+ // stdio: 'inherit',
45
+ ...options
46
+ });
47
+ childProcess.on("error", (error) => {
48
+ reject(error);
49
+ });
50
+ let stderr = "";
51
+ childProcess.stderr?.on("data", (message) => {
52
+ stderr += message;
53
+ });
54
+ childProcess.on("close", (code) => {
55
+ if (code === 0) {
56
+ resolve();
57
+ } else {
58
+ reject(new Error(stderr));
59
+ }
60
+ });
61
+ });
62
+ }
63
+ function validate(file) {
64
+ return spawn(
65
+ "node",
66
+ [
67
+ "--import",
68
+ undefined("@mastra/deployer/loader"),
69
+ "--input-type=module",
70
+ "-e",
71
+ `import('file://${file.replaceAll("\\", "/")}')`
72
+ ],
73
+ {
74
+ cwd: path.dirname(file)
75
+ }
76
+ );
77
+ }
78
+ var globalExternals = ["pino", "pino-pretty", "@libsql/client", "pg", "libsql", "jsdom", "sqlite3"];
79
+ function findExternalImporter(module, external, allOutputs) {
80
+ const capturedFiles = /* @__PURE__ */ new Set();
81
+ for (const id of module.imports) {
82
+ if (id === external) {
83
+ return module;
84
+ } else {
85
+ if (id.endsWith(".mjs")) {
86
+ capturedFiles.add(id);
87
+ }
88
+ }
89
+ }
90
+ for (const file of capturedFiles) {
91
+ const nextModule = allOutputs.find((o) => o.fileName === file);
92
+ if (nextModule) {
93
+ const importer = findExternalImporter(nextModule, external, allOutputs);
94
+ if (importer) {
95
+ return importer;
96
+ }
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+ async function analyze(entry, mastraEntry, isVirtualFile, platform, logger) {
102
+ logger.info("Analyzing dependencies...");
103
+ let virtualPlugin = null;
104
+ if (isVirtualFile) {
105
+ virtualPlugin = virtual__default.default({
106
+ "#entry": entry
107
+ });
108
+ entry = "#entry";
109
+ }
110
+ const normalizedMastraEntry = mastraEntry.replaceAll("\\", "/");
111
+ const optimizerBundler = await rollup.rollup({
112
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
113
+ input: isVirtualFile ? "#entry" : entry,
114
+ treeshake: "smallest",
115
+ preserveSymlinks: true,
116
+ plugins: [
117
+ virtualPlugin,
118
+ chunk54KOF3NB_cjs.tsConfigPaths(),
119
+ {
120
+ name: "custom-alias-resolver",
121
+ resolveId(id) {
122
+ if (id === "#server") {
123
+ return url.fileURLToPath(undefined("@mastra/deployer/server")).replaceAll("\\", "/");
124
+ }
125
+ if (id === "#mastra") {
126
+ return normalizedMastraEntry;
127
+ }
128
+ if (id.startsWith("@mastra/server")) {
129
+ return url.fileURLToPath(undefined(id));
130
+ }
131
+ }
132
+ },
133
+ json__default.default(),
134
+ esbuild__default.default({
135
+ target: "node20",
136
+ platform,
137
+ minify: false
138
+ }),
139
+ commonjs__default.default({
140
+ strictRequires: "debug",
141
+ ignoreTryCatch: false,
142
+ transformMixedEsModules: true,
143
+ extensions: [".js", ".ts"]
144
+ }),
145
+ chunk54KOF3NB_cjs.removeDeployer(normalizedMastraEntry),
146
+ esbuild__default.default({
147
+ target: "node20",
148
+ platform,
149
+ minify: false
150
+ })
151
+ ].filter(Boolean)
152
+ });
153
+ const { output } = await optimizerBundler.generate({
154
+ format: "esm",
155
+ inlineDynamicImports: true
156
+ });
157
+ await optimizerBundler.close();
158
+ const depsToOptimize = new Map(Object.entries(output[0].importedBindings));
159
+ for (const dep of depsToOptimize.keys()) {
160
+ if (isNodeBuiltin(dep)) {
161
+ depsToOptimize.delete(dep);
162
+ }
163
+ }
164
+ return depsToOptimize;
165
+ }
166
+ async function bundleExternals(depsToOptimize, outputDir, logger) {
167
+ logger.info("Optimizing dependencies...");
168
+ logger.debug(
169
+ `${Array.from(depsToOptimize.keys()).map((key) => `- ${key}`).join("\n")}`
170
+ );
171
+ const reverseVirtualReferenceMap = /* @__PURE__ */ new Map();
172
+ const virtualDependencies = /* @__PURE__ */ new Map();
173
+ for (const [dep, exports] of depsToOptimize.entries()) {
174
+ const name = dep.replaceAll("/", "-");
175
+ reverseVirtualReferenceMap.set(name, dep);
176
+ const virtualFile = [];
177
+ let exportStringBuilder = [];
178
+ for (const local of exports) {
179
+ if (local === "*") {
180
+ virtualFile.push(`export * from '${dep}';`);
181
+ } else if (local === "default") {
182
+ virtualFile.push(`export { default } from '${dep}';`);
183
+ } else {
184
+ exportStringBuilder.push(local);
185
+ }
186
+ }
187
+ if (exportStringBuilder.length > 0) {
188
+ virtualFile.push(`export { ${exportStringBuilder.join(", ")} } from '${dep}';`);
189
+ }
190
+ virtualDependencies.set(dep, {
191
+ name,
192
+ virtual: virtualFile.join("\n")
193
+ });
194
+ }
195
+ const bundler = await rollup.rollup({
196
+ logLevel: process.env.MASTRA_BUNDLER_DEBUG === "true" ? "debug" : "silent",
197
+ input: Array.from(virtualDependencies.entries()).reduce(
198
+ (acc, [dep, virtualDep]) => {
199
+ acc[virtualDep.name] = `#virtual-${dep}`;
200
+ return acc;
201
+ },
202
+ {}
203
+ ),
204
+ // this dependency breaks the build, so we need to exclude it
205
+ // TODO actually fix this so we don't need to exclude it
206
+ external: globalExternals,
207
+ treeshake: "smallest",
208
+ plugins: [
209
+ virtual__default.default(
210
+ Array.from(virtualDependencies.entries()).reduce(
211
+ (acc, [dep, virtualDep]) => {
212
+ acc[`#virtual-${dep}`] = virtualDep.virtual;
213
+ return acc;
214
+ },
215
+ {}
216
+ )
217
+ ),
218
+ commonjs__default.default({
219
+ strictRequires: "strict",
220
+ transformMixedEsModules: true,
221
+ ignoreTryCatch: false
222
+ }),
223
+ nodeResolve__default.default({
224
+ preferBuiltins: true,
225
+ exportConditions: ["node", "import", "require"],
226
+ mainFields: ["module", "main"]
227
+ }),
228
+ // hono is imported from deployer, so we need to resolve from here instead of the project root
229
+ aliasHono(),
230
+ json__default.default()
231
+ ].filter(Boolean)
232
+ });
233
+ const { output } = await bundler.write({
234
+ format: "esm",
235
+ dir: outputDir,
236
+ entryFileNames: "[name].mjs",
237
+ chunkFileNames: "[name].mjs",
238
+ hoistTransitiveImports: false
239
+ });
240
+ const moduleResolveMap = {};
241
+ const filteredChunks = output.filter((o) => o.type === "chunk");
242
+ for (const o of filteredChunks.filter((o2) => o2.isEntry || o2.isDynamicEntry)) {
243
+ for (const external of globalExternals) {
244
+ const importer = findExternalImporter(o, external, filteredChunks);
245
+ if (importer) {
246
+ const fullPath = path.join(outputDir, importer.fileName);
247
+ moduleResolveMap[fullPath] = moduleResolveMap[fullPath] || {};
248
+ if (importer.moduleIds.length) {
249
+ moduleResolveMap[fullPath][external] = importer.moduleIds[importer.moduleIds.length - 1]?.startsWith(
250
+ "\0virtual:#virtual"
251
+ ) ? importer.moduleIds[importer.moduleIds.length - 2] : importer.moduleIds[importer.moduleIds.length - 1];
252
+ }
253
+ }
254
+ }
255
+ }
256
+ await promises.writeFile(path.join(outputDir, "module-resolve-map.json"), JSON.stringify(moduleResolveMap, null, 2));
257
+ await bundler.close();
258
+ return { output, reverseVirtualReferenceMap, usedExternals: moduleResolveMap };
259
+ }
260
+ async function validateOutput({
261
+ output,
262
+ reverseVirtualReferenceMap,
263
+ usedExternals,
264
+ outputDir
265
+ }, logger) {
266
+ const result = {
267
+ invalidChunks: /* @__PURE__ */ new Set(),
268
+ dependencies: /* @__PURE__ */ new Map(),
269
+ externalDependencies: /* @__PURE__ */ new Set()
270
+ };
271
+ for (const deps of Object.values(usedExternals)) {
272
+ for (const dep of Object.keys(deps)) {
273
+ result.externalDependencies.add(dep);
274
+ }
275
+ }
276
+ for (const file of output) {
277
+ if (file.type === "asset") {
278
+ continue;
279
+ }
280
+ try {
281
+ logger.debug(`Validating if ${file.fileName} is a valid module.`);
282
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
283
+ result.dependencies.set(reverseVirtualReferenceMap.get(file.name), file.fileName);
284
+ }
285
+ if (!file.isDynamicEntry && file.isEntry) {
286
+ await validate(path.join(outputDir, file.fileName));
287
+ }
288
+ } catch (err) {
289
+ result.invalidChunks.add(file.fileName);
290
+ if (file.isEntry && reverseVirtualReferenceMap.has(file.name)) {
291
+ const reference = reverseVirtualReferenceMap.get(file.name);
292
+ const dep = reference.startsWith("@") ? reference.split("/").slice(0, 2).join("/") : reference.split("/")[0];
293
+ result.externalDependencies.add(dep);
294
+ }
295
+ }
296
+ }
297
+ return result;
298
+ }
299
+ async function analyzeBundle(entry, mastraEntry, outputDir, platform, logger) {
300
+ const isVirtualFile = entry.includes("\n") || !fs.existsSync(entry);
301
+ const depsToOptimize = await analyze(entry, mastraEntry, isVirtualFile, platform, logger);
302
+ const { output, reverseVirtualReferenceMap, usedExternals } = await bundleExternals(
303
+ depsToOptimize,
304
+ outputDir,
305
+ logger
306
+ );
307
+ const result = await validateOutput({ output, reverseVirtualReferenceMap, usedExternals, outputDir }, logger);
308
+ return result;
309
+ }
310
+
311
+ exports.aliasHono = aliasHono;
312
+ exports.analyzeBundle = analyzeBundle;