@mastra/deployer 1.80.0-alpha.7 → 1.81.0-alpha.0

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