@mastra/express 1.4.11-alpha.0 → 1.4.11-alpha.2

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/dist/index.cjs CHANGED
@@ -1,669 +1,578 @@
1
- 'use strict';
2
-
3
- var busboy = require('@fastify/busboy');
4
- var auth = require('@mastra/server/auth');
5
- var serverAdapter = require('@mastra/server/server-adapter');
6
- var requestContext = require('@mastra/core/request-context');
7
-
8
- // src/index.ts
9
- function toWebRequest(req) {
10
- const protocol = req.protocol || "http";
11
- const host = req.get("host") || "localhost";
12
- const url = `${protocol}://${host}${req.originalUrl || req.url}`;
13
- const headers = new Headers();
14
- for (const [key, value] of Object.entries(req.headers)) {
15
- if (!value) continue;
16
- if (Array.isArray(value)) {
17
- value.forEach((v) => headers.append(key, v));
18
- } else {
19
- headers.set(key, value);
20
- }
21
- }
22
- return new globalThis.Request(url, {
23
- method: req.method,
24
- headers
25
- });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _fastify_busboy = require("@fastify/busboy");
3
+ let _mastra_server_auth = require("@mastra/server/auth");
4
+ let _mastra_server_server_adapter = require("@mastra/server/server-adapter");
5
+ let _mastra_core_request_context = require("@mastra/core/request-context");
6
+ //#region src/auth-middleware.ts
7
+ function toWebRequest$1(req) {
8
+ const url = `${req.protocol || "http"}://${req.get("host") || "localhost"}${req.originalUrl || req.url}`;
9
+ const headers = new Headers();
10
+ for (const [key, value] of Object.entries(req.headers)) {
11
+ if (!value) continue;
12
+ if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
13
+ else headers.set(key, value);
14
+ }
15
+ return new globalThis.Request(url, {
16
+ method: req.method,
17
+ headers
18
+ });
26
19
  }
27
- function createAuthMiddleware({
28
- mastra,
29
- requiresAuth = true
30
- }) {
31
- return async (req, res, next) => {
32
- if (!requiresAuth) {
33
- next();
34
- return;
35
- }
36
- const authConfig = mastra.getServer()?.auth;
37
- if (!authConfig) {
38
- next();
39
- return;
40
- }
41
- const requestContext$1 = res.locals.requestContext ?? new requestContext.RequestContext();
42
- res.locals.requestContext = requestContext$1;
43
- res.locals.mastra = res.locals.mastra ?? mastra;
44
- const path = String(req.path || "/");
45
- const method = String(req.method || "GET");
46
- const customRouteAuthConfig = new Map(res.locals.customRouteAuthConfig ?? []);
47
- customRouteAuthConfig.set(`${method}:${path}`, true);
48
- const authHeader = req.headers.authorization;
49
- let token = authHeader ? authHeader.replace("Bearer ", "") : null;
50
- if (!token && req.query.apiKey) {
51
- token = req.query.apiKey || null;
52
- }
53
- const result = await auth.coreAuthMiddleware({
54
- path,
55
- method,
56
- getHeader: (name) => req.headers[name.toLowerCase()],
57
- mastra,
58
- authConfig,
59
- customRouteAuthConfig,
60
- requestContext: requestContext$1,
61
- rawRequest: toWebRequest(req),
62
- token,
63
- buildAuthorizeContext: () => toWebRequest(req)
64
- });
65
- if (result.action === "next") {
66
- next();
67
- return;
68
- }
69
- res.status(result.status).json(result.body);
70
- };
20
+ function createAuthMiddleware({ mastra, requiresAuth = true }) {
21
+ return async (req, res, next) => {
22
+ if (!requiresAuth) {
23
+ next();
24
+ return;
25
+ }
26
+ const authConfig = mastra.getServer()?.auth;
27
+ if (!authConfig) {
28
+ next();
29
+ return;
30
+ }
31
+ const requestContext = res.locals.requestContext ?? new _mastra_core_request_context.RequestContext();
32
+ res.locals.requestContext = requestContext;
33
+ res.locals.mastra = res.locals.mastra ?? mastra;
34
+ const path = String(req.path || "/");
35
+ const method = String(req.method || "GET");
36
+ const customRouteAuthConfig = new Map(res.locals.customRouteAuthConfig ?? []);
37
+ customRouteAuthConfig.set(`${method}:${path}`, true);
38
+ const authHeader = req.headers.authorization;
39
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
40
+ if (!token && req.query.apiKey) token = req.query.apiKey || null;
41
+ const result = await (0, _mastra_server_auth.coreAuthMiddleware)({
42
+ path,
43
+ method,
44
+ getHeader: (name) => req.headers[name.toLowerCase()],
45
+ mastra,
46
+ authConfig,
47
+ customRouteAuthConfig,
48
+ requestContext,
49
+ rawRequest: toWebRequest$1(req),
50
+ token,
51
+ buildAuthorizeContext: () => toWebRequest$1(req)
52
+ });
53
+ if (result.action === "next") {
54
+ next();
55
+ return;
56
+ }
57
+ res.status(result.status).json(result.body);
58
+ };
71
59
  }
72
-
73
- // src/index.ts
74
- var _hasPermissionPromise;
60
+ //#endregion
61
+ //#region src/index.ts
62
+ let _hasPermissionPromise;
75
63
  function loadHasPermission() {
76
- if (!_hasPermissionPromise) {
77
- _hasPermissionPromise = import('@mastra/core/auth/ee').then((m) => m.hasPermission).catch(() => {
78
- console.error(
79
- "[@mastra/express] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest"
80
- );
81
- return void 0;
82
- });
83
- }
84
- return _hasPermissionPromise;
64
+ if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
65
+ console.error("[@mastra/express] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest");
66
+ });
67
+ return _hasPermissionPromise;
85
68
  }
