@mastra/deployer 1.58.0-alpha.12 → 1.58.0-alpha.14

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @mastra/deployer
2
2
 
3
+ ## 1.58.0-alpha.14
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`210cb7a`](https://github.com/mastra-ai/mastra/commit/210cb7a167998c7bbf72cb3b93e6eb0563330239), [`5f798b3`](https://github.com/mastra-ai/mastra/commit/5f798b3362e9bdf4d690f85245606e146eef60b9), [`01a2943`](https://github.com/mastra-ai/mastra/commit/01a2943a7d886edefdff072bfa51f055bab54437), [`01a2943`](https://github.com/mastra-ai/mastra/commit/01a2943a7d886edefdff072bfa51f055bab54437), [`25ca73d`](https://github.com/mastra-ai/mastra/commit/25ca73d25dee7ce9f0ca72939e3a505c4db7257e), [`e1cead1`](https://github.com/mastra-ai/mastra/commit/e1cead17b5f3653cf00d2f90cc19b113119c02ba), [`01a2943`](https://github.com/mastra-ai/mastra/commit/01a2943a7d886edefdff072bfa51f055bab54437)]:
8
+ - @mastra/core@1.58.0-alpha.14
9
+ - @mastra/server@1.58.0-alpha.14
10
+
11
+ ## 1.58.0-alpha.13
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [[`9571e3a`](https://github.com/mastra-ai/mastra/commit/9571e3a06ed2c5220196460bf82a2129255c3a8b), [`d6c56f9`](https://github.com/mastra-ai/mastra/commit/d6c56f951db3213330b98b0abafa9778c8770e58), [`9571e3a`](https://github.com/mastra-ai/mastra/commit/9571e3a06ed2c5220196460bf82a2129255c3a8b), [`acc3513`](https://github.com/mastra-ai/mastra/commit/acc3513b19f79bf0a7ec2998694580edca54086c), [`94e7ae9`](https://github.com/mastra-ai/mastra/commit/94e7ae970b37c888cd1244ef013292639a2fe6d1), [`6a667b4`](https://github.com/mastra-ai/mastra/commit/6a667b4b7cd6a93fe41fcdd357b08c5a8c09b9ab), [`2440e09`](https://github.com/mastra-ai/mastra/commit/2440e096ea6c2def1ccc1eb2d0f3f5b88c4af940), [`d6c56f9`](https://github.com/mastra-ai/mastra/commit/d6c56f951db3213330b98b0abafa9778c8770e58), [`a59049b`](https://github.com/mastra-ai/mastra/commit/a59049b1652a13efff66ac826326b5ed9a550342)]:
16
+ - @mastra/core@1.58.0-alpha.13
17
+ - @mastra/server@1.58.0-alpha.13
18
+
3
19
  ## 1.58.0-alpha.12
4
20
 
5
21
  ### Patch Changes
@@ -34,12 +34,6 @@ export interface BundlerOptions {
34
34
  enableEsmShim: boolean;
35
35
  externals: boolean | string[];
36
36
  dynamicPackages?: string[];
37
- /**
38
- * Extra process entries to emit beside the server bundle, as output name ->
39
- * absolute source path. Already resolved and validated against the user's
40
- * `bundler.entries` config; see `resolveExtraEntries`.
41
- */
42
- entries?: Record<string, string>;
43
37
  }
44
38
  /**
45
39
  * Version information for an external dependency
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/build/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB;;OAEG;IACH,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB;;OAEG;IACH,WAAW,EAAE,OAAO,CAAC;IACrB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,cAAc;IAC7B,eAAe,EAAE,OAAO,CAAC;IACzB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,EAAE,OAAO,CAAC;IACvB,SAAS,EAAE,OAAO,GAAG,MAAM,EAAE,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/build/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB;;OAEG;IACH,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB;;OAEG;IACH,WAAW,EAAE,OAAO,CAAC;IACrB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,cAAc;IAC7B,eAAe,EAAE,OAAO,CAAC;IACzB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,EAAE,OAAO,CAAC;IACvB,SAAS,EAAE,OAAO,GAAG,MAAM,EAAE,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACrC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB"}
@@ -1,7 +1,509 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_bundler = require("../bundler-DLXwkS7b.cjs");
3
- exports.Bundler = require_bundler.Bundler;
4
- exports.IS_DEFAULT = require_bundler.IS_DEFAULT;
5
- exports.applySourceDependencyRange = require_bundler.applySourceDependencyRange;
6
- exports.getSourceDependencyConstraints = require_bundler.getSourceDependencyConstraints;
7
- exports.isRegistryVersionSpec = require_bundler.isRegistryVersionSpec;
2
+ const require_rolldown_runtime = require("../rolldown-runtime-emK7D4bc.cjs");
3
+ const require_analyze = require("../analyze-BIrkd7zx.cjs");
4
+ const require_utils = require("../utils-O98BGdnP.cjs");
5
+ const require_services = require("../services-_ksvysL5.cjs");
6
+ const require_bundler = require("../bundler-DCGtF4jP.cjs");
7
+ const require_bundlerOptions = require("../bundlerOptions-CjjAPZYp.cjs");
8
+ let child_process = require("child_process");
9
+ let fs = require("fs");
10
+ let fs_promises = require("fs/promises");
11
+ let path = require("path");
12
+ let _mastra_core_bundler = require("@mastra/core/bundler");
13
+ let _mastra_core_error = require("@mastra/core/error");
14
+ let _rollup_plugin_virtual = require("@rollup/plugin-virtual");
15
+ _rollup_plugin_virtual = require_rolldown_runtime.__toESM(_rollup_plugin_virtual, 1);
16
+ let empathic_package = require("empathic/package");
17
+ empathic_package = require_rolldown_runtime.__toESM(empathic_package, 1);
18
+ let fs_extra_esm = require("fs-extra/esm");
19
+ fs_extra_esm = require_rolldown_runtime.__toESM(fs_extra_esm, 1);
20
+ let tinyglobby = require("tinyglobby");
21
+ //#region src/bundler/index.ts
22
+ const IS_DEFAULT = Symbol("IS_DEFAULT");
23
+ const NPM_ALIAS_PREFIX = "npm:";
24
+ /** Characters a registry range or dist tag can contain. Protocols need `:`, git shorthand needs `/` or `#`. */
25
+ const REGISTRY_SPEC_PATTERN = /^[A-Za-z0-9.+_^~><=*|!\s-]+$/;
26
+ const PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/;
27
+ const TARBALL_SUFFIX_PATTERN = /\.(?:tgz|tar\.gz|tar)$/i;
28
+ /** npm reads a value starting like this as a path, whatever follows. A bare `~` is a semver range. */
29
+ const FILE_SPEC_PREFIX_PATTERN = /^(?:\.|~[/\\]|[/\\]|[A-Za-z]:[/\\])/;
30
+ /** A range admitting any published version: `*`, `x`, `>=0`, and any union containing one. */
31
+ const UNBOUNDED_RANGE_PATTERN = /(?:^|\|\||\s)\s*(?:[*xX]|>=?\s*0(?:\.0)*(?:\.0)*)\s*(?:$|\|\|)/;
32
+ const toStringRecord = (value) => {
33
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
34
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
35
+ };
36
+ /**
37
+ * True when a specifier is something the isolated install in `.mastra/output` can resolve from the
38
+ * registry: a semver range, a dist tag, a wildcard, or an npm alias whose target is a registry
39
+ * package and range.
40
+ *
41
+ * This is an allowlist rather than a denylist of known protocols, so an unfamiliar protocol is
42
+ * rejected without this code having to know it exists. The output directory is not a workspace, has
43
+ * no catalog definitions and has a different relative-path base, so `catalog:`, `workspace:`,
44
+ * `file:`, `link:` and git specifiers are all either uninstallable there or point somewhere else.
45
+ */
46
+ const isRegistryVersionSpec = (spec) => {
47
+ if (FILE_SPEC_PREFIX_PATTERN.test(spec) || TARBALL_SUFFIX_PATTERN.test(spec)) return false;
48
+ if (spec.startsWith(NPM_ALIAS_PREFIX)) {
49
+ const alias = spec.slice(4);
50
+ const rangeSeparator = alias.lastIndexOf("@");
51
+ const name = rangeSeparator > 0 ? alias.slice(0, rangeSeparator) : alias;
52
+ const range = rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : "*";
53
+ return PACKAGE_NAME_PATTERN.test(name) && isRegistryVersionSpec(range);
54
+ }
55
+ return REGISTRY_SPEC_PATTERN.test(spec);
56
+ };
57
+ /**
58
+ * True when a specifier names a version the output install can be held to.
59
+ *
60
+ * A range admitting anything (`*`, `latest`, `>=0`, an alias with no range) is looser than the
61
+ * version already resolved, so writing it would let a later install pull something the bundle was
62
+ * never analyzed against.
63
+ */
64
+ const isBoundedVersionSpec = (spec) => {
65
+ const range = spec.startsWith(NPM_ALIAS_PREFIX) ? (() => {
66
+ const alias = spec.slice(4);
67
+ const rangeSeparator = alias.lastIndexOf("@");
68
+ return rangeSeparator > 0 ? alias.slice(rangeSeparator + 1) : "";
69
+ })() : spec;
70
+ return /\d/.test(range) && !UNBOUNDED_RANGE_PATTERN.test(range);
71
+ };
72
+ const readManifest = async (manifestPath) => {
73
+ if (!manifestPath) return;
74
+ try {
75
+ const manifest = await (0, fs_extra_esm.readJSON)(manifestPath);
76
+ return manifest && typeof manifest === "object" ? manifest : void 0;
77
+ } catch {
78
+ return;
79
+ }
80
+ };
81
+ /** Collect the package names a manifest's resolution fields pin, ignoring their values. */
82
+ const collectManifestPinnedNames = (manifest, pinned) => {
83
+ const pnpmSection = manifest?.pnpm;
84
+ const records = [
85
+ manifest?.overrides,
86
+ manifest?.resolutions,
87
+ pnpmSection && typeof pnpmSection === "object" ? pnpmSection.overrides : void 0
88
+ ];
89
+ for (const record of records) if (record && typeof record === "object" && !Array.isArray(record)) for (const key of Object.keys(record)) pinned.add(key);
90
+ };
91
+ /**
92
+ * Collect the names under a top-level `overrides:` block in `pnpm-workspace.yaml`.
93
+ *
94
+ * pnpm moved overrides out of `package.json` into this file, so a workspace on a current pnpm keeps
95
+ * them only here. Reading names off the indented block avoids a YAML dependency, the same tradeoff
96
+ * `copyPnpmWorkspaceSettings` already makes for the top-level keys it copies.
97
+ */
98
+ const collectPnpmWorkspacePinnedNames = (source, pinned) => {
99
+ const lines = source.split(/\r?\n/);
100
+ let insideOverrides = false;
101
+ for (const line of lines) {
102
+ if (/^\S/.test(line)) {
103
+ insideOverrides = /^overrides:\s*$/.test(line);
104
+ continue;
105
+ }
106
+ if (!insideOverrides) continue;
107
+ const key = /^\s+(?:'([^']+)'|"([^"]+)"|([^'"\s:][^:]*?))\s*:/.exec(line);
108
+ if (key) pinned.add((key[1] ?? key[2] ?? key[3] ?? "").trim());
109
+ }
110
+ };
111
+ /**
112
+ * Read the constraints the source app declared.
113
+ *
114
+ * `dependencies` come from the manifest at `projectRoot`, the package the build was invoked for and
115
+ * whose directory receives the output, falling back to the manifest above the entry file. Anchoring
116
+ * on `projectRoot` rather than the entry file keeps the answer deterministic when the entry handed
117
+ * to the bundler is a generated wrapper rather than the app's own source file.
118
+ *
119
+ * Resolution-field names are collected from both that manifest and the workspace root, including the
120
+ * root `pnpm-workspace.yaml`, because a name pinned anywhere means the resolved version may have been
121
+ * chosen deliberately rather than hoisted by accident.
122
+ */
123
+ const getSourceDependencyConstraints = async ({ projectRoot, mastraEntryFile, workspaceRoot }) => {
124
+ const manifestPaths = [empathic_package.up({ cwd: projectRoot }), empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) })].filter((entry, index, entries) => !!entry && entries.indexOf(entry) === index);
125
+ if (workspaceRoot) manifestPaths.push((0, path.join)(workspaceRoot, "package.json"));
126
+ const pinnedByResolutionField = /* @__PURE__ */ new Set();
127
+ let dependencies;
128
+ for (const manifestPath of manifestPaths) {
129
+ const manifest = await readManifest(manifestPath);
130
+ if (!manifest) continue;
131
+ dependencies ??= toStringRecord(manifest.dependencies);
132
+ collectManifestPinnedNames(manifest, pinnedByResolutionField);
133
+ }
134
+ if (workspaceRoot) try {
135
+ collectPnpmWorkspacePinnedNames(await (0, fs_promises.readFile)((0, path.join)(workspaceRoot, "pnpm-workspace.yaml"), "utf-8"), pinnedByResolutionField);
136
+ } catch {}
137
+ return {
138
+ dependencies: dependencies ?? {},
139
+ pinnedByResolutionField
140
+ };
141
+ };
142
+ const findDeclaredConstraint = (constraints, dependencyName) => {
143
+ const names = [dependencyName, require_utils.getPackageName(dependencyName)].filter((name, index, all) => !!name && all.indexOf(name) === index);
144
+ for (const name of names) if (constraints.pinnedByResolutionField.has(name)) return;
145
+ for (const name of names) {
146
+ const declared = (constraints.dependencies[name] ?? "").trim();
147
+ if (declared && isBoundedVersionSpec(declared) && isRegistryVersionSpec(declared)) return declared;
148
+ }
149
+ };
150
+ /**
151
+ * Prefer the constraint the app declared over the version resolved from `node_modules`.
152
+ *
153
+ * The resolved version is whatever the install happened to hoist, so an app declaring `zod: ^4.3.6`
154
+ * next to a hoisted `zod@3.25.76` gets the hoisted version written into the output manifest and the
155
+ * isolated install then locks it in.
156
+ */
157
+ const applySourceDependencyRange = (dependencyName, dependencyInfo, constraints) => {
158
+ const declared = findDeclaredConstraint(constraints, dependencyName);
159
+ if (!declared) return dependencyInfo;
160
+ if (declared.startsWith(NPM_ALIAS_PREFIX)) return {
161
+ ...dependencyInfo,
162
+ packageSpec: declared
163
+ };
164
+ if (dependencyInfo.packageSpec) return dependencyInfo;
165
+ return {
166
+ ...dependencyInfo,
167
+ version: declared
168
+ };
169
+ };
170
+ var Bundler = class extends _mastra_core_bundler.MastraBundler {
171
+ analyzeOutputDir = ".build";
172
+ outputDir = "output";
173
+ platform = "node";
174
+ constructor(name, component = "BUNDLER") {
175
+ super({
176
+ name,
177
+ component
178
+ });
179
+ }
180
+ async prepare(outputDirectory) {
181
+ await (0, fs_extra_esm.emptyDir)(outputDirectory);
182
+ await (0, fs_extra_esm.ensureDir)((0, path.join)(outputDirectory, this.analyzeOutputDir));
183
+ await (0, fs_extra_esm.ensureDir)((0, path.join)(outputDirectory, this.outputDir));
184
+ }
185
+ async writePackageJson(outputDirectory, dependencies, resolutions) {
186
+ this.logger.debug("Writing project's package.json");
187
+ await (0, fs_extra_esm.ensureDir)(outputDirectory);
188
+ const pkgPath = (0, path.join)(outputDirectory, "package.json");
189
+ const dependenciesMap = /* @__PURE__ */ new Map();
190
+ for (const [key, value] of dependencies.entries()) {
191
+ const dependencyValue = typeof value === "string" ? value : value.packageSpec ?? value.version ?? "latest";
192
+ if (key.startsWith("@")) {
193
+ const pkgChunks = key.split("/");
194
+ dependenciesMap.set(`${pkgChunks[0]}/${pkgChunks[1]}`, dependencyValue);
195
+ } else {
196
+ const pkgName = key.split("/")[0] || key;
197
+ dependenciesMap.set(pkgName, dependencyValue);
198
+ }
199
+ }
200
+ await (0, fs_promises.writeFile)(pkgPath, JSON.stringify({
201
+ name: "server",
202
+ version: "1.0.0",
203
+ private: true,
204
+ type: "module",
205
+ main: "index.mjs",
206
+ scripts: { start: "node ./index.mjs" },
207
+ dependencies: Object.fromEntries(dependenciesMap.entries()),
208
+ ...Object.keys(resolutions ?? {}).length > 0 && { resolutions }
209
+ }, null, 2));
210
+ }
211
+ createBundler(inputOptions, outputOptions) {
212
+ return require_bundler.createBundler(inputOptions, outputOptions);
213
+ }
214
+ async getUserBundlerOptions(mastraEntryFile, outputDirectory) {
215
+ const defaultBundlerOptions = {
216
+ externals: [],
217
+ sourcemap: false,
218
+ transpilePackages: [],
219
+ [IS_DEFAULT]: true
220
+ };
221
+ try {
222
+ return await require_bundlerOptions.getBundlerOptions(mastraEntryFile, outputDirectory) ?? defaultBundlerOptions;
223
+ } catch (error) {
224
+ this.logger.debug("Failed to get bundler options, sourcemap will be disabled", { error });
225
+ }
226
+ return defaultBundlerOptions;
227
+ }
228
+ async analyze(entry, mastraFile, outputDirectory) {
229
+ return await require_analyze.analyzeBundle([].concat(entry), mastraFile, {
230
+ outputDir: (0, path.join)(outputDirectory, this.analyzeOutputDir),
231
+ projectRoot: outputDirectory,
232
+ platform: this.platform
233
+ }, this.logger);
234
+ }
235
+ pnpmNodeLinker;
236
+ async installDependencies(outputDirectory, rootDir = process.cwd(), pnpmOverrides) {
237
+ const deps = new require_services.DepsService(rootDir);
238
+ deps.__setLogger(this.logger);
239
+ await deps.install({
240
+ dir: (0, path.join)(outputDirectory, this.outputDir),
241
+ pnpmOverrides,
242
+ pnpmNodeLinker: this.pnpmNodeLinker
243
+ });
244
+ }
245
+ /**
246
+ * Generate a package-lock.json for the output directory so that deploy targets
247
+ * can use `npm ci` instead of `npm install`, skipping version resolution entirely.
248
+ * This is a lockfile-only operation — no packages are downloaded.
249
+ *
250
+ * Temporarily moves node_modules out of the way because pnpm's symlink-based
251
+ * layout confuses npm's arborist, then restores it afterwards so that
252
+ * `mastra start` (or wrangler) can still resolve dependencies at runtime.
253
+ */
254
+ async generateNpmLockfile(outputDir) {
255
+ const nodeModules = (0, path.join)(outputDir, "node_modules");
256
+ const nodeModulesTmp = (0, path.join)(outputDir, "node_modules.__tmp");
257
+ let movedNodeModules = false;
258
+ try {
259
+ if (await fs_extra_esm.default.pathExists(nodeModules)) {
260
+ await fs_extra_esm.default.move(nodeModules, nodeModulesTmp, { overwrite: true });
261
+ movedNodeModules = true;
262
+ }
263
+ (0, child_process.execSync)("npm install --package-lock-only --force", {
264
+ cwd: outputDir,
265
+ stdio: "pipe",
266
+ timeout: 6e4
267
+ });
268
+ } catch {
269
+ this.logger.warn("Failed to generate package-lock.json — deploy will fall back to npm install");
270
+ } finally {
271
+ if (movedNodeModules) {
272
+ await (0, fs_promises.rm)(nodeModules, {
273
+ recursive: true,
274
+ force: true
275
+ });
276
+ await fs_extra_esm.default.move(nodeModulesTmp, nodeModules, { overwrite: true });
277
+ }
278
+ }
279
+ }
280
+ async copyPublic(mastraDir, outputDirectory) {
281
+ const publicDir = (0, path.join)(mastraDir, "public");
282
+ try {
283
+ await (0, fs_promises.stat)(publicDir);
284
+ } catch {
285
+ return;
286
+ }
287
+ await (0, fs_extra_esm.copy)(publicDir, (0, path.join)(outputDirectory, this.outputDir));
288
+ }
289
+ async copyDOTNPMRC({ rootDir = process.cwd(), outputDirectory }) {
290
+ const sourceDotNpmRcPath = (0, path.join)(rootDir, ".npmrc");
291
+ const targetDotNpmRcPath = (0, path.join)(outputDirectory, this.outputDir, ".npmrc");
292
+ try {
293
+ await (0, fs_promises.stat)(sourceDotNpmRcPath);
294
+ await (0, fs_extra_esm.copy)(sourceDotNpmRcPath, targetDotNpmRcPath);
295
+ } catch {
296
+ return;
297
+ }
298
+ }
299
+ /**
300
+ * Writes the `mastra-project.json` deployment marker for Software Factory
301
+ * projects after public assets have been copied. Verifies that the Factory
302
+ * SPA (`factory/index.html`) exists in the output before emitting the marker.
303
+ */
304
+ async writeFactoryMarker(outputDirectory) {
305
+ const outputDir = (0, path.join)(outputDirectory, this.outputDir);
306
+ if (!(0, fs.existsSync)((0, path.join)(outputDir, "factory", "index.html"))) throw new _mastra_core_error.MastraError({
307
+ id: "DEPLOYER_BUNDLER_FACTORY_UI_MISSING",
308
+ text: "Software Factory project detected but factory/index.html was not found after copying the prebuilt Factory UI.",
309
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
310
+ category: _mastra_core_error.ErrorCategory.SYSTEM
311
+ });
312
+ await (0, fs_promises.writeFile)((0, path.join)(outputDir, "mastra-project.json"), JSON.stringify({
313
+ schemaVersion: 1,
314
+ projectType: "factory",
315
+ assets: { ui: "factory" }
316
+ }, null, 2));
317
+ this.logger.info("Wrote mastra-project.json for Software Factory project");
318
+ }
319
+ async getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, { enableSourcemap, enableMinify, enableEsmShim, externals }) {
320
+ const { workspaceRoot } = await require_analyze.getWorkspaceInformation({ mastraEntryFile });
321
+ const closestPkgJson = empathic_package.up({ cwd: (0, path.dirname)(mastraEntryFile) });
322
+ const projectRoot = closestPkgJson ? (0, path.dirname)(closestPkgJson) : process.cwd();
323
+ const inputOptions = await require_bundler.getInputOptions(mastraEntryFile, analyzedBundleInfo, this.platform, { "process.env.NODE_ENV": JSON.stringify("production") }, {
324
+ sourcemap: enableSourcemap,
325
+ minify: enableMinify,
326
+ workspaceRoot,
327
+ projectRoot,
328
+ enableEsmShim,
329
+ externalsPreset: externals === true
330
+ });
331
+ const isVirtual = serverFile.includes("\n") || !(0, fs.existsSync)(serverFile);
332
+ const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);
333
+ if (isVirtual) {
334
+ inputOptions.input = {
335
+ index: "#entry",
336
+ ...toolsInputOptions
337
+ };
338
+ if (Array.isArray(inputOptions.plugins)) inputOptions.plugins.unshift((0, _rollup_plugin_virtual.default)({ "#entry": serverFile }));
339
+ else inputOptions.plugins = [(0, _rollup_plugin_virtual.default)({ "#entry": serverFile })];
340
+ } else inputOptions.input = {
341
+ index: serverFile,
342
+ ...toolsInputOptions
343
+ };
344
+ return inputOptions;
345
+ }
346
+ getAllToolPaths(mastraDir, toolsPaths = []) {
347
+ const normalizedMastraDir = require_utils.slash(mastraDir);
348
+ const defaultPaths = [path.posix.join(normalizedMastraDir, "tools/**/*.{js,ts}"), ...[`!${path.posix.join(normalizedMastraDir, "tools/**/*.{test,spec}.{js,ts}")}`, `!${path.posix.join(normalizedMastraDir, "tools/**/__tests__/**")}`]];
349
+ if (toolsPaths.length === 0) return [defaultPaths];
350
+ return [...toolsPaths, defaultPaths];
351
+ }
352
+ async listToolsInputOptions(toolsPaths) {
353
+ const inputs = {};
354
+ for (const toolPath of toolsPaths) {
355
+ const expandedPaths = await (0, tinyglobby.glob)(toolPath, {
356
+ absolute: true,
357
+ expandDirectories: false
358
+ });
359
+ for (const path$1 of expandedPaths) if (await fs_extra_esm.default.pathExists(path$1)) {
360
+ const entryFile = new require_services.FileService().getFirstExistingFile([
361
+ (0, path.join)(path$1, "index.ts"),
362
+ (0, path.join)(path$1, "index.js"),
363
+ path$1
364
+ ]);
365
+ if (!entryFile || (await (0, fs_promises.stat)(entryFile)).isDirectory()) {
366
+ this.logger.warn("No entry file found, skipping", { path: path$1 });
367
+ continue;
368
+ }
369
+ const uniqueToolID = crypto.randomUUID();
370
+ const normalizedEntryFile = entryFile.replaceAll("\\", "/");
371
+ inputs[`tools/${uniqueToolID}`] = normalizedEntryFile;
372
+ } else this.logger.warn("Tool path does not exist, skipping", { path: path$1 });
373
+ }
374
+ return inputs;
375
+ }
376
+ async _bundle(serverFile, mastraEntryFile, { projectRoot, outputDirectory, enableEsmShim = true }, toolsPaths = [], bundleLocation = (0, path.join)(outputDirectory, this.outputDir)) {
377
+ const analyzeDir = (0, path.join)(outputDirectory, this.analyzeOutputDir);
378
+ const bundlerOptions = await this.getUserBundlerOptions(mastraEntryFile, outputDirectory);
379
+ const internalBundlerOptions = {
380
+ enableSourcemap: !!bundlerOptions.sourcemap,
381
+ enableMinify: !!bundlerOptions.minify,
382
+ externals: bundlerOptions.externals ?? [],
383
+ enableEsmShim,
384
+ dynamicPackages: bundlerOptions.dynamicPackages
385
+ };
386
+ let analyzedBundleInfo;
387
+ try {
388
+ const resolvedToolsPaths = await this.listToolsInputOptions(toolsPaths);
389
+ analyzedBundleInfo = await require_analyze.analyzeBundle([serverFile, ...Object.values(resolvedToolsPaths)], mastraEntryFile, {
390
+ outputDir: analyzeDir,
391
+ projectRoot,
392
+ platform: this.platform,
393
+ bundlerOptions: internalBundlerOptions
394
+ }, this.logger);
395
+ } catch (error) {
396
+ const message = error instanceof Error ? error.message : String(error);
397
+ if (error instanceof _mastra_core_error.MastraError) throw error;
398
+ throw new _mastra_core_error.MastraError({
399
+ id: "DEPLOYER_BUNDLER_ANALYZE_FAILED",
400
+ text: `Failed to analyze Mastra application: ${message}`,
401
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
402
+ category: _mastra_core_error.ErrorCategory.SYSTEM
403
+ }, error);
404
+ }
405
+ const { workspaceRoot } = await require_analyze.getWorkspaceInformation({
406
+ dir: projectRoot,
407
+ mastraEntryFile
408
+ });
409
+ const sourceDependencyConstraints = await getSourceDependencyConstraints({
410
+ projectRoot,
411
+ mastraEntryFile,
412
+ workspaceRoot
413
+ });
414
+ const dependenciesToInstall = /* @__PURE__ */ new Map();
415
+ for (const [dep, depInfo] of analyzedBundleInfo.externalDependencies) {
416
+ if (analyzedBundleInfo.workspaceMap.has(dep) || !require_utils.isBareModuleSpecifier(dep)) continue;
417
+ dependenciesToInstall.set(dep, applySourceDependencyRange(dep, depInfo, sourceDependencyConstraints));
418
+ }
419
+ const initialWorkspaceDependencies = /* @__PURE__ */ new Set();
420
+ for (const dep of analyzedBundleInfo.dependencies.keys()) {
421
+ const pkgName = require_utils.getPackageName(dep);
422
+ if (pkgName && analyzedBundleInfo.workspaceMap.has(pkgName)) initialWorkspaceDependencies.add(pkgName);
423
+ }
424
+ const transitiveWorkspaceDependencies = require_analyze.collectTransitiveWorkspaceDependencies({
425
+ workspaceMap: analyzedBundleInfo.workspaceMap,
426
+ initialDependencies: initialWorkspaceDependencies,
427
+ logger: this.logger
428
+ });
429
+ for (const [dep, packageSpec] of Object.entries(transitiveWorkspaceDependencies.resolutions)) dependenciesToInstall.set(dep, {
430
+ version: analyzedBundleInfo.workspaceMap.get(dep)?.version,
431
+ packageSpec
432
+ });
433
+ try {
434
+ await this.writePackageJson((0, path.join)(outputDirectory, this.outputDir), dependenciesToInstall, transitiveWorkspaceDependencies.resolutions);
435
+ if (transitiveWorkspaceDependencies.usedWorkspacePackages.size > 0) await require_analyze.packWorkspaceDependencies({
436
+ workspaceMap: analyzedBundleInfo.workspaceMap,
437
+ usedWorkspacePackages: transitiveWorkspaceDependencies.usedWorkspacePackages,
438
+ bundleOutputDir: (0, path.join)(outputDirectory, this.outputDir),
439
+ logger: this.logger
440
+ });
441
+ this.logger.info("Bundling Mastra application");
442
+ const inputOptions = await this.getBundlerOptions(serverFile, mastraEntryFile, analyzedBundleInfo, toolsPaths, internalBundlerOptions);
443
+ await (await this.createBundler({
444
+ ...inputOptions,
445
+ logLevel: inputOptions.logLevel === "silent" ? "warn" : inputOptions.logLevel,
446
+ onwarn: (warning) => {
447
+ if (warning.code === "CIRCULAR_DEPENDENCY") {
448
+ if (warning.ids?.[0]?.includes("node_modules")) return;
449
+ this.logger.warn("Circular dependency found", { dependency: warning.message.replace("Circular dependency: ", "") });
450
+ }
451
+ }
452
+ }, {
453
+ dir: bundleLocation,
454
+ manualChunks: { mastra: ["#mastra"] },
455
+ sourcemap: internalBundlerOptions.enableSourcemap
456
+ })).write();
457
+ const toolImports = [];
458
+ const toolsExports = [];
459
+ Array.from(Object.keys(inputOptions.input || {})).filter((key) => key.startsWith("tools/")).forEach((key, index) => {
460
+ const toolExport = `tool${index}`;
461
+ toolImports.push(`import * as ${toolExport} from './${key}.mjs';`);
462
+ toolsExports.push(toolExport);
463
+ });
464
+ await (0, fs_promises.writeFile)((0, path.join)(bundleLocation, "tools.mjs"), `${toolImports.join("\n")}
465
+
466
+ export const tools = [${toolsExports.join(", ")}]`);
467
+ this.logger.info("Bundling Mastra done");
468
+ this.logger.info("Copying public files");
469
+ await this.copyPublic((0, path.dirname)(mastraEntryFile), outputDirectory);
470
+ this.logger.info("Done copying public files");
471
+ if (analyzedBundleInfo.projectType === "factory") await this.writeFactoryMarker(outputDirectory);
472
+ this.logger.info("Copying .npmrc file");
473
+ await this.copyDOTNPMRC({
474
+ outputDirectory,
475
+ rootDir: projectRoot
476
+ });
477
+ this.logger.info("Done copying .npmrc file");
478
+ this.logger.info("Installing dependencies");
479
+ await this.installDependencies(outputDirectory, projectRoot, transitiveWorkspaceDependencies.resolutions);
480
+ this.logger.info("Done installing dependencies");
481
+ if (Object.keys(transitiveWorkspaceDependencies.resolutions).length === 0) {
482
+ this.logger.info("Generating package-lock.json for deploy");
483
+ await this.generateNpmLockfile((0, path.join)(outputDirectory, this.outputDir));
484
+ this.logger.info("Done generating package-lock.json");
485
+ } else this.logger.warn("Skipping package-lock.json generation because the output contains packed workspace dependencies");
486
+ } catch (error) {
487
+ if (error instanceof _mastra_core_error.MastraError && error.id === "DEPLOYER_BUNDLER_FACTORY_UI_MISSING") throw error;
488
+ throw new _mastra_core_error.MastraError({
489
+ id: "DEPLOYER_BUNDLER_BUNDLE_STAGE_FAILED",
490
+ text: `Failed during bundler bundle stage: ${error instanceof Error ? error.message : String(error)}`,
491
+ domain: _mastra_core_error.ErrorDomain.DEPLOYER,
492
+ category: _mastra_core_error.ErrorCategory.SYSTEM
493
+ }, error);
494
+ }
495
+ }
496
+ async lint(_entryFile, _outputDirectory, toolsPaths) {
497
+ const toolsInputOptions = await this.listToolsInputOptions(toolsPaths);
498
+ const toolsLength = Object.keys(toolsInputOptions).length;
499
+ if (toolsLength > 0) this.logger.info("Found tools", { count: toolsLength });
500
+ }
501
+ };
502
+ //#endregion
503
+ exports.Bundler = Bundler;
504
+ exports.IS_DEFAULT = IS_DEFAULT;
505
+ exports.applySourceDependencyRange = applySourceDependencyRange;
506
+ exports.getSourceDependencyConstraints = getSourceDependencyConstraints;
507
+ exports.isRegistryVersionSpec = isRegistryVersionSpec;
508
+
509
+ //# sourceMappingURL=index.cjs.map