@mastra/deployer 1.58.0-alpha.1 → 1.58.0-alpha.13

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