86
- function toWebRequest2(req) {
87
- const protocol = req.protocol || "http";
88
- const host = req.get("host") || "localhost";
89
- const url = `${protocol}://${host}${req.originalUrl || req.url}`;
90
- const headers = new Headers();
91
- for (const [key, value] of Object.entries(req.headers)) {
92
- if (value) {
93
- if (Array.isArray(value)) {
94
- value.forEach((v) => headers.append(key, v));
95
- } else {
96
- headers.set(key, value);
97
- }
98
- }
99
- }
100
- return new globalThis.Request(url, {
101
- method: req.method,
102
- headers
103
- });
69
+ /**
70
+ * Convert Express request to Web API Request for cookie-based auth providers.
71
+ */
72
+ function toWebRequest(req) {
73
+ const url = `${req.protocol || "http"}://${req.get("host") || "localhost"}${req.originalUrl || req.url}`;
74
+ const headers = new Headers();
75
+ for (const [key, value] of Object.entries(req.headers)) if (value) if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
76
+ else headers.set(key, value);
77
+ return new globalThis.Request(url, {
78
+ method: req.method,
79
+ headers
80
+ });
104
81
  }
105
- var MastraServer = class extends serverAdapter.MastraServer {
106
- createContextMiddleware() {
107
- return async (req, res, next) => {
108
- let bodyRequestContext;
109
- let paramsRequestContext;
110
- if (req.method === "POST" || req.method === "PUT") {
111
- const contentType = req.headers["content-type"];
112
- if (contentType?.includes("application/json") && req.body) {
113
- if (req.body.requestContext) {
114
- bodyRequestContext = req.body.requestContext;
115
- }
116
- }
117
- }
118
- if (req.method === "GET") {
119
- try {
120
- const encodedRequestContext = req.query.requestContext;
121
- if (typeof encodedRequestContext === "string") {
122
- try {
123
- paramsRequestContext = JSON.parse(encodedRequestContext);
124
- } catch {
125
- try {
126
- const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
127
- paramsRequestContext = JSON.parse(json);
128
- } catch {
129
- }
130
- }
131
- }
132
- } catch {
133
- }
134
- }
135
- const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });
136
- this.applyRequestMetadataToContext({
137
- requestContext,
138
- getHeader: (name) => req.get(name)
139
- });
140
- res.locals.requestContext = requestContext;
141
- res.locals.mastra = this.mastra;
142
- res.locals.registeredTools = this.tools || {};
143
- if (this.taskStore) {
144
- res.locals.taskStore = this.taskStore;
145
- }
146
- res.locals.customRouteAuthConfig = this.customRouteAuthConfig;
147
- const controller = new AbortController();
148
- res.on("close", () => {
149
- if (!res.writableFinished) {
150
- controller.abort();
151
- }
152
- });
153
- res.locals.abortSignal = controller.signal;
154
- next();
155
- };
156
- }
157
- async stream(route, res, result) {
158
- const streamFormat = route.streamFormat || "stream";
159
- if (streamFormat === "sse") {
160
- res.setHeader("Content-Type", "text/event-stream");
161
- res.setHeader("Cache-Control", "no-cache");
162
- res.setHeader("Connection", "keep-alive");
163
- res.setHeader("X-Accel-Buffering", "no");
164
- } else {
165
- res.setHeader("Content-Type", "text/plain");
166
- }
167
- res.setHeader("Transfer-Encoding", "chunked");
168
- res.flushHeaders();
169
- if (streamFormat === "sse" && route.sseFlushOnConnect) {
170
- res.write(": connected\n\n");
171
- }
172
- const readableStream = result instanceof ReadableStream ? result : result.fullStream;
173
- const reader = readableStream.getReader();
174
- try {
175
- while (true) {
176
- const { done, value } = await reader.read();
177
- if (done) break;
178
- if (value) {
179
- if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
180
- res.write(value);
181
- continue;
182
- }
183
- const shouldRedact = this.streamOptions?.redact ?? true;
184
- const outputValue = shouldRedact ? serverAdapter.redactStreamChunk(value) : value;
185
- const serialized = serverAdapter.serializeStreamChunk(outputValue);
186
- if (!serialized.ok) {
187
- this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
188
- path: route.path,
189
- chunkType: outputValue?.type,
190
- error: serialized.error.message
191
- });
192
- continue;
193
- }
194
- if (streamFormat === "sse") {
195
- res.write(`data: ${serialized.json}
196
-
197
- `);
198
- } else {
199
- res.write(serialized.json + "");
200
- }
201
- }
202
- }
203
- } catch (error) {
204
- this.mastra.getLogger()?.error("Error in stream processing", {
205
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
206
- });
207
- } finally {
208
- res.end();
209
- }
210
- }
211
- async getParams(route, request) {
212
- const urlParams = request.params;
213
- const queryParams = serverAdapter.normalizeQueryParams(request.query);
214
- let body;
215
- let bodyParseError;
216
- if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") {
217
- const contentType = request.headers["content-type"] || "";
218
- if (contentType.includes("multipart/form-data")) {
219
- try {
220
- const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
221
- body = await this.parseMultipartFormData(request, maxFileSize);
222
- } catch (error) {
223
- this.mastra.getLogger()?.error("Failed to parse multipart form data", {
224
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
225
- });
226
- if (error instanceof Error && error.message.toLowerCase().includes("size")) {
227
- throw error;
228
- }
229
- bodyParseError = {
230
- message: error instanceof Error ? error.message : "Failed to parse multipart form data"
231
- };
232
- }
233
- } else {
234
- body = request.body;
235
- }
236
- }
237
- return { urlParams, queryParams, body, bodyParseError };
238
- }
239
- /**
240
- * Parse multipart/form-data using @fastify/busboy.
241
- * Converts file uploads to Buffers and parses JSON field values.
242
- *
243
- * @param request - The Express request object
244
- * @param maxFileSize - Optional maximum file size in bytes
245
- */
246
- parseMultipartFormData(request, maxFileSize) {
247
- return new Promise((resolve, reject) => {
248
- const result = {};
249
- const busboy$1 = new busboy.Busboy({
250
- headers: {
251
- "content-type": request.headers["content-type"]
252
- },
253
- limits: maxFileSize ? { fileSize: maxFileSize } : void 0
254
- });
255
- busboy$1.on("file", (fieldname, file) => {
256
- const chunks = [];
257
- let limitExceeded = false;
258
- file.on("data", (chunk) => {
259
- chunks.push(chunk);
260
- });
261
- file.on("limit", () => {
262
- limitExceeded = true;
263
- reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
264
- });
265
- file.on("end", () => {
266
- if (!limitExceeded) {
267
- result[fieldname] = Buffer.concat(chunks);
268
- }
269
- });
270
- });
271
- busboy$1.on("field", (fieldname, value) => {
272
- try {
273
- result[fieldname] = JSON.parse(value);
274
- } catch {
275
- result[fieldname] = value;
276
- }
277
- });
278
- busboy$1.on("finish", () => {
279
- resolve(result);
280
- });
281
- busboy$1.on("error", (error) => {
282
- reject(error);
283
- });
284
- request.pipe(busboy$1);
285
- });
286
- }
287
- async sendResponse(route, response, result, request, prefix) {
288
- const resolvedPrefix = prefix ?? this.prefix ?? "";
289
- if (result && typeof result === "object" && "__refreshHeaders" in result) {
290
- const refreshHeaders = result.__refreshHeaders;
291
- for (const [key, value] of Object.entries(refreshHeaders)) {
292
- response.setHeader(key, value);
293
- }
294
- delete result.__refreshHeaders;
295
- }
296
- if (route.responseType === "json") {
297
- response.json(result);
298
- } else if (route.responseType === "stream") {
299
- await this.stream(route, response, result);
300
- } else if (route.responseType === "datastream-response") {
301
- const fetchResponse = result;
302
- fetchResponse.headers.forEach((value, key) => response.setHeader(key, value));
303
- response.status(fetchResponse.status);
304
- if (fetchResponse.body) {
305
- const reader = fetchResponse.body.getReader();
306
- const onResError = (err) => {
307
- this.mastra.getLogger()?.error("Error writing datastream response", {
308
- error: err instanceof Error ? { message: err.message, stack: err.stack } : err
309
- });
310
- void reader.cancel("response write error");
311
- };
312
- response.once("error", onResError);
313
- try {
314
- while (true) {
315
- const { done, value } = await reader.read();
316
- if (done) break;
317
- response.write(value);
318
- }
319
- } catch (error) {
320
- this.mastra.getLogger()?.error("Error in datastream processing", {
321
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
322
- });
323
- } finally {
324
- response.off("error", onResError);
325
- response.end();
326
- }
327
- } else {
328
- response.end();
329
- }
330
- } else if (route.responseType === "mcp-http") {
331
- if (!request) {
332
- response.status(500).json({ error: "Request object required for MCP transport" });
333
- return;
334
- }
335
- const { server, httpPath, mcpOptions: routeMcpOptions } = result;
336
- try {
337
- const options = { ...this.mcpOptions, ...routeMcpOptions };
338
- await server.startHTTP({
339
- url: new URL(request.url, `http://${request.headers.host}`),
340
- httpPath: `${resolvedPrefix}${httpPath}`,
341
- req: request,
342
- res: response,
343
- options: Object.keys(options).length > 0 ? options : void 0
344
- });
345
- } catch {
346
- if (!response.headersSent) {
347
- response.status(500).json({
348
- jsonrpc: "2.0",
349
- error: { code: -32603, message: "Internal server error" },
350
- id: null
351
- });
352
- }
353
- }
354
- } else if (route.responseType === "mcp-sse") {
355
- if (!request) {
356
- response.status(500).json({ error: "Request object required for MCP transport" });
357
- return;
358
- }
359
- const { server, ssePath, messagePath } = result;
360
- try {
361
- await server.startSSE({
362
- url: new URL(request.url, `http://${request.headers.host}`),
363
- ssePath: `${resolvedPrefix}${ssePath}`,
364
- messagePath: `${resolvedPrefix}${messagePath}`,
365
- req: request,
366
- res: response
367
- });
368
- } catch {
369
- if (!response.headersSent) {
370
- response.status(500).json({ error: "Error handling MCP SSE request" });
371
- }
372
- }
373
- } else {
374
- response.sendStatus(500);
375
- }
376
- }
377
- async registerRoute(app, route, { prefix: prefixParam } = {}) {
378
- const prefix = prefixParam ?? this.prefix ?? "";
379
- const shouldApplyBodyLimit = this.bodyLimitOptions && ["POST", "PUT", "PATCH"].includes(route.method.toUpperCase());
380
- const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
381
- const middlewares = [];
382
- if (shouldApplyBodyLimit && maxSize && this.bodyLimitOptions) {
383
- const bodyLimitMiddleware = (req, res, next) => {
384
- const contentLength = req.headers["content-length"];
385
- if (contentLength && parseInt(contentLength, 10) > maxSize) {
386
- try {
387
- const errorResponse = this.bodyLimitOptions.onError({ error: "Request body too large" });
388
- return res.status(413).json(errorResponse);
389
- } catch {
390
- return res.status(413).json({ error: "Request body too large" });
391
- }
392
- }
393
- next();
394
- };
395
- middlewares.push(bodyLimitMiddleware);
396
- }
397
- app[route.method.toLowerCase()](
398
- `${prefix}${route.path}`,
399
- ...middlewares,
400
- async (req, res) => {
401
- const authError = await this.checkRouteAuth(route, {
402
- path: String(req.path || "/"),
403
- method: String(req.method || "GET"),
404
- getHeader: (name) => req.headers[name.toLowerCase()],
405
- getQuery: (name) => req.query[name],
406
- requestContext: res.locals.requestContext,
407
- request: toWebRequest2(req),
408
- buildAuthorizeContext: () => toWebRequest2(req)
409
- });
410
- if (authError) {
411
- const authResult = authError;
412
- if (authResult.headers) {
413
- for (const [key, value] of Object.entries(authResult.headers)) {
414
- res.setHeader(key, value);
415
- }
416
- }
417
- if (authResult.error) {
418
- return res.status(authResult.status).json({ error: authResult.error });
419
- }
420
- }
421
- const params = await this.getParams(route, req);
422
- if (params.bodyParseError) {
423
- return res.status(400).json({
424
- error: "Invalid request body",
425
- issues: [{ field: "body", message: params.bodyParseError.message }]
426
- });
427
- }
428
- if (params.queryParams) {
429
- try {
430
- params.queryParams = await this.parseQueryParams(route, params.queryParams);
431
- } catch (error) {
432
- this.mastra.getLogger()?.error("Error parsing query params", {
433
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
434
- });
435
- if (serverAdapter.isZodError(error)) {
436
- const { status, body } = this.resolveValidationError(route, error, "query");
437
- return res.status(status).json(body);
438
- }
439
- return res.status(400).json({
440
- error: "Invalid query parameters",
441
- issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
442
- });
443
- }
444
- }
445
- if (params.body) {
446
- try {
447
- params.body = await this.parseBody(route, params.body);
448
- } catch (error) {
449
- this.mastra.getLogger()?.error("Error parsing body", {
450
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
451
- });
452
- if (serverAdapter.isZodError(error)) {
453
- const { status, body } = this.resolveValidationError(route, error, "body");
454
- return res.status(status).json(body);
455
- }
456
- return res.status(400).json({
457
- error: "Invalid request body",
458
- issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
459
- });
460
- }
461
- }
462
- if (params.urlParams) {
463
- try {
464
- params.urlParams = await this.parsePathParams(route, params.urlParams);
465
- } catch (error) {
466
- this.mastra.getLogger()?.error("Error parsing path params", {
467
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
468
- });
469
- if (serverAdapter.isZodError(error)) {
470
- const { status, body } = this.resolveValidationError(route, error, "path");
471
- return res.status(status).json(body);
472
- }
473
- return res.status(400).json({
474
- error: "Invalid path parameters",
475
- issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
476
- });
477
- }
478
- }
479
- const handlerParams = {
480
- ...params.urlParams,
481
- ...params.queryParams,
482
- ...typeof params.body === "object" ? params.body : {},
483
- requestContext: res.locals.requestContext,
484
- mastra: this.mastra,
485
- registeredTools: res.locals.registeredTools,
486
- taskStore: res.locals.taskStore,
487
- abortSignal: res.locals.abortSignal,
488
- routePrefix: prefix,
489
- request: toWebRequest2(req)
490
- };
491
- const authConfig = this.mastra.getServer()?.auth;
492
- if (authConfig) {
493
- const hasPermission = await loadHasPermission();
494
- if (hasPermission) {
495
- const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
496
- const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
497
- if (permissionError) {
498
- return res.status(permissionError.status).json({
499
- error: permissionError.error,
500
- message: permissionError.message
501
- });
502
- }
503
- }
504
- }
505
- const fgaError = await serverAdapter.checkRouteFGA(this.mastra, route, res.locals.requestContext, {
506
- ...params.urlParams,
507
- ...params.queryParams,
508
- ...typeof params.body === "object" ? params.body : {}
509
- });
510
- if (fgaError) {
511
- return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });
512
- }
513
- try {
514
- const result = await route.handler(handlerParams);
515
- await this.sendResponse(route, res, result, req, prefix);
516
- } catch (error) {
517
- const httpStatus = error && typeof error === "object" && "status" in error ? error.status : void 0;
518
- const isClientError = typeof httpStatus === "number" && httpStatus >= 400 && httpStatus < 500;
519
- if (!isClientError) {
520
- this.mastra.getLogger()?.error("Error calling handler", {
521
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error,
522
- path: route.path,
523
- method: route.method
524
- });
525
- }
526
- let status = 500;
527
- if (error && typeof error === "object") {
528
- if ("status" in error) {
529
- status = error.status;
530
- } else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) {
531
- status = error.details.status;
532
- }
533
- }
534
- res.status(status).json({ error: error instanceof Error ? error.message : "Unknown error" });
535
- }
536
- }
537
- );
538
- }
539
- async registerCustomApiRoutes() {
540
- if (!await this.buildCustomRouteHandler()) return;
541
- this.app.use(async (req, res, next) => {
542
- const path = String(req.path || "/");
543
- const method = String(req.method || "GET");
544
- const matchedRoute = auth.findMatchingCustomRoute(
545
- path,
546
- method,
547
- this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes
548
- );
549
- const shouldRunCustomRouteAuth = auth.isProtectedCustomRoute(path, method, this.customRouteAuthConfig);
550
- const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
551
- if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
552
- const serverRoute = {
553
- method: matchedRoute?.route.method ?? method,
554
- path: matchedRoute?.route.path ?? path,
555
- responseType: "json",
556
- handler: async () => {
557
- },
558
- requiresAuth: matchedRoute?.route.requiresAuth,
559
- requiresPermission: matchedRoute?.route.requiresPermission,
560
- fga: matchedRoute?.route.fga
561
- };
562
- if (shouldRunCustomRouteAuth) {
563
- const authError = await this.checkRouteAuth(serverRoute, {
564
- path,
565
- method,
566
- getHeader: (name) => req.headers[name.toLowerCase()],
567
- getQuery: (name) => req.query[name],
568
- requestContext: res.locals.requestContext,
569
- request: toWebRequest2(req),
570
- buildAuthorizeContext: () => toWebRequest2(req)
571
- });
572
- if (authError) {
573
- const authResult = authError;
574
- if (authResult.headers) {
575
- for (const [key, value] of Object.entries(authResult.headers)) {
576
- res.setHeader(key, value);
577
- }
578
- }
579
- if (authResult.error) {
580
- return res.status(authResult.status).json({ error: authResult.error });
581
- }
582
- }
583
- const authConfig = this.mastra.getServer()?.auth;
584
- if (authConfig) {
585
- const hasPermission = await loadHasPermission();
586
- if (hasPermission) {
587
- const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
588
- const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
589
- if (permissionError) {
590
- return res.status(permissionError.status).json({
591
- error: permissionError.error,
592
- message: permissionError.message
593
- });
594
- }
595
- }
596
- }
597
- }
598
- const fgaError = await serverAdapter.checkRouteFGA(this.mastra, serverRoute, res.locals.requestContext, {
599
- ...matchedRoute?.params ?? {},
600
- ...req.query,
601
- ...typeof req.body === "object" && req.body !== null ? req.body : {}
602
- });
603
- if (fgaError) {
604
- return res.status(fgaError.status).json({ error: fgaError.error, message: fgaError.message });
605
- }
606
- }
607
- const response = await this.handleCustomRouteRequest(
608
- `${req.protocol}://${req.get("host") || "localhost"}${req.originalUrl}`,
609
- req.method,
610
- req.headers,
611
- req.body,
612
- res.locals.requestContext,
613
- res.locals.abortSignal
614
- );
615
- if (!response) return next();
616
- await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);
617
- });
618
- }
619
- registerContextMiddleware() {
620
- this.app.use(this.createContextMiddleware());
621
- }
622
- registerAuthMiddleware() {
623
- }
624
- registerHttpLoggingMiddleware() {
625
- if (!this.httpLoggingConfig?.enabled) {
626
- return;
627
- }
628
- this.app.use((req, res, next) => {
629
- if (!this.shouldLogRequest(req.path)) {
630
- return next();
631
- }
632
- const start = Date.now();
633
- const method = req.method;
634
- const path = req.path;
635
- res.on("finish", () => {
636
- const duration = Date.now() - start;
637
- const status = res.statusCode;
638
- const level = this.httpLoggingConfig?.level || "info";
639
- const logData = {
640
- method,
641
- path,
642
- status,
643
- duration: `${duration}ms`
644
- };
645
- if (this.httpLoggingConfig?.includeQueryParams) {
646
- logData.query = req.query;
647
- }
648
- if (this.httpLoggingConfig?.includeHeaders) {
649
- const headers = { ...req.headers };
650
- const redactHeaders = this.httpLoggingConfig.redactHeaders || [];
651
- redactHeaders.forEach((h) => {
652
- const key = h.toLowerCase();
653
- if (headers[key] !== void 0) {
654
- headers[key] = "[REDACTED]";
655
- }
656
- });
657
- logData.headers = headers;
658
- }
659
- this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);
660
- });
661
- next();
662
- });
663
- }
82
+ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
83
+ createContextMiddleware() {
84
+ return async (req, res, next) => {
85
+ let bodyRequestContext;
86
+ let paramsRequestContext;
87
+ if (req.method === "POST" || req.method === "PUT") {
88
+ if (req.headers["content-type"]?.includes("application/json") && req.body) {
89
+ if (req.body.requestContext) bodyRequestContext = req.body.requestContext;
90
+ }
91
+ }
92
+ if (req.method === "GET") try {
93
+ const encodedRequestContext = req.query.requestContext;
94
+ if (typeof encodedRequestContext === "string") try {
95
+ paramsRequestContext = JSON.parse(encodedRequestContext);
96
+ } catch {
97
+ try {
98
+ const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
99
+ paramsRequestContext = JSON.parse(json);
100
+ } catch {}
101
+ }
102
+ } catch {}
103
+ const requestContext = this.mergeRequestContext({
104
+ paramsRequestContext,
105
+ bodyRequestContext
106
+ });
107
+ this.applyRequestMetadataToContext({
108
+ requestContext,
109
+ getHeader: (name) => req.get(name)
110
+ });
111
+ res.locals.requestContext = requestContext;
112
+ res.locals.mastra = this.mastra;
113
+ res.locals.registeredTools = this.tools || {};
114
+ if (this.taskStore) res.locals.taskStore = this.taskStore;
115
+ res.locals.customRouteAuthConfig = this.customRouteAuthConfig;
116
+ const controller = new AbortController();
117
+ res.on("close", () => {
118
+ if (!res.writableFinished) controller.abort();
119
+ });
120
+ res.locals.abortSignal = controller.signal;
121
+ next();
122
+ };
123
+ }
124
+ async stream(route, res, result) {
125
+ const streamFormat = route.streamFormat || "stream";
126
+ if (streamFormat === "sse") {
127
+ res.setHeader("Content-Type", "text/event-stream");
128
+ res.setHeader("Cache-Control", "no-cache");
129
+ res.setHeader("Connection", "keep-alive");
130
+ res.setHeader("X-Accel-Buffering", "no");
131
+ } else res.setHeader("Content-Type", "text/plain");
132
+ res.setHeader("Transfer-Encoding", "chunked");
133
+ res.flushHeaders();
134
+ if (streamFormat === "sse" && route.sseFlushOnConnect) res.write(": connected\n\n");
135
+ const reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();
136
+ try {
137
+ while (true) {
138
+ const { done, value } = await reader.read();
139
+ if (done) break;
140
+ if (value) {
141
+ if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
142
+ res.write(value);
143
+ continue;
144
+ }
145
+ const outputValue = this.streamOptions?.redact ?? true ? (0, _mastra_server_server_adapter.redactStreamChunk)(value) : value;
146
+ const serialized = (0, _mastra_server_server_adapter.serializeStreamChunk)(outputValue);
147
+ if (!serialized.ok) {
148
+ this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
149
+ path: route.path,
150
+ chunkType: outputValue?.type,
151
+ error: serialized.error.message
152
+ });
153
+ continue;
154
+ }
155
+ if (streamFormat === "sse") res.write(`data: ${serialized.json}\n\n`);
156
+ else res.write(serialized.json + "");
157
+ }
158
+ }
159
+ } catch (error) {
160
+ this.mastra.getLogger()?.error("Error in stream processing", { error: error instanceof Error ? {
161
+ message: error.message,
162
+ stack: error.stack
163
+ } : error });
164
+ } finally {
165
+ res.end();
166
+ }
167
+ }
168
+ async getParams(route, request) {
169
+ const urlParams = request.params;
170
+ const queryParams = (0, _mastra_server_server_adapter.normalizeQueryParams)(request.query);
171
+ let body;
172
+ let bodyParseError;
173
+ if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") if ((request.headers["content-type"] || "").includes("multipart/form-data")) try {
174
+ const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
175
+ body = await this.parseMultipartFormData(request, maxFileSize);
176
+ } catch (error) {
177
+ this.mastra.getLogger()?.error("Failed to parse multipart form data", { error: error instanceof Error ? {
178
+ message: error.message,
179
+ stack: error.stack
180
+ } : error });
181
+ if (error instanceof Error && error.message.toLowerCase().includes("size")) throw error;
182
+ bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
183
+ }
184
+ else body = request.body;
185
+ return {
186
+ urlParams,
187
+ queryParams,
188
+ body,
189
+ bodyParseError
190
+ };
191
+ }
192
+ /**
193
+ * Parse multipart/form-data using @fastify/busboy.
194
+ * Converts file uploads to Buffers and parses JSON field values.
195
+ *
196
+ * @param request - The Express request object
197
+ * @param maxFileSize - Optional maximum file size in bytes
198
+ */
199
+ parseMultipartFormData(request, maxFileSize) {
200
+ return new Promise((resolve, reject) => {
201
+ const result = {};
202
+ const busboy = new _fastify_busboy.Busboy({
203
+ headers: { "content-type": request.headers["content-type"] },
204
+ limits: maxFileSize ? { fileSize: maxFileSize } : void 0
205
+ });
206
+ busboy.on("file", (fieldname, file) => {
207
+ const chunks = [];
208
+ let limitExceeded = false;
209
+ file.on("data", (chunk) => {
210
+ chunks.push(chunk);
211
+ });
212
+ file.on("limit", () => {
213
+ limitExceeded = true;
214
+ reject(/* @__PURE__ */ new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
215
+ });
216
+ file.on("end", () => {
217
+ if (!limitExceeded) result[fieldname] = Buffer.concat(chunks);
218
+ });
219
+ });
220
+ busboy.on("field", (fieldname, value) => {
221
+ try {
222
+ result[fieldname] = JSON.parse(value);
223
+ } catch {
224
+ result[fieldname] = value;
225
+ }
226
+ });
227
+ busboy.on("finish", () => {
228
+ resolve(result);
229
+ });
230
+ busboy.on("error", (error) => {
231
+ reject(error);
232
+ });
233
+ request.pipe(busboy);
234
+ });
235
+ }
236
+ async sendResponse(route, response, result, request, prefix) {
237
+ const resolvedPrefix = prefix ?? this.prefix ?? "";
238
+ if (result && typeof result === "object" && "__refreshHeaders" in result) {
239
+ const refreshHeaders = result.__refreshHeaders;
240
+ for (const [key, value] of Object.entries(refreshHeaders)) response.setHeader(key, value);
241
+ delete result.__refreshHeaders;
242
+ }
243
+ if (route.responseType === "json") response.json(result);
244
+ else if (route.responseType === "stream") await this.stream(route, response, result);
245
+ else if (route.responseType === "datastream-response") {
246
+ const fetchResponse = result;
247
+ fetchResponse.headers.forEach((value, key) => response.setHeader(key, value));
248
+ response.status(fetchResponse.status);
249
+ if (fetchResponse.body) {
250
+ const reader = fetchResponse.body.getReader();
251
+ const onResError = (err) => {
252
+ this.mastra.getLogger()?.error("Error writing datastream response", { error: err instanceof Error ? {
253
+ message: err.message,
254
+ stack: err.stack
255
+ } : err });
256
+ reader.cancel("response write error");
257
+ };
258
+ response.once("error", onResError);
259
+ try {
260
+ while (true) {
261
+ const { done, value } = await reader.read();
262
+ if (done) break;
263
+ response.write(value);
264
+ }
265
+ } catch (error) {
266
+ this.mastra.getLogger()?.error("Error in datastream processing", { error: error instanceof Error ? {
267
+ message: error.message,
268
+ stack: error.stack
269
+ } : error });
270
+ } finally {
271
+ response.off("error", onResError);
272
+ response.end();
273
+ }
274
+ } else response.end();
275
+ } else if (route.responseType === "mcp-http") {
276
+ if (!request) {
277
+ response.status(500).json({ error: "Request object required for MCP transport" });
278
+ return;
279
+ }
280
+ const { server, httpPath, mcpOptions: routeMcpOptions } = result;
281
+ try {
282
+ const options = {
283
+ ...this.mcpOptions,
284
+ ...routeMcpOptions
285
+ };
286
+ await server.startHTTP({
287
+ url: new URL(request.url, `http://${request.headers.host}`),
288
+ httpPath: `${resolvedPrefix}${httpPath}`,
289
+ req: request,
290
+ res: response,
291
+ options: Object.keys(options).length > 0 ? options : void 0
292
+ });
293
+ } catch {
294
+ if (!response.headersSent) response.status(500).json({
295
+ jsonrpc: "2.0",
296
+ error: {
297
+ code: -32603,
298
+ message: "Internal server error"
299
+ },
300
+ id: null
301
+ });
302
+ }
303
+ } else if (route.responseType === "mcp-sse") {
304
+ if (!request) {
305
+ response.status(500).json({ error: "Request object required for MCP transport" });
306
+ return;
307
+ }
308
+ const { server, ssePath, messagePath } = result;
309
+ try {
310
+ await server.startSSE({
311
+ url: new URL(request.url, `http://${request.headers.host}`),
312
+ ssePath: `${resolvedPrefix}${ssePath}`,
313
+ messagePath: `${resolvedPrefix}${messagePath}`,
314
+ req: request,
315
+ res: response
316
+ });
317
+ } catch {
318
+ if (!response.headersSent) response.status(500).json({ error: "Error handling MCP SSE request" });
319
+ }
320
+ } else response.sendStatus(500);
321
+ }
322
+ async registerRoute(app, route, { prefix: prefixParam } = {}) {
323
+ const prefix = prefixParam ?? this.prefix ?? "";
324
+ const shouldApplyBodyLimit = this.bodyLimitOptions && [
325
+ "POST",
326
+ "PUT",
327
+ "PATCH"
328
+ ].includes(route.method.toUpperCase());
329
+ const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
330
+ const middlewares = [];
331
+ if (shouldApplyBodyLimit && maxSize && this.bodyLimitOptions) {
332
+ const bodyLimitMiddleware = (req, res, next) => {
333
+ const contentLength = req.headers["content-length"];
334
+ if (contentLength && parseInt(contentLength, 10) > maxSize) try {
335
+ const errorResponse = this.bodyLimitOptions.onError({ error: "Request body too large" });
336
+ return res.status(413).json(errorResponse);
337
+ } catch {
338
+ return res.status(413).json({ error: "Request body too large" });
339
+ }
340
+ next();
341
+ };
342
+ middlewares.push(bodyLimitMiddleware);
343
+ }
344
+ app[route.method.toLowerCase()](`${prefix}${route.path}`, ...middlewares, async (req, res) => {
345
+ const authError = await this.checkRouteAuth(route, {
346
+ path: String(req.path || "/"),
347
+ method: String(req.method || "GET"),
348
+ getHeader: (name) => req.headers[name.toLowerCase()],
349
+ getQuery: (name) => req.query[name],
350
+ requestContext: res.locals.requestContext,
351
+ request: toWebRequest(req),
352
+ buildAuthorizeContext: () => toWebRequest(req)
353
+ });
354
+ if (authError) {
355
+ const authResult = authError;
356
+ if (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) res.setHeader(key, value);
357
+ if (authResult.error) return res.status(authResult.status).json({ error: authResult.error });
358
+ }
359
+ const params = await this.getParams(route, req);
360
+ if (params.bodyParseError) return res.status(400).json({
361
+ error: "Invalid request body",
362
+ issues: [{
363
+ field: "body",
364
+ message: params.bodyParseError.message
365
+ }]
366
+ });
367
+ if (params.queryParams) try {
368
+ params.queryParams = await this.parseQueryParams(route, params.queryParams);
369
+ } catch (error) {
370
+ this.mastra.getLogger()?.error("Error parsing query params", { error: error instanceof Error ? {
371
+ message: error.message,
372
+ stack: error.stack
373
+ } : error });
374
+ if ((0, _mastra_server_server_adapter.isZodError)(error)) {
375
+ const { status, body } = this.resolveValidationError(route, error, "query");
376
+ return res.status(status).json(body);
377
+ }
378
+ return res.status(400).json({
379
+ error: "Invalid query parameters",
380
+ issues: [{
381
+ field: "unknown",
382
+ message: error instanceof Error ? error.message : "Unknown error"
383
+ }]
384
+ });
385
+ }
386
+ if (params.body) try {
387
+ params.body = await this.parseBody(route, params.body);
388
+ } catch (error) {
389
+ this.mastra.getLogger()?.error("Error parsing body", { error: error instanceof Error ? {
390
+ message: error.message,
391
+ stack: error.stack
392
+ } : error });
393
+ if ((0, _mastra_server_server_adapter.isZodError)(error)) {
394
+ const { status, body } = this.resolveValidationError(route, error, "body");
395
+ return res.status(status).json(body);
396
+ }
397
+ return res.status(400).json({
398
+ error: "Invalid request body",
399
+ issues: [{
400
+ field: "unknown",
401
+ message: error instanceof Error ? error.message : "Unknown error"
402
+ }]
403
+ });
404
+ }
405
+ if (params.urlParams) try {
406
+ params.urlParams = await this.parsePathParams(route, params.urlParams);
407
+ } catch (error) {
408
+ this.mastra.getLogger()?.error("Error parsing path params", { error: error instanceof Error ? {
409
+ message: error.message,
410
+ stack: error.stack
411
+ } : error });
412
+ if ((0, _mastra_server_server_adapter.isZodError)(error)) {
413
+ const { status, body } = this.resolveValidationError(route, error, "path");
414
+ return res.status(status).json(body);
415
+ }
416
+ return res.status(400).json({
417
+ error: "Invalid path parameters",
418
+ issues: [{
419
+ field: "unknown",
420
+ message: error instanceof Error ? error.message : "Unknown error"
421
+ }]
422
+ });
423
+ }
424
+ const handlerParams = {
425
+ ...params.urlParams,
426
+ ...params.queryParams,
427
+ ...typeof params.body === "object" ? params.body : {},
428
+ requestContext: res.locals.requestContext,
429
+ mastra: this.mastra,
430
+ registeredTools: res.locals.registeredTools,
431
+ taskStore: res.locals.taskStore,
432
+ abortSignal: res.locals.abortSignal,
433
+ routePrefix: prefix,
434
+ request: toWebRequest(req)
435
+ };
436
+ if (this.mastra.getServer()?.auth) {
437
+ const hasPermission = await loadHasPermission();
438
+ if (hasPermission) {
439
+ const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
440
+ const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);
441
+ if (permissionError) return res.status(permissionError.status).json({
442
+ error: permissionError.error,
443
+ message: permissionError.message
444
+ });
445
+ }
446
+ }
447
+ const fgaError = await (0, _mastra_server_server_adapter.checkRouteFGA)(this.mastra, route, res.locals.requestContext, {
448
+ ...params.urlParams,
449
+ ...params.queryParams,
450
+ ...typeof params.body === "object" ? params.body : {}
451
+ });
452
+ if (fgaError) return res.status(fgaError.status).json({
453
+ error: fgaError.error,
454
+ message: fgaError.message
455
+ });
456
+ try {
457
+ const result = await route.handler(handlerParams);
458
+ await this.sendResponse(route, res, result, req, prefix);
459
+ } catch (error) {
460
+ const httpStatus = error && typeof error === "object" && "status" in error ? error.status : void 0;
461
+ if (!(typeof httpStatus === "number" && httpStatus >= 400 && httpStatus < 500)) this.mastra.getLogger()?.error("Error calling handler", {
462
+ error: error instanceof Error ? {
463
+ message: error.message,
464
+ stack: error.stack
465
+ } : error,
466
+ path: route.path,
467
+ method: route.method
468
+ });
469
+ let status = 500;
470
+ if (error && typeof error === "object") {
471
+ if ("status" in error) status = error.status;
472
+ else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) status = error.details.status;
473
+ }
474
+ res.status(status).json({ error: error instanceof Error ? error.message : "Unknown error" });
475
+ }
476
+ });
477
+ }
478
+ async registerCustomApiRoutes() {
479
+ if (!await this.buildCustomRouteHandler()) return;
480
+ this.app.use(async (req, res, next) => {
481
+ const path = String(req.path || "/");
482
+ const method = String(req.method || "GET");
483
+ const matchedRoute = (0, _mastra_server_auth.findMatchingCustomRoute)(path, method, this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes);
484
+ const shouldRunCustomRouteAuth = (0, _mastra_server_auth.isProtectedCustomRoute)(path, method, this.customRouteAuthConfig);
485
+ const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
486
+ if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
487
+ const serverRoute = {
488
+ method: matchedRoute?.route.method ?? method,
489
+ path: matchedRoute?.route.path ?? path,
490
+ responseType: "json",
491
+ handler: async () => {},
492
+ requiresAuth: matchedRoute?.route.requiresAuth,
493
+ requiresPermission: matchedRoute?.route.requiresPermission,
494
+ fga: matchedRoute?.route.fga
495
+ };
496
+ if (shouldRunCustomRouteAuth) {
497
+ const authError = await this.checkRouteAuth(serverRoute, {
498
+ path,
499
+ method,
500
+ getHeader: (name) => req.headers[name.toLowerCase()],
501
+ getQuery: (name) => req.query[name],
502
+ requestContext: res.locals.requestContext,
503
+ request: toWebRequest(req),
504
+ buildAuthorizeContext: () => toWebRequest(req)
505
+ });
506
+ if (authError) {
507
+ const authResult = authError;
508
+ if (authResult.headers) for (const [key, value] of Object.entries(authResult.headers)) res.setHeader(key, value);
509
+ if (authResult.error) return res.status(authResult.status).json({ error: authResult.error });
510
+ }
511
+ if (this.mastra.getServer()?.auth) {
512
+ const hasPermission = await loadHasPermission();
513
+ if (hasPermission) {
514
+ const userPermissions = res.locals.requestContext.get("mastra__userPermissions");
515
+ const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);
516
+ if (permissionError) return res.status(permissionError.status).json({
517
+ error: permissionError.error,
518
+ message: permissionError.message
519
+ });
520
+ }
521
+ }
522
+ }
523
+ const fgaError = await (0, _mastra_server_server_adapter.checkRouteFGA)(this.mastra, serverRoute, res.locals.requestContext, {
524
+ ...matchedRoute?.params ?? {},
525
+ ...req.query,
526
+ ...typeof req.body === "object" && req.body !== null ? req.body : {}
527
+ });
528
+ if (fgaError) return res.status(fgaError.status).json({
529
+ error: fgaError.error,
530
+ message: fgaError.message
531
+ });
532
+ }
533
+ const response = await this.handleCustomRouteRequest(`${req.protocol}://${req.get("host") || "localhost"}${req.originalUrl}`, req.method, req.headers, req.body, res.locals.requestContext, res.locals.abortSignal);
534
+ if (!response) return next();
535
+ await this.writeCustomRouteResponse(response, res, res.locals.abortSignal);
536
+ });
537
+ }
538
+ registerContextMiddleware() {
539
+ this.app.use(this.createContextMiddleware());
540
+ }
541
+ registerAuthMiddleware() {}
542
+ registerHttpLoggingMiddleware() {
543
+ if (!this.httpLoggingConfig?.enabled) return;
544
+ this.app.use((req, res, next) => {
545
+ if (!this.shouldLogRequest(req.path)) return next();
546
+ const start = Date.now();
547
+ const method = req.method;
548
+ const path = req.path;
549
+ res.on("finish", () => {
550
+ const duration = Date.now() - start;
551
+ const status = res.statusCode;
552
+ const level = this.httpLoggingConfig?.level || "info";
553
+ const logData = {
554
+ method,
555
+ path,
556
+ status,
557
+ duration: `${duration}ms`
558
+ };
559
+ if (this.httpLoggingConfig?.includeQueryParams) logData.query = req.query;
560
+ if (this.httpLoggingConfig?.includeHeaders) {
561
+ const headers = { ...req.headers };
562
+ (this.httpLoggingConfig.redactHeaders || []).forEach((h) => {
563
+ const key = h.toLowerCase();
564
+ if (headers[key] !== void 0) headers[key] = "[REDACTED]";
565
+ });
566
+ logData.headers = headers;
567
+ }
568
+ this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);
569
+ });
570
+ next();
571
+ });
572
+ }
664
573
  };
665
-
574
+ //#endregion
666
575
  exports.MastraServer = MastraServer;
667
576
  exports.createAuthMiddleware = createAuthMiddleware;
668
- //# sourceMappingURL=index.cjs.map
577
+
669
578
  //# sourceMappingURL=index.cjs.map