@nest-boot/mastra 0.0.0-stage → 8.0.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.
@@ -0,0 +1,230 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var MastraStudioMiddleware_1;
14
+ import { randomUUID } from "node:crypto";
15
+ import fs from "node:fs";
16
+ import { createRequire } from "node:module";
17
+ import path from "node:path";
18
+ import { escapeStudioHtmlValue, injectStudioHtmlConfig, normalizeStudioBase, } from "@mastra/deployer/build";
19
+ import { Inject, Injectable, Logger, Optional, RequestMethod, } from "@nestjs/common";
20
+ import { ApplicationConfig } from "@nestjs/core";
21
+ import express from "express";
22
+ import { MASTRA_MODULE_OPTIONS, normalizeMastraApiOptions, normalizeMastraStudioOptions, resolveMastraStudioBasePath, } from "./mastra.module-definition.js";
23
+ const requireFromHere = createRequire(import.meta.url);
24
+ /**
25
+ * Resolves the bundled `mastra/dist/studio` directory path when the optional
26
+ * `mastra` peer dependency is installed.
27
+ * @param resolvePackage - Package specifier resolver (overridable for tests)
28
+ * @returns Absolute path to the Mastra Studio distribution directory, or `null` when unavailable
29
+ */
30
+ export function resolveMastraStudioDistDir(resolvePackage = (specifier) => requireFromHere.resolve(specifier)) {
31
+ try {
32
+ const mastraPkgPath = resolvePackage("mastra/package.json");
33
+ return path.join(path.dirname(mastraPkgPath), "dist", "studio");
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ /**
40
+ * Checks whether a route path is excluded from NestJS's configured global prefix.
41
+ * @param applicationConfig - NestJS application configuration
42
+ * @param routePath - Candidate route path without global prefix
43
+ * @param method - HTTP request method to match against exclude rules
44
+ * @returns True when the route matches a global prefix exclude entry
45
+ */
46
+ function isGlobalPrefixExcluded(applicationConfig, routePath, method) {
47
+ const excludedRoutes = applicationConfig?.getGlobalPrefixOptions().exclude;
48
+ if (!Array.isArray(excludedRoutes) || excludedRoutes.length === 0) {
49
+ return false;
50
+ }
51
+ const normalizedPath = routePath.startsWith("/")
52
+ ? routePath
53
+ : `/${routePath}`;
54
+ return excludedRoutes.some((route) => {
55
+ const matchesMethod = route.requestMethod === RequestMethod.ALL ||
56
+ route.requestMethod === method;
57
+ if (!matchesMethod) {
58
+ return false;
59
+ }
60
+ return route.pathRegex.test(normalizedPath);
61
+ });
62
+ }
63
+ /**
64
+ * Checks whether an unmatched Studio relative path looks like a missing static asset.
65
+ * @param relativePath - Request path relative to the Studio base path
66
+ * @returns True when the path should return 404 instead of SPA `index.html`
67
+ */
68
+ function looksLikeMissingAsset(relativePath) {
69
+ if (relativePath.startsWith("/assets/") ||
70
+ relativePath.startsWith("/dist/assets/")) {
71
+ return true;
72
+ }
73
+ return /\.[a-z0-9]{1,8}$/i.test(relativePath);
74
+ }
75
+ /**
76
+ * Express-backed NestJS middleware serving bundled Mastra Studio assets and SPA HTML
77
+ * at `${prefix}/studio` without requiring route-level authentication (matching GraphQL Playground).
78
+ */
79
+ let MastraStudioMiddleware = MastraStudioMiddleware_1 = class MastraStudioMiddleware {
80
+ options;
81
+ applicationConfig;
82
+ logger = new Logger(MastraStudioMiddleware_1.name);
83
+ router;
84
+ constructor(options, applicationConfig) {
85
+ this.options = options;
86
+ this.applicationConfig = applicationConfig;
87
+ }
88
+ /**
89
+ * Pre-builds the Studio router once NestJS has finished applying global prefix options,
90
+ * avoiding synchronous file I/O on the first incoming HTTP request.
91
+ */
92
+ onApplicationBootstrap() {
93
+ this.ensureRouter();
94
+ }
95
+ ensureRouter() {
96
+ if (this.router === undefined) {
97
+ this.router = this.createRouter();
98
+ }
99
+ return this.router;
100
+ }
101
+ /**
102
+ * Builds the Studio router after the host has configured its global prefix.
103
+ * @returns Mounted Studio router, or null when Studio is unavailable
104
+ */
105
+ createRouter() {
106
+ const { enabled: apiEnabled, serverOptions } = normalizeMastraApiOptions(this.options.api);
107
+ const studioOptions = normalizeMastraStudioOptions(this.options.studio, apiEnabled);
108
+ if (!studioOptions.enabled) {
109
+ return null;
110
+ }
111
+ const studioDir = resolveMastraStudioDistDir();
112
+ const indexPath = studioDir ? path.join(studioDir, "index.html") : null;
113
+ if (!studioDir || !indexPath || !fs.existsSync(indexPath)) {
114
+ this.logger.warn('Mastra Studio is enabled, but the optional "mastra" peer dependency (dist/studio/index.html) was not found. Install "mastra" to serve embedded Studio.');
115
+ return null;
116
+ }
117
+ const globalPrefix = normalizeStudioBase(this.applicationConfig?.getGlobalPrefix() ?? "");
118
+ const rawApiPrefix = serverOptions.prefix;
119
+ const rawStudioBasePath = resolveMastraStudioBasePath(rawApiPrefix);
120
+ const apiExcluded = globalPrefix.length > 0 &&
121
+ (isGlobalPrefixExcluded(this.applicationConfig, rawApiPrefix, RequestMethod.ALL) ||
122
+ isGlobalPrefixExcluded(this.applicationConfig, `${rawApiPrefix}/agents`, RequestMethod.GET));
123
+ const studioExcluded = globalPrefix.length > 0 &&
124
+ isGlobalPrefixExcluded(this.applicationConfig, rawStudioBasePath, RequestMethod.GET);
125
+ const apiPrefix = globalPrefix && !apiExcluded
126
+ ? `${globalPrefix}${rawApiPrefix}`
127
+ : rawApiPrefix;
128
+ const studioBasePath = globalPrefix && !studioExcluded
129
+ ? `${globalPrefix}${rawStudioBasePath}`
130
+ : rawStudioBasePath;
131
+ const devServerInstanceId = randomUUID();
132
+ const renderedIndexHtml = injectStudioHtmlConfig(fs.readFileSync(indexPath, "utf8"), {
133
+ basePath: studioBasePath,
134
+ host: "window.location.hostname",
135
+ port: "(window.location.port || (window.location.protocol === 'https:' ? '443' : '80'))",
136
+ protocol: "window.location.protocol.slice(0, -1)",
137
+ apiPrefix: `'${escapeStudioHtmlValue(apiPrefix)}'`,
138
+ cloudApiEndpoint: `''`,
139
+ autoDetectUrl: `'true'`,
140
+ hideCloudCta: `'${studioOptions.hideCloudCta ? "true" : "false"}'`,
141
+ telemetryDisabled: `'${studioOptions.telemetryDisabled ? "true" : "false"}'`,
142
+ experimentalFeatures: `'false'`,
143
+ templates: `'false'`,
144
+ requestContextPresets: `''`,
145
+ experimentalUI: `'false'`,
146
+ agentSignals: `'true'`,
147
+ signalsUI: `'false'`,
148
+ organizationId: `''`,
149
+ platformProjectId: `''`,
150
+ platformObservabilityEndpoint: `''`,
151
+ devServerInstanceId: `'${escapeStudioHtmlValue(devServerInstanceId)}'`,
152
+ });
153
+ const studioRouter = express.Router();
154
+ studioRouter.get("/refresh-events", (req, res) => {
155
+ res.status(200);
156
+ res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
157
+ res.setHeader("Cache-Control", "no-cache, no-transform");
158
+ res.setHeader("Connection", "keep-alive");
159
+ res.setHeader("X-Accel-Buffering", "no");
160
+ res.flushHeaders();
161
+ res.write(`id: ${devServerInstanceId}\ndata: connected\n\n`);
162
+ const keepAlive = setInterval(() => {
163
+ if (!res.writableEnded) {
164
+ res.write(": ping\n\n");
165
+ }
166
+ }, 30_000);
167
+ keepAlive.unref();
168
+ const cleanup = () => {
169
+ clearInterval(keepAlive);
170
+ if (!res.writableEnded) {
171
+ res.end();
172
+ }
173
+ };
174
+ req.on("close", cleanup);
175
+ res.on("close", cleanup);
176
+ });
177
+ const sendRenderedIndexHtml = (res) => {
178
+ res
179
+ .status(200)
180
+ .type("html")
181
+ .set("Cache-Control", "no-cache")
182
+ .send(renderedIndexHtml);
183
+ };
184
+ studioRouter.get(["/", "/index.html"], (_req, res) => {
185
+ sendRenderedIndexHtml(res);
186
+ });
187
+ studioRouter.use(express.static(studioDir, {
188
+ index: false,
189
+ redirect: false,
190
+ fallthrough: true,
191
+ setHeaders: (res, filePath) => {
192
+ if (filePath.includes(`${path.sep}assets${path.sep}`)) {
193
+ res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
194
+ }
195
+ },
196
+ }));
197
+ studioRouter.get("/{*path}", (req, res) => {
198
+ if (looksLikeMissingAsset(req.path)) {
199
+ res.status(404).end();
200
+ return;
201
+ }
202
+ sendRenderedIndexHtml(res);
203
+ });
204
+ const mountedRouter = express.Router();
205
+ mountedRouter.use(studioBasePath, studioRouter);
206
+ return mountedRouter;
207
+ }
208
+ /**
209
+ * Delegates incoming Studio requests to the mounted Express router.
210
+ * @param req - Incoming Express request
211
+ * @param res - Outgoing Express response
212
+ * @param next - Next middleware callback
213
+ */
214
+ use(req, res, next) {
215
+ const router = this.ensureRouter();
216
+ if (!router) {
217
+ next();
218
+ return;
219
+ }
220
+ void router(req, res, next);
221
+ }
222
+ };
223
+ MastraStudioMiddleware = MastraStudioMiddleware_1 = __decorate([
224
+ Injectable(),
225
+ __param(0, Inject(MASTRA_MODULE_OPTIONS)),
226
+ __param(1, Optional()),
227
+ __metadata("design:paramtypes", [Object, ApplicationConfig])
228
+ ], MastraStudioMiddleware);
229
+ export { MastraStudioMiddleware };
230
+ //# sourceMappingURL=mastra-studio.middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra-studio.middleware.js","sourceRoot":"","sources":["../src/mastra-studio.middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,IAAI,MAAM,WAAW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AAC;IAC9B,CAAC;CACF,CAAA;AAxMY,sBAAsB;IADlC,UAAU,EAAE;IAQR,WAAA,MAAM,CAAC,qBAAqB,CAAC,CAAA;IAE7B,WAAA,QAAQ,EAAE,CAAA;6CAAsC,iBAAiB;GATzD,sBAAsB,CAwMlC"}
@@ -0,0 +1,30 @@
1
+ import { type MastraModuleOptions as MastraCoreModuleOptions, MastraThrottleGuard, RequestContextService, RouteHandlerService } from "@mastra/nestjs";
2
+ import { ApplicationConfig } from "@nestjs/core";
3
+ import type { Request, Response } from "express";
4
+ import { type MastraModuleOptions } from "./mastra.module-definition.js";
5
+ interface RequestWithMastraMetadata extends Request {
6
+ mastraRawBodySize?: number;
7
+ }
8
+ /**
9
+ * NestJS controller exposing Mastra HTTP API routes under the configured prefix
10
+ * (default `/api/mastra`), reusing `@mastra/nestjs` services and interceptors while
11
+ * keeping full control over NestJS routing, guards, and authorization.
12
+ */
13
+ export declare class MastraController {
14
+ private readonly options;
15
+ private readonly routeHandler;
16
+ private readonly requestContext;
17
+ private readonly throttleGuard;
18
+ private readonly applicationConfig?;
19
+ private readonly apiEnabled;
20
+ constructor(moduleOptions: MastraModuleOptions, options: MastraCoreModuleOptions, routeHandler: RouteHandlerService, requestContext: RequestContextService, throttleGuard: MastraThrottleGuard, applicationConfig?: ApplicationConfig | undefined);
21
+ /**
22
+ * Dispatches incoming requests to matched Mastra API routes.
23
+ * @param req - Incoming Express request
24
+ * @param _res - Outgoing Express response managed by StreamingInterceptor
25
+ * @returns Mastra route handler result for StreamingInterceptor
26
+ */
27
+ handleRequest(req: RequestWithMastraMetadata, _res: Response): Promise<unknown>;
28
+ private parseBody;
29
+ }
30
+ export {};
@@ -0,0 +1,209 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { Mastra } from "@mastra/core/mastra";
14
+ import { MASTRA_OPTIONS, MastraExceptionFilter, MastraThrottleGuard, parseMultipartFormData, RequestContextService, RequestTrackingInterceptor, RouteHandlerService, StreamingInterceptor, TracingInterceptor, } from "@mastra/nestjs";
15
+ import { Can } from "@nest-boot/auth";
16
+ import { All, Controller, Inject, NotFoundException, Optional, PayloadTooLargeException, Req, Res, UseFilters, UseInterceptors, } from "@nestjs/common";
17
+ import { ApplicationConfig } from "@nestjs/core";
18
+ import { MASTRA_MODULE_OPTIONS, normalizeMastraApiOptions, } from "./mastra.module-definition.js";
19
+ const DANGEROUS_QUERY_KEYS = new Set(["__proto__", "prototype", "constructor"]);
20
+ const BODY_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
21
+ /**
22
+ * Normalizes a route prefix to either empty string or a leading-slash path without trailing slashes.
23
+ * @param prefix - Raw prefix string
24
+ * @returns Normalized route prefix
25
+ */
26
+ function normalizeRoutePrefix(prefix) {
27
+ let normalized = prefix?.trim() ?? "";
28
+ if (normalized && !normalized.startsWith("/")) {
29
+ normalized = `/${normalized}`;
30
+ }
31
+ while (normalized.endsWith("/")) {
32
+ normalized = normalized.slice(0, -1);
33
+ }
34
+ return normalized;
35
+ }
36
+ /**
37
+ * Strips the effective mounted prefix (accounting for NestJS global prefix and Mastra API prefix)
38
+ * from an incoming request path.
39
+ * @param requestPath - Express request path
40
+ * @param prefix - Configured Mastra API prefix
41
+ * @param globalPrefix - Optional NestJS application global prefix
42
+ * @returns Mastra-relative route path, or null when outside the prefix
43
+ */
44
+ function getMastraRoutePath(requestPath, prefix, globalPrefix) {
45
+ const normalizedPrefix = normalizeRoutePrefix(prefix);
46
+ const normalizedGlobalPrefix = normalizeRoutePrefix(globalPrefix);
47
+ const candidatePrefixes = normalizedGlobalPrefix
48
+ ? [`${normalizedGlobalPrefix}${normalizedPrefix}`, normalizedPrefix]
49
+ : [normalizedPrefix];
50
+ for (const candidatePrefix of candidatePrefixes) {
51
+ if (!candidatePrefix) {
52
+ return requestPath || "/";
53
+ }
54
+ if (requestPath === candidatePrefix ||
55
+ requestPath.startsWith(`${candidatePrefix}/`)) {
56
+ const routePath = requestPath.slice(candidatePrefix.length);
57
+ return routePath || "/";
58
+ }
59
+ }
60
+ return null;
61
+ }
62
+ /**
63
+ * Converts an Express request into a Web Fetch `Request` for Mastra handlers.
64
+ * @param req - Incoming Express request
65
+ * @returns Web-standard Request with method and headers
66
+ */
67
+ function toWebRequest(req) {
68
+ const hostHeader = req.get("host");
69
+ const host = hostHeader && hostHeader.length > 0 ? hostHeader : "localhost";
70
+ const url = `${req.protocol || "http"}://${host}${req.originalUrl || req.url}`;
71
+ const headers = new Headers();
72
+ for (const [key, value] of Object.entries(req.headers)) {
73
+ if (!value) {
74
+ continue;
75
+ }
76
+ if (Array.isArray(value)) {
77
+ for (const entry of value) {
78
+ headers.append(key, entry);
79
+ }
80
+ }
81
+ else {
82
+ headers.set(key, value);
83
+ }
84
+ }
85
+ return new globalThis.Request(url, {
86
+ method: req.method,
87
+ headers,
88
+ });
89
+ }
90
+ /**
91
+ * Normalizes Express query values to strings or string arrays while filtering unsafe keys.
92
+ * @param query - Express request query object
93
+ * @returns Sanitized query parameter record
94
+ */
95
+ function parseQueryParams(query) {
96
+ const result = {};
97
+ for (const [key, value] of Object.entries(query)) {
98
+ if (key === "requestContext" || DANGEROUS_QUERY_KEYS.has(key)) {
99
+ continue;
100
+ }
101
+ result[key] = value;
102
+ }
103
+ return result;
104
+ }
105
+ /**
106
+ * NestJS controller exposing Mastra HTTP API routes under the configured prefix
107
+ * (default `/api/mastra`), reusing `@mastra/nestjs` services and interceptors while
108
+ * keeping full control over NestJS routing, guards, and authorization.
109
+ */
110
+ let MastraController = class MastraController {
111
+ options;
112
+ routeHandler;
113
+ requestContext;
114
+ throttleGuard;
115
+ applicationConfig;
116
+ apiEnabled;
117
+ constructor(moduleOptions, options, routeHandler, requestContext, throttleGuard, applicationConfig) {
118
+ this.options = options;
119
+ this.routeHandler = routeHandler;
120
+ this.requestContext = requestContext;
121
+ this.throttleGuard = throttleGuard;
122
+ this.applicationConfig = applicationConfig;
123
+ this.apiEnabled = normalizeMastraApiOptions(moduleOptions.api).enabled;
124
+ }
125
+ /**
126
+ * Dispatches incoming requests to matched Mastra API routes.
127
+ * @param req - Incoming Express request
128
+ * @param _res - Outgoing Express response managed by StreamingInterceptor
129
+ * @returns Mastra route handler result for StreamingInterceptor
130
+ */
131
+ async handleRequest(req, _res) {
132
+ const requestPath = req.path;
133
+ const method = req.method.toUpperCase();
134
+ if (!this.apiEnabled) {
135
+ throw new NotFoundException(`Route not found: ${method} ${requestPath}`);
136
+ }
137
+ const routePath = getMastraRoutePath(requestPath, this.options.prefix, this.applicationConfig?.getGlobalPrefix());
138
+ const matchResult = routePath && !routePath.includes("//")
139
+ ? this.routeHandler.matchRoute(method, routePath)
140
+ : null;
141
+ if (!matchResult) {
142
+ throw new NotFoundException(`Route not found: ${method} ${requestPath}`);
143
+ }
144
+ const { route, pathParams } = matchResult;
145
+ if (this.options.rateLimitOptions?.enabled !== false && routePath) {
146
+ const { limit, windowMs } = this.throttleGuard.getRateLimitSettings(req, undefined, routePath);
147
+ await this.throttleGuard.checkLimit(req, limit, windowMs, routePath);
148
+ }
149
+ const queryParams = parseQueryParams(req.query);
150
+ const body = await this.parseBody(req, route.maxBodySize);
151
+ return await this.routeHandler.executeHandler(route, {
152
+ pathParams,
153
+ queryParams,
154
+ body,
155
+ requestContext: this.requestContext.requestContext,
156
+ abortSignal: this.requestContext.abortSignal,
157
+ request: toWebRequest(req),
158
+ });
159
+ }
160
+ async parseBody(req, routeMaxBodySize) {
161
+ if (!BODY_HTTP_METHODS.has(req.method.toUpperCase())) {
162
+ return undefined;
163
+ }
164
+ const contentType = req.headers["content-type"] ?? "";
165
+ if (contentType.includes("multipart/form-data")) {
166
+ return await parseMultipartFormData(req, {
167
+ maxFileSize: routeMaxBodySize ?? this.options.bodyLimitOptions?.maxFileSize,
168
+ allowedMimeTypes: this.options.bodyLimitOptions?.allowedMimeTypes,
169
+ });
170
+ }
171
+ if (routeMaxBodySize !== undefined) {
172
+ const rawBodySize = req.mastraRawBodySize;
173
+ const contentLength = Number.parseInt(req.headers["content-length"] ?? "", 10);
174
+ const bodySize = rawBodySize ??
175
+ (Number.isNaN(contentLength)
176
+ ? req.body === undefined
177
+ ? 0
178
+ : Buffer.byteLength(JSON.stringify(req.body), "utf8")
179
+ : contentLength);
180
+ if (bodySize > routeMaxBodySize) {
181
+ throw new PayloadTooLargeException("Request body too large");
182
+ }
183
+ }
184
+ return req.body === undefined ? {} : req.body;
185
+ }
186
+ };
187
+ __decorate([
188
+ All(["", "{*path}"]),
189
+ __param(0, Req()),
190
+ __param(1, Res({ passthrough: true })),
191
+ __metadata("design:type", Function),
192
+ __metadata("design:paramtypes", [Object, Object]),
193
+ __metadata("design:returntype", Promise)
194
+ ], MastraController.prototype, "handleRequest", null);
195
+ MastraController = __decorate([
196
+ Controller(),
197
+ Can("manage", Mastra),
198
+ UseInterceptors(RequestTrackingInterceptor, TracingInterceptor, StreamingInterceptor),
199
+ UseFilters(MastraExceptionFilter),
200
+ __param(0, Inject(MASTRA_MODULE_OPTIONS)),
201
+ __param(1, Inject(MASTRA_OPTIONS)),
202
+ __param(5, Optional()),
203
+ __metadata("design:paramtypes", [Object, Object, RouteHandlerService,
204
+ RequestContextService,
205
+ MastraThrottleGuard,
206
+ ApplicationConfig])
207
+ ], MastraController);
208
+ export { MastraController };
209
+ //# sourceMappingURL=mastra.controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mastra.controller.js","sourceRoot":"","sources":["../src/mastra.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EACL,cAAc,EACd,qBAAqB,EAErB,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACtC,OAAO,EACL,GAAG,EACH,UAAU,EACV,MAAM,EACN,iBAAiB,EACjB,QAAQ,EACR,wBAAwB,EACxB,GAAG,EACH,GAAG,EACH,UAAU,EACV,eAAe,GAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAGjD,OAAO,EACL,qBAAqB,EAErB,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AAEvC,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC;AAChF,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AAMtE;;;;GAIG;AACH,SAAS,oBAAoB,CAAC,MAAe;IAC3C,IAAI,UAAU,GAAG,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACtC,IAAI,UAAU,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QAC9C,UAAU,GAAG,IAAI,UAAU,EAAE,CAAC;IAChC,CAAC;IACD,OAAO,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAChC,UAAU,G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;GAXzD,gBAAgB,CA6G5B"}
@@ -0,0 +1,51 @@
1
+ import { Agent as MastraAgent } from "@mastra/core/agent";
2
+ import { Mastra } from "@mastra/core/mastra";
3
+ import { type AnyWorkflow } from "@mastra/core/workflows";
4
+ import { type OnApplicationShutdown, type OnModuleInit } from "@nestjs/common";
5
+ import { DiscoveryService } from "@nestjs/core";
6
+ /**
7
+ * Discovers singleton NestJS providers extending Mastra `Agent` (including `BaseAgent`)
8
+ * and Mastra `Workflow` (including `BaseWorkflow`) across all loaded modules and
9
+ * registers them into the shared `Mastra` instance.
10
+ */
11
+ export declare class MastraManager implements OnModuleInit, OnApplicationShutdown {
12
+ private readonly discovery;
13
+ private readonly mastra;
14
+ private readonly logger;
15
+ private readonly agents;
16
+ private readonly workflows;
17
+ private initialized;
18
+ private shutDown;
19
+ constructor(discovery: DiscoveryService, mastra: Mastra);
20
+ /**
21
+ * Scans NestJS providers and registers all discovered singleton Mastra agents and workflows.
22
+ */
23
+ onModuleInit(): void;
24
+ /**
25
+ * Returns all discovered and registered Mastra agents.
26
+ * @returns Array of registered Mastra agent instances
27
+ */
28
+ getAgents(): MastraAgent[];
29
+ /**
30
+ * Looks up a registered Mastra agent by its id.
31
+ * @param id - Agent id
32
+ * @returns Matching agent instance or undefined
33
+ */
34
+ getAgent(id: string): MastraAgent | undefined;
35
+ /**
36
+ * Returns all discovered and registered Mastra workflows.
37
+ * @returns Array of registered Mastra workflow instances
38
+ */
39
+ getWorkflows(): AnyWorkflow[];
40
+ /**
41
+ * Looks up a registered Mastra workflow by its id.
42
+ * @param id - Workflow id
43
+ * @returns Matching workflow instance or undefined
44
+ */
45
+ getWorkflow(id: string): AnyWorkflow | undefined;
46
+ /**
47
+ * Flushes observability exporters and releases underlying storage handles
48
+ * (such as PostgreSQL connection pools) when the Nest application shuts down.
49
+ */
50
+ onApplicationShutdown(): Promise<void>;
51
+ }