@mastra/koa 1.6.11-alpha.0 → 1.6.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.js CHANGED
@@ -1,874 +1,773 @@
1
- import { Busboy } from '@fastify/busboy';
2
- import { coreAuthMiddleware, findMatchingCustomRoute, isProtectedCustomRoute } from '@mastra/server/auth';
3
- import { MastraServer as MastraServer$1, isZodError, checkRouteFGA, redactStreamChunk, serializeStreamChunk, normalizeQueryParams } from '@mastra/server/server-adapter';
4
- import { RequestContext } from '@mastra/core/request-context';
5
-
6
- // src/index.ts
7
- function toWebRequest(ctx) {
8
- const protocol = ctx.protocol || "http";
9
- const host = ctx.host || "localhost";
10
- const url = `${protocol}://${host}${ctx.url}`;
11
- const headers = new Headers();
12
- for (const [key, value] of Object.entries(ctx.headers)) {
13
- if (!value) continue;
14
- if (Array.isArray(value)) {
15
- value.forEach((v) => headers.append(key, v));
16
- } else {
17
- headers.set(key, value);
18
- }
19
- }
20
- return new globalThis.Request(url, {
21
- method: ctx.method,
22
- headers
23
- });
1
+ import { Busboy } from "@fastify/busboy";
2
+ import { coreAuthMiddleware, findMatchingCustomRoute, isProtectedCustomRoute } from "@mastra/server/auth";
3
+ import { MastraServer as MastraServer$1, checkRouteFGA, isZodError, normalizeQueryParams, redactStreamChunk, serializeStreamChunk } from "@mastra/server/server-adapter";
4
+ import { RequestContext } from "@mastra/core/request-context";
5
+ //#region src/auth-middleware.ts
6
+ function toWebRequest$1(ctx) {
7
+ const url = `${ctx.protocol || "http"}://${ctx.host || "localhost"}${ctx.url}`;
8
+ const headers = new Headers();
9
+ for (const [key, value] of Object.entries(ctx.headers)) {
10
+ if (!value) continue;
11
+ if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
12
+ else headers.set(key, value);
13
+ }
14
+ return new globalThis.Request(url, {
15
+ method: ctx.method,
16
+ headers
17
+ });
24
18
  }
25
19
  function createAuthMiddleware({ mastra, requiresAuth = true }) {
26
- return async (ctx, next) => {
27
- if (!requiresAuth) {
28
- await next();
29
- return;
30
- }
31
- const authConfig = mastra.getServer()?.auth;
32
- if (!authConfig) {
33
- await next();
34
- return;
35
- }
36
- ctx.state.requestContext ??= new RequestContext();
37
- ctx.state.mastra ??= mastra;
38
- const path = String(ctx.path || "/");
39
- const method = String(ctx.method || "GET");
40
- const customRouteAuthConfig = new Map(ctx.state.customRouteAuthConfig ?? []);
41
- customRouteAuthConfig.set(`${method}:${path}`, true);
42
- const authHeader = ctx.headers.authorization;
43
- let token = authHeader ? authHeader.replace("Bearer ", "") : null;
44
- if (!token) {
45
- token = ctx.query.apiKey || null;
46
- }
47
- const result = await coreAuthMiddleware({
48
- path,
49
- method,
50
- getHeader: (name) => ctx.headers[name.toLowerCase()],
51
- mastra,
52
- authConfig,
53
- customRouteAuthConfig,
54
- requestContext: ctx.state.requestContext,
55
- rawRequest: toWebRequest(ctx),
56
- token,
57
- buildAuthorizeContext: () => toWebRequest(ctx)
58
- });
59
- if (result.action === "next") {
60
- await next();
61
- return;
62
- }
63
- ctx.status = result.status;
64
- ctx.body = result.body;
65
- };
20
+ return async (ctx, next) => {
21
+ if (!requiresAuth) {
22
+ await next();
23
+ return;
24
+ }
25
+ const authConfig = mastra.getServer()?.auth;
26
+ if (!authConfig) {
27
+ await next();
28
+ return;
29
+ }
30
+ ctx.state.requestContext ??= new RequestContext();
31
+ ctx.state.mastra ??= mastra;
32
+ const path = String(ctx.path || "/");
33
+ const method = String(ctx.method || "GET");
34
+ const customRouteAuthConfig = new Map(ctx.state.customRouteAuthConfig ?? []);
35
+ customRouteAuthConfig.set(`${method}:${path}`, true);
36
+ const authHeader = ctx.headers.authorization;
37
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
38
+ if (!token) token = ctx.query.apiKey || null;
39
+ const result = await coreAuthMiddleware({
40
+ path,
41
+ method,
42
+ getHeader: (name) => ctx.headers[name.toLowerCase()],
43
+ mastra,
44
+ authConfig,
45
+ customRouteAuthConfig,
46
+ requestContext: ctx.state.requestContext,
47
+ rawRequest: toWebRequest$1(ctx),
48
+ token,
49
+ buildAuthorizeContext: () => toWebRequest$1(ctx)
50
+ });
51
+ if (result.action === "next") {
52
+ await next();
53
+ return;
54
+ }
55
+ ctx.status = result.status;
56
+ ctx.body = result.body;
57
+ };
66
58
  }
67
-
68
- // src/index.ts
69
- var _hasPermissionPromise;
59
+ //#endregion
60
+ //#region src/index.ts
61
+ let _hasPermissionPromise;
70
62
  function loadHasPermission() {
71
- if (!_hasPermissionPromise) {
72
- _hasPermissionPromise = import('@mastra/core/auth/ee').then((m) => m.hasPermission).catch(() => {
73
- console.error(
74
- "[@mastra/koa] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest"
75
- );
76
- return void 0;
77
- });
78
- }
79
- return _hasPermissionPromise;
63
+ if (!_hasPermissionPromise) _hasPermissionPromise = import("@mastra/core/auth/ee").then((m) => m.hasPermission).catch(() => {
64
+ console.error("[@mastra/koa] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest");
65
+ });
66
+ return _hasPermissionPromise;
80
67
  }
81
- function toWebRequest2(ctx) {
82
- const protocol = ctx.protocol || "http";
83
- const host = ctx.host || "localhost";
84
- const url = `${protocol}://${host}${ctx.url}`;
85
- const headers = new Headers();
86
- for (const [key, value] of Object.entries(ctx.headers)) {
87
- if (value) {
88
- if (Array.isArray(value)) {
89
- value.forEach((v) => headers.append(key, v));
90
- } else {
91
- headers.set(key, value);
92
- }
93
- }
94
- }
95
- return new globalThis.Request(url, {
96
- method: ctx.method,
97
- headers
98
- });
68
+ /**
69
+ * Convert Koa context to Web API Request for cookie-based auth providers.
70
+ */
71
+ function toWebRequest(ctx) {
72
+ const url = `${ctx.protocol || "http"}://${ctx.host || "localhost"}${ctx.url}`;
73
+ const headers = new Headers();
74
+ for (const [key, value] of Object.entries(ctx.headers)) if (value) if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
75
+ else headers.set(key, value);
76
+ return new globalThis.Request(url, {
77
+ method: ctx.method,
78
+ headers
79
+ });
99
80
  }
100
81
  var MastraServer = class extends MastraServer$1 {
101
- activeRouteDispatchers = /* @__PURE__ */ new WeakMap();
102
- async init() {
103
- this.registerErrorMiddleware();
104
- await super.init();
105
- }
106
- /**
107
- * Register a global error-handling middleware at the top of the middleware chain.
108
- * This acts as a safety net for errors that propagate past route handlers
109
- * (e.g., from auth middleware, context middleware, or when route handlers re-throw).
110
- *
111
- * When `server.onError` is configured, calls it and uses the response.
112
- * Otherwise provides a default JSON error response.
113
- *
114
- * Errors are emitted on the app for logging (Koa convention) but NOT re-thrown,
115
- * so this middleware is the final error boundary. Users who need custom error handling
116
- * should use `server.onError` or register their own middleware between this and the routes.
117
- */
118
- registerErrorMiddleware() {
119
- const server = this;
120
- this.app.use(async function mastraErrorBoundary(ctx, next) {
121
- try {
122
- await next();
123
- } catch (err) {
124
- if (await server.handleOnError(err, ctx)) {
125
- return;
126
- }
127
- const error = err instanceof Error ? err : new Error(String(err));
128
- let status = 500;
129
- if (err && typeof err === "object") {
130
- if ("status" in err) {
131
- status = err.status;
132
- } else if ("details" in err && err.details && typeof err.details === "object" && "status" in err.details) {
133
- status = err.details.status;
134
- }
135
- }
136
- ctx.status = status;
137
- ctx.body = { error: error.message || "Unknown error" };
138
- ctx.app.emit("error", err, ctx);
139
- }
140
- });
141
- }
142
- /**
143
- * Try to handle an error using the `server.onError` hook.
144
- * Creates a minimal context shim compatible with the Hono-style onError signature.
145
- *
146
- * @returns true if the error was handled and the response was set on ctx
147
- */
148
- async handleOnError(err, ctx) {
149
- if (ctx._mastraOnErrorAttempted) return false;
150
- ctx._mastraOnErrorAttempted = true;
151
- const onError = this.mastra.getServer()?.onError;
152
- if (!onError) return false;
153
- const error = err instanceof Error ? err : new Error(String(err));
154
- const shimContext = {
155
- json: (data, status = 200) => new Response(JSON.stringify(data), {
156
- status,
157
- headers: { "Content-Type": "application/json" }
158
- }),
159
- req: {
160
- path: ctx.path,
161
- method: ctx.method,
162
- header: (name) => {
163
- const value = ctx.headers[name.toLowerCase()];
164
- if (Array.isArray(value)) return value.join(", ");
165
- return value;
166
- },
167
- url: ctx.url
168
- }
169
- };
170
- try {
171
- const response = await onError(error, shimContext);
172
- ctx.status = response.status;
173
- const contentType = response.headers.get("content-type") || "";
174
- if (contentType.includes("application/json")) {
175
- ctx.body = await response.json();
176
- } else {
177
- ctx.body = await response.text();
178
- }
179
- return true;
180
- } catch (onErrorErr) {
181
- this.mastra.getLogger()?.error("Error in custom onError handler", {
182
- error: onErrorErr instanceof Error ? { message: onErrorErr.message, stack: onErrorErr.stack } : onErrorErr
183
- });
184
- return false;
185
- }
186
- }
187
- createContextMiddleware() {
188
- const server = this;
189
- return async function mastraRequestContext(ctx, next) {
190
- let bodyRequestContext;
191
- let paramsRequestContext;
192
- if (ctx.method === "POST" || ctx.method === "PUT") {
193
- const contentType = ctx.headers["content-type"];
194
- if (contentType?.includes("application/json") && ctx.request.body) {
195
- const body = ctx.request.body;
196
- if (body.requestContext) {
197
- bodyRequestContext = body.requestContext;
198
- }
199
- }
200
- }
201
- if (ctx.method === "GET") {
202
- try {
203
- const query = ctx.query;
204
- const encodedRequestContext = query.requestContext;
205
- if (typeof encodedRequestContext === "string") {
206
- try {
207
- paramsRequestContext = JSON.parse(encodedRequestContext);
208
- } catch {
209
- try {
210
- const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
211
- paramsRequestContext = JSON.parse(json);
212
- } catch {
213
- }
214
- }
215
- }
216
- } catch {
217
- }
218
- }
219
- const requestContext = server.mergeRequestContext({ paramsRequestContext, bodyRequestContext });
220
- server.applyRequestMetadataToContext({
221
- requestContext,
222
- getHeader: (name) => ctx.get(name)
223
- });
224
- ctx.state.requestContext = requestContext;
225
- ctx.state.mastra = server.mastra;
226
- ctx.state.tools = server.tools || {};
227
- if (server.taskStore) {
228
- ctx.state.taskStore = server.taskStore;
229
- }
230
- ctx.state.customRouteAuthConfig = server.customRouteAuthConfig;
231
- const controller = new AbortController();
232
- ctx.req.on("close", () => {
233
- if (!ctx.res.writableEnded) {
234
- controller.abort();
235
- }
236
- });
237
- ctx.state.abortSignal = controller.signal;
238
- await next();
239
- };
240
- }
241
- getRouteDispatcherGroup(app) {
242
- const middlewareStack = app.middleware;
243
- const supportsReuse = Array.isArray(middlewareStack);
244
- if (supportsReuse) {
245
- const activeGroup = this.activeRouteDispatchers.get(app);
246
- if (activeGroup && middlewareStack.length === activeGroup.stackLengthAfterRegistration) {
247
- return activeGroup;
248
- }
249
- }
250
- const group = {
251
- routes: [],
252
- stackLengthAfterRegistration: 0
253
- };
254
- app.use(this.createRouteDispatcherMiddleware(group));
255
- if (supportsReuse) {
256
- group.stackLengthAfterRegistration = app.middleware.length;
257
- this.activeRouteDispatchers.set(app, group);
258
- }
259
- return group;
260
- }
261
- createRouteDispatcherMiddleware(group) {
262
- const server = this;
263
- return async function mastraRouteDispatcher(ctx, next) {
264
- const matchedRoute = server.findRegisteredRoute(group.routes, ctx);
265
- if (!matchedRoute) {
266
- await next();
267
- return;
268
- }
269
- await server.handleMatchedRoute(matchedRoute, ctx);
270
- };
271
- }
272
- findRegisteredRoute(routes, ctx) {
273
- const method = ctx.method.toUpperCase();
274
- for (const registeredRoute of routes) {
275
- if (registeredRoute.route.method.toUpperCase() !== "ALL" && method !== registeredRoute.route.method.toUpperCase()) {
276
- continue;
277
- }
278
- const match = registeredRoute.pathRegex.exec(ctx.path);
279
- if (!match) {
280
- continue;
281
- }
282
- ctx.params = {};
283
- registeredRoute.paramNames.forEach((name, index) => {
284
- ctx.params[name] = match[index + 1];
285
- });
286
- return registeredRoute;
287
- }
288
- return void 0;
289
- }
290
- async handleMatchedRoute(registeredRoute, ctx) {
291
- const { route, prefix } = registeredRoute;
292
- const authError = await this.checkRouteAuth(route, {
293
- path: String(ctx.path || "/"),
294
- method: String(ctx.method || "GET"),
295
- getHeader: (name) => ctx.headers[name.toLowerCase()],
296
- getQuery: (name) => ctx.query[name],
297
- requestContext: ctx.state.requestContext,
298
- request: toWebRequest2(ctx),
299
- buildAuthorizeContext: () => toWebRequest2(ctx)
300
- });
301
- if (authError) {
302
- if (authError.headers) {
303
- for (const [key, value] of Object.entries(authError.headers)) {
304
- ctx.set(key, value);
305
- }
306
- }
307
- if (authError.error) {
308
- ctx.status = authError.status;
309
- ctx.body = { error: authError.error };
310
- return;
311
- }
312
- }
313
- const params = await this.getParams(route, ctx);
314
- if (params.bodyParseError) {
315
- ctx.status = 400;
316
- ctx.body = {
317
- error: "Invalid request body",
318
- issues: [{ field: "body", message: params.bodyParseError.message }]
319
- };
320
- return;
321
- }
322
- if (params.queryParams) {
323
- try {
324
- params.queryParams = await this.parseQueryParams(route, params.queryParams);
325
- } catch (error) {
326
- this.mastra.getLogger()?.error("Error parsing query params", {
327
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
328
- });
329
- if (isZodError(error)) {
330
- const resolved = this.resolveValidationError(route, error, "query");
331
- ctx.status = resolved.status;
332
- ctx.body = resolved.body;
333
- return;
334
- }
335
- ctx.status = 400;
336
- ctx.body = {
337
- error: "Invalid query parameters",
338
- issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
339
- };
340
- return;
341
- }
342
- }
343
- if (params.body) {
344
- try {
345
- params.body = await this.parseBody(route, params.body);
346
- } catch (error) {
347
- this.mastra.getLogger()?.error("Error parsing body", {
348
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
349
- });
350
- if (isZodError(error)) {
351
- const resolved = this.resolveValidationError(route, error, "body");
352
- ctx.status = resolved.status;
353
- ctx.body = resolved.body;
354
- return;
355
- }
356
- ctx.status = 400;
357
- ctx.body = {
358
- error: "Invalid request body",
359
- issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
360
- };
361
- return;
362
- }
363
- }
364
- if (params.urlParams) {
365
- try {
366
- params.urlParams = await this.parsePathParams(route, params.urlParams);
367
- } catch (error) {
368
- this.mastra.getLogger()?.error("Error parsing path params", {
369
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
370
- });
371
- if (isZodError(error)) {
372
- const resolved = this.resolveValidationError(route, error, "path");
373
- ctx.status = resolved.status;
374
- ctx.body = resolved.body;
375
- return;
376
- }
377
- ctx.status = 400;
378
- ctx.body = {
379
- error: "Invalid path parameters",
380
- issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
381
- };
382
- return;
383
- }
384
- }
385
- const handlerParams = {
386
- ...params.urlParams,
387
- ...params.queryParams,
388
- ...typeof params.body === "object" ? params.body : {},
389
- requestContext: ctx.state.requestContext,
390
- mastra: this.mastra,
391
- tools: ctx.state.tools,
392
- taskStore: ctx.state.taskStore,
393
- abortSignal: ctx.state.abortSignal,
394
- routePrefix: prefix,
395
- request: toWebRequest2(ctx)
396
- };
397
- const requestContext = ctx.state.requestContext;
398
- const hasAuth = this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth;
399
- if (hasAuth) {
400
- const hasPermission = await loadHasPermission();
401
- if (hasPermission) {
402
- const userPermissions = requestContext.get("mastra__userPermissions");
403
- const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);
404
- if (permissionError) {
405
- ctx.status = permissionError.status;
406
- ctx.body = {
407
- error: permissionError.error,
408
- message: permissionError.message
409
- };
410
- return;
411
- }
412
- }
413
- }
414
- const fgaError = await checkRouteFGA(this.mastra, route, requestContext, {
415
- ...params.urlParams,
416
- ...params.queryParams,
417
- ...typeof params.body === "object" ? params.body : {}
418
- });
419
- if (fgaError) {
420
- ctx.status = fgaError.status;
421
- ctx.body = { error: fgaError.error, message: fgaError.message };
422
- return;
423
- }
424
- try {
425
- const result = await route.handler(handlerParams);
426
- await this.sendResponse(route, ctx, result, prefix);
427
- } catch (error) {
428
- const httpStatus = error && typeof error === "object" && "status" in error ? error.status : void 0;
429
- const isClientError = typeof httpStatus === "number" && httpStatus >= 400 && httpStatus < 500;
430
- if (!isClientError) {
431
- this.mastra.getLogger()?.error("Error calling handler", {
432
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error,
433
- path: route.path,
434
- method: route.method
435
- });
436
- }
437
- if (error && typeof error === "object") {
438
- if (!("status" in error)) {
439
- if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) {
440
- error.status = error.details.status;
441
- }
442
- }
443
- }
444
- if (await this.handleOnError(error, ctx)) {
445
- return;
446
- }
447
- throw error;
448
- }
449
- }
450
- async stream(route, ctx, result) {
451
- ctx.respond = false;
452
- const streamFormat = route.streamFormat || "stream";
453
- const sseHeaders = streamFormat === "sse" ? {
454
- "Content-Type": "text/event-stream",
455
- "Cache-Control": "no-cache",
456
- Connection: "keep-alive",
457
- "X-Accel-Buffering": "no"
458
- } : {
459
- "Content-Type": "text/plain"
460
- };
461
- ctx.res.writeHead(200, {
462
- ...sseHeaders,
463
- "Transfer-Encoding": "chunked"
464
- });
465
- if (streamFormat === "sse" && route.sseFlushOnConnect) {
466
- ctx.res.write(": connected\n\n");
467
- }
468
- const readableStream = result instanceof ReadableStream ? result : result.fullStream;
469
- const reader = readableStream.getReader();
470
- ctx.res.on("close", () => {
471
- void reader.cancel("request aborted");
472
- });
473
- try {
474
- while (true) {
475
- const { done, value } = await reader.read();
476
- if (done) break;
477
- if (value) {
478
- if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
479
- ctx.res.write(value);
480
- continue;
481
- }
482
- const shouldRedact = this.streamOptions?.redact ?? true;
483
- const outputValue = shouldRedact ? redactStreamChunk(value) : value;
484
- const serialized = serializeStreamChunk(outputValue);
485
- if (!serialized.ok) {
486
- this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
487
- path: route.path,
488
- chunkType: outputValue?.type,
489
- error: serialized.error.message
490
- });
491
- continue;
492
- }
493
- if (streamFormat === "sse") {
494
- ctx.res.write(`data: ${serialized.json}
495
-
496
- `);
497
- } else {
498
- ctx.res.write(serialized.json + "");
499
- }
500
- }
501
- }
502
- } catch (error) {
503
- this.mastra.getLogger()?.error("Error in stream processing", {
504
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
505
- });
506
- } finally {
507
- ctx.res.end();
508
- }
509
- }
510
- async getParams(route, ctx) {
511
- const urlParams = ctx.params || {};
512
- const queryParams = normalizeQueryParams(ctx.query || {});
513
- let body;
514
- let bodyParseError;
515
- if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") {
516
- const contentType = ctx.headers["content-type"] || "";
517
- if (contentType.includes("multipart/form-data")) {
518
- try {
519
- const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
520
- body = await this.parseMultipartFormData(ctx, maxFileSize);
521
- } catch (error) {
522
- this.mastra.getLogger()?.error("Failed to parse multipart form data", {
523
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
524
- });
525
- if (error instanceof Error && error.message.toLowerCase().includes("size")) {
526
- throw error;
527
- }
528
- bodyParseError = {
529
- message: error instanceof Error ? error.message : "Failed to parse multipart form data"
530
- };
531
- }
532
- } else {
533
- body = ctx.request.body;
534
- }
535
- }
536
- return { urlParams, queryParams, body, bodyParseError };
537
- }
538
- /**
539
- * Parse multipart/form-data using @fastify/busboy.
540
- * Converts file uploads to Buffers and parses JSON field values.
541
- *
542
- * @param ctx - The Koa context object
543
- * @param maxFileSize - Optional maximum file size in bytes
544
- */
545
- parseMultipartFormData(ctx, maxFileSize) {
546
- return new Promise((resolve, reject) => {
547
- const result = {};
548
- const busboy = new Busboy({
549
- headers: {
550
- "content-type": ctx.headers["content-type"]
551
- },
552
- limits: maxFileSize ? { fileSize: maxFileSize } : void 0
553
- });
554
- busboy.on("file", (fieldname, file) => {
555
- const chunks = [];
556
- let limitExceeded = false;
557
- file.on("data", (chunk) => {
558
- chunks.push(chunk);
559
- });
560
- file.on("limit", () => {
561
- limitExceeded = true;
562
- reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
563
- });
564
- file.on("end", () => {
565
- if (!limitExceeded) {
566
- result[fieldname] = Buffer.concat(chunks);
567
- }
568
- });
569
- });
570
- busboy.on("field", (fieldname, value) => {
571
- try {
572
- result[fieldname] = JSON.parse(value);
573
- } catch {
574
- result[fieldname] = value;
575
- }
576
- });
577
- busboy.on("finish", () => {
578
- resolve(result);
579
- });
580
- busboy.on("error", (error) => {
581
- reject(error);
582
- });
583
- ctx.req.pipe(busboy);
584
- });
585
- }
586
- async sendResponse(route, ctx, result, prefix) {
587
- const resolvedPrefix = prefix ?? this.prefix ?? "";
588
- if (result && typeof result === "object" && "__refreshHeaders" in result) {
589
- const refreshHeaders = result.__refreshHeaders;
590
- for (const [key, value] of Object.entries(refreshHeaders)) {
591
- ctx.set(key, value);
592
- }
593
- delete result.__refreshHeaders;
594
- }
595
- if (route.responseType === "json") {
596
- ctx.type = "application/json";
597
- ctx.body = result === null || result === void 0 ? JSON.stringify(null) : result;
598
- } else if (route.responseType === "stream") {
599
- await this.stream(route, ctx, result);
600
- } else if (route.responseType === "datastream-response") {
601
- ctx.respond = false;
602
- const fetchResponse = result;
603
- const headers = {};
604
- fetchResponse.headers.forEach((value, key) => {
605
- headers[key] = value;
606
- });
607
- ctx.res.writeHead(fetchResponse.status, headers);
608
- if (fetchResponse.body) {
609
- const reader = fetchResponse.body.getReader();
610
- const onResError = (err) => {
611
- this.mastra.getLogger()?.error("Error writing datastream response", {
612
- error: err instanceof Error ? { message: err.message, stack: err.stack } : err
613
- });
614
- void reader.cancel("response write error");
615
- };
616
- ctx.res.once("error", onResError);
617
- try {
618
- while (true) {
619
- const { done, value } = await reader.read();
620
- if (done) break;
621
- ctx.res.write(value);
622
- }
623
- } catch (error) {
624
- this.mastra.getLogger()?.error("Error in datastream processing", {
625
- error: error instanceof Error ? { message: error.message, stack: error.stack } : error
626
- });
627
- } finally {
628
- ctx.res.off("error", onResError);
629
- ctx.res.end();
630
- }
631
- } else {
632
- ctx.res.end();
633
- }
634
- } else if (route.responseType === "mcp-http") {
635
- ctx.respond = false;
636
- const { server, httpPath, mcpOptions: routeMcpOptions } = result;
637
- try {
638
- const rawReq = ctx.req;
639
- if (ctx.request.body !== void 0) {
640
- rawReq.body = ctx.request.body;
641
- }
642
- const options = { ...this.mcpOptions, ...routeMcpOptions };
643
- await server.startHTTP({
644
- url: new URL(ctx.url, `http://${ctx.headers.host}`),
645
- httpPath: `${resolvedPrefix}${httpPath}`,
646
- req: rawReq,
647
- res: ctx.res,
648
- options: Object.keys(options).length > 0 ? options : void 0
649
- });
650
- } catch {
651
- if (!ctx.res.headersSent) {
652
- ctx.res.writeHead(500, { "Content-Type": "application/json" });
653
- ctx.res.end(
654
- JSON.stringify({
655
- jsonrpc: "2.0",
656
- error: { code: -32603, message: "Internal server error" },
657
- id: null
658
- })
659
- );
660
- }
661
- }
662
- } else if (route.responseType === "mcp-sse") {
663
- ctx.respond = false;
664
- const { server, ssePath, messagePath } = result;
665
- try {
666
- const rawReq = ctx.req;
667
- if (ctx.request.body !== void 0) {
668
- rawReq.body = ctx.request.body;
669
- }
670
- await server.startSSE({
671
- url: new URL(ctx.url, `http://${ctx.headers.host}`),
672
- ssePath: `${resolvedPrefix}${ssePath}`,
673
- messagePath: `${resolvedPrefix}${messagePath}`,
674
- req: rawReq,
675
- res: ctx.res
676
- });
677
- } catch {
678
- if (!ctx.res.headersSent) {
679
- ctx.res.writeHead(500, { "Content-Type": "application/json" });
680
- ctx.res.end(JSON.stringify({ error: "Error handling MCP SSE request" }));
681
- }
682
- }
683
- } else {
684
- ctx.status = 500;
685
- }
686
- }
687
- async registerRoute(app, route, { prefix: prefixParam } = {}) {
688
- const prefix = prefixParam ?? this.prefix ?? "";
689
- const fullPath = `${prefix}${route.path}`;
690
- const koaPath = fullPath;
691
- const group = this.getRouteDispatcherGroup(app);
692
- group.routes.push({
693
- route,
694
- prefix,
695
- koaPath,
696
- pathRegex: this.pathToRegex(koaPath),
697
- paramNames: this.extractParamNames(koaPath)
698
- });
699
- }
700
- /**
701
- * Convert Express-style path to regex for matching
702
- */
703
- pathToRegex(path) {
704
- const PARAM_PLACEHOLDER = "\0PARAM\0";
705
- const pathWithPlaceholders = path.replace(/:[^/]+/g, PARAM_PLACEHOLDER);
706
- const escapedPath = pathWithPlaceholders.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
707
- const regexPath = escapedPath.replace(new RegExp(PARAM_PLACEHOLDER, "g"), "([^/]+)").replace(/\//g, "\\/");
708
- return new RegExp(`^${regexPath}$`);
709
- }
710
- /**
711
- * Extract parameter names from path
712
- */
713
- extractParamNames(path) {
714
- const matches = path.match(/:[^/]+/g) || [];
715
- return matches.map((m) => m.slice(1));
716
- }
717
- async registerCustomApiRoutes() {
718
- if (!await this.buildCustomRouteHandler()) return;
719
- const server = this;
720
- this.app.use(async function mastraCustomRouteDispatcher(ctx, next) {
721
- const path = String(ctx.path || "/");
722
- const method = String(ctx.method || "GET");
723
- const matchedRoute = findMatchingCustomRoute(
724
- path,
725
- method,
726
- server.customApiRoutes ?? server.mastra.getServer()?.apiRoutes
727
- );
728
- const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, server.customRouteAuthConfig);
729
- const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
730
- const customRouteAbortController = new AbortController();
731
- const abortCustomRoute = () => {
732
- customRouteAbortController.abort();
733
- };
734
- const abortCustomRouteIfOpen = () => {
735
- if (!ctx.res.writableEnded) {
736
- abortCustomRoute();
737
- }
738
- };
739
- ctx.res.once("close", abortCustomRouteIfOpen);
740
- ctx.res.once("error", abortCustomRouteIfOpen);
741
- try {
742
- if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
743
- const serverRoute = {
744
- method: matchedRoute?.route.method ?? method,
745
- path: matchedRoute?.route.path ?? path,
746
- responseType: "json",
747
- handler: async () => {
748
- },
749
- requiresAuth: matchedRoute?.route.requiresAuth,
750
- requiresPermission: matchedRoute?.route.requiresPermission,
751
- fga: matchedRoute?.route.fga
752
- };
753
- if (shouldRunCustomRouteAuth) {
754
- const authError = await server.checkRouteAuth(serverRoute, {
755
- path,
756
- method,
757
- getHeader: (name) => ctx.headers[name.toLowerCase()],
758
- getQuery: (name) => ctx.query[name],
759
- requestContext: ctx.state.requestContext,
760
- request: toWebRequest2(ctx),
761
- buildAuthorizeContext: () => toWebRequest2(ctx)
762
- });
763
- if (authError) {
764
- if (authError.headers) {
765
- for (const [key, value] of Object.entries(authError.headers)) {
766
- ctx.set(key, value);
767
- }
768
- }
769
- if (authError.error) {
770
- ctx.status = authError.status;
771
- ctx.body = { error: authError.error };
772
- return;
773
- }
774
- }
775
- }
776
- const requestContext = ctx.state.requestContext;
777
- const hasAuth = server.mastra.getStudio?.()?.auth || server.mastra.getServer()?.auth;
778
- if (hasAuth) {
779
- const hasPermission = await loadHasPermission();
780
- if (hasPermission) {
781
- const userPermissions = requestContext.get("mastra__userPermissions");
782
- const permissionError = server.checkRoutePermission(
783
- serverRoute,
784
- userPermissions,
785
- hasPermission,
786
- requestContext
787
- );
788
- if (permissionError) {
789
- ctx.status = permissionError.status;
790
- ctx.body = {
791
- error: permissionError.error,
792
- message: permissionError.message
793
- };
794
- return;
795
- }
796
- }
797
- }
798
- const fgaError = await checkRouteFGA(server.mastra, serverRoute, ctx.state.requestContext, {
799
- ...matchedRoute?.params ?? {},
800
- ...ctx.query,
801
- ...typeof ctx.request.body === "object" && ctx.request.body !== null ? ctx.request.body : {}
802
- });
803
- if (fgaError) {
804
- ctx.status = fgaError.status;
805
- ctx.body = { error: fgaError.error, message: fgaError.message };
806
- return;
807
- }
808
- }
809
- const response = await server.handleCustomRouteRequest(
810
- `${ctx.protocol}://${ctx.host}${ctx.originalUrl || ctx.url}`,
811
- ctx.method,
812
- ctx.headers,
813
- ctx.request.body,
814
- ctx.state.requestContext,
815
- customRouteAbortController.signal
816
- );
817
- if (!response) return next();
818
- ctx.respond = false;
819
- await server.writeCustomRouteResponse(response, ctx.res, customRouteAbortController.signal);
820
- } finally {
821
- ctx.res.off("close", abortCustomRouteIfOpen);
822
- ctx.res.off("error", abortCustomRouteIfOpen);
823
- }
824
- });
825
- }
826
- registerContextMiddleware() {
827
- this.app.use(this.createContextMiddleware());
828
- }
829
- registerAuthMiddleware() {
830
- }
831
- registerHttpLoggingMiddleware() {
832
- if (!this.httpLoggingConfig?.enabled) {
833
- return;
834
- }
835
- const server = this;
836
- this.app.use(async function mastraHttpLogger(ctx, next) {
837
- if (!server.shouldLogRequest(ctx.path)) {
838
- return next();
839
- }
840
- const start = Date.now();
841
- const method = ctx.method;
842
- const path = ctx.path;
843
- await next();
844
- const duration = Date.now() - start;
845
- const status = ctx.status;
846
- const level = server.httpLoggingConfig?.level || "info";
847
- const logData = {
848
- method,
849
- path,
850
- status,
851
- duration: `${duration}ms`
852
- };
853
- if (server.httpLoggingConfig?.includeQueryParams) {
854
- logData.query = ctx.query;
855
- }
856
- if (server.httpLoggingConfig?.includeHeaders) {
857
- const headers = { ...ctx.headers };
858
- const redactHeaders = server.httpLoggingConfig.redactHeaders || [];
859
- redactHeaders.forEach((h) => {
860
- const key = h.toLowerCase();
861
- if (headers[key] !== void 0) {
862
- headers[key] = "[REDACTED]";
863
- }
864
- });
865
- logData.headers = headers;
866
- }
867
- server.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);
868
- });
869
- }
82
+ activeRouteDispatchers = /* @__PURE__ */ new WeakMap();
83
+ async init() {
84
+ this.registerErrorMiddleware();
85
+ await super.init();
86
+ }
87
+ /**
88
+ * Register a global error-handling middleware at the top of the middleware chain.
89
+ * This acts as a safety net for errors that propagate past route handlers
90
+ * (e.g., from auth middleware, context middleware, or when route handlers re-throw).
91
+ *
92
+ * When `server.onError` is configured, calls it and uses the response.
93
+ * Otherwise provides a default JSON error response.
94
+ *
95
+ * Errors are emitted on the app for logging (Koa convention) but NOT re-thrown,
96
+ * so this middleware is the final error boundary. Users who need custom error handling
97
+ * should use `server.onError` or register their own middleware between this and the routes.
98
+ */
99
+ registerErrorMiddleware() {
100
+ const server = this;
101
+ this.app.use(async function mastraErrorBoundary(ctx, next) {
102
+ try {
103
+ await next();
104
+ } catch (err) {
105
+ if (await server.handleOnError(err, ctx)) return;
106
+ const error = err instanceof Error ? err : new Error(String(err));
107
+ let status = 500;
108
+ if (err && typeof err === "object") {
109
+ if ("status" in err) status = err.status;
110
+ else if ("details" in err && err.details && typeof err.details === "object" && "status" in err.details) status = err.details.status;
111
+ }
112
+ ctx.status = status;
113
+ ctx.body = { error: error.message || "Unknown error" };
114
+ ctx.app.emit("error", err, ctx);
115
+ }
116
+ });
117
+ }
118
+ /**
119
+ * Try to handle an error using the `server.onError` hook.
120
+ * Creates a minimal context shim compatible with the Hono-style onError signature.
121
+ *
122
+ * @returns true if the error was handled and the response was set on ctx
123
+ */
124
+ async handleOnError(err, ctx) {
125
+ if (ctx._mastraOnErrorAttempted) return false;
126
+ ctx._mastraOnErrorAttempted = true;
127
+ const onError = this.mastra.getServer()?.onError;
128
+ if (!onError) return false;
129
+ const error = err instanceof Error ? err : new Error(String(err));
130
+ const shimContext = {
131
+ json: (data, status = 200) => new Response(JSON.stringify(data), {
132
+ status,
133
+ headers: { "Content-Type": "application/json" }
134
+ }),
135
+ req: {
136
+ path: ctx.path,
137
+ method: ctx.method,
138
+ header: (name) => {
139
+ const value = ctx.headers[name.toLowerCase()];
140
+ if (Array.isArray(value)) return value.join(", ");
141
+ return value;
142
+ },
143
+ url: ctx.url
144
+ }
145
+ };
146
+ try {
147
+ const response = await onError(error, shimContext);
148
+ ctx.status = response.status;
149
+ if ((response.headers.get("content-type") || "").includes("application/json")) ctx.body = await response.json();
150
+ else ctx.body = await response.text();
151
+ return true;
152
+ } catch (onErrorErr) {
153
+ this.mastra.getLogger()?.error("Error in custom onError handler", { error: onErrorErr instanceof Error ? {
154
+ message: onErrorErr.message,
155
+ stack: onErrorErr.stack
156
+ } : onErrorErr });
157
+ return false;
158
+ }
159
+ }
160
+ createContextMiddleware() {
161
+ const server = this;
162
+ return async function mastraRequestContext(ctx, next) {
163
+ let bodyRequestContext;
164
+ let paramsRequestContext;
165
+ if (ctx.method === "POST" || ctx.method === "PUT") {
166
+ if (ctx.headers["content-type"]?.includes("application/json") && ctx.request.body) {
167
+ const body = ctx.request.body;
168
+ if (body.requestContext) bodyRequestContext = body.requestContext;
169
+ }
170
+ }
171
+ if (ctx.method === "GET") try {
172
+ const encodedRequestContext = ctx.query.requestContext;
173
+ if (typeof encodedRequestContext === "string") try {
174
+ paramsRequestContext = JSON.parse(encodedRequestContext);
175
+ } catch {
176
+ try {
177
+ const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
178
+ paramsRequestContext = JSON.parse(json);
179
+ } catch {}
180
+ }
181
+ } catch {}
182
+ const requestContext = server.mergeRequestContext({
183
+ paramsRequestContext,
184
+ bodyRequestContext
185
+ });
186
+ server.applyRequestMetadataToContext({
187
+ requestContext,
188
+ getHeader: (name) => ctx.get(name)
189
+ });
190
+ ctx.state.requestContext = requestContext;
191
+ ctx.state.mastra = server.mastra;
192
+ ctx.state.tools = server.tools || {};
193
+ if (server.taskStore) ctx.state.taskStore = server.taskStore;
194
+ ctx.state.customRouteAuthConfig = server.customRouteAuthConfig;
195
+ const controller = new AbortController();
196
+ ctx.req.on("close", () => {
197
+ if (!ctx.res.writableEnded) controller.abort();
198
+ });
199
+ ctx.state.abortSignal = controller.signal;
200
+ await next();
201
+ };
202
+ }
203
+ getRouteDispatcherGroup(app) {
204
+ const middlewareStack = app.middleware;
205
+ const supportsReuse = Array.isArray(middlewareStack);
206
+ if (supportsReuse) {
207
+ const activeGroup = this.activeRouteDispatchers.get(app);
208
+ if (activeGroup && middlewareStack.length === activeGroup.stackLengthAfterRegistration) return activeGroup;
209
+ }
210
+ const group = {
211
+ routes: [],
212
+ stackLengthAfterRegistration: 0
213
+ };
214
+ app.use(this.createRouteDispatcherMiddleware(group));
215
+ if (supportsReuse) {
216
+ group.stackLengthAfterRegistration = app.middleware.length;
217
+ this.activeRouteDispatchers.set(app, group);
218
+ }
219
+ return group;
220
+ }
221
+ createRouteDispatcherMiddleware(group) {
222
+ const server = this;
223
+ return async function mastraRouteDispatcher(ctx, next) {
224
+ const matchedRoute = server.findRegisteredRoute(group.routes, ctx);
225
+ if (!matchedRoute) {
226
+ await next();
227
+ return;
228
+ }
229
+ await server.handleMatchedRoute(matchedRoute, ctx);
230
+ };
231
+ }
232
+ findRegisteredRoute(routes, ctx) {
233
+ const method = ctx.method.toUpperCase();
234
+ for (const registeredRoute of routes) {
235
+ if (registeredRoute.route.method.toUpperCase() !== "ALL" && method !== registeredRoute.route.method.toUpperCase()) continue;
236
+ const match = registeredRoute.pathRegex.exec(ctx.path);
237
+ if (!match) continue;
238
+ ctx.params = {};
239
+ registeredRoute.paramNames.forEach((name, index) => {
240
+ ctx.params[name] = match[index + 1];
241
+ });
242
+ return registeredRoute;
243
+ }
244
+ }
245
+ async handleMatchedRoute(registeredRoute, ctx) {
246
+ const { route, prefix } = registeredRoute;
247
+ const authError = await this.checkRouteAuth(route, {
248
+ path: String(ctx.path || "/"),
249
+ method: String(ctx.method || "GET"),
250
+ getHeader: (name) => ctx.headers[name.toLowerCase()],
251
+ getQuery: (name) => ctx.query[name],
252
+ requestContext: ctx.state.requestContext,
253
+ request: toWebRequest(ctx),
254
+ buildAuthorizeContext: () => toWebRequest(ctx)
255
+ });
256
+ if (authError) {
257
+ if (authError.headers) for (const [key, value] of Object.entries(authError.headers)) ctx.set(key, value);
258
+ if (authError.error) {
259
+ ctx.status = authError.status;
260
+ ctx.body = { error: authError.error };
261
+ return;
262
+ }
263
+ }
264
+ const params = await this.getParams(route, ctx);
265
+ if (params.bodyParseError) {
266
+ ctx.status = 400;
267
+ ctx.body = {
268
+ error: "Invalid request body",
269
+ issues: [{
270
+ field: "body",
271
+ message: params.bodyParseError.message
272
+ }]
273
+ };
274
+ return;
275
+ }
276
+ if (params.queryParams) try {
277
+ params.queryParams = await this.parseQueryParams(route, params.queryParams);
278
+ } catch (error) {
279
+ this.mastra.getLogger()?.error("Error parsing query params", { error: error instanceof Error ? {
280
+ message: error.message,
281
+ stack: error.stack
282
+ } : error });
283
+ if (isZodError(error)) {
284
+ const resolved = this.resolveValidationError(route, error, "query");
285
+ ctx.status = resolved.status;
286
+ ctx.body = resolved.body;
287
+ return;
288
+ }
289
+ ctx.status = 400;
290
+ ctx.body = {
291
+ error: "Invalid query parameters",
292
+ issues: [{
293
+ field: "unknown",
294
+ message: error instanceof Error ? error.message : "Unknown error"
295
+ }]
296
+ };
297
+ return;
298
+ }
299
+ if (params.body) try {
300
+ params.body = await this.parseBody(route, params.body);
301
+ } catch (error) {
302
+ this.mastra.getLogger()?.error("Error parsing body", { error: error instanceof Error ? {
303
+ message: error.message,
304
+ stack: error.stack
305
+ } : error });
306
+ if (isZodError(error)) {
307
+ const resolved = this.resolveValidationError(route, error, "body");
308
+ ctx.status = resolved.status;
309
+ ctx.body = resolved.body;
310
+ return;
311
+ }
312
+ ctx.status = 400;
313
+ ctx.body = {
314
+ error: "Invalid request body",
315
+ issues: [{
316
+ field: "unknown",
317
+ message: error instanceof Error ? error.message : "Unknown error"
318
+ }]
319
+ };
320
+ return;
321
+ }
322
+ if (params.urlParams) try {
323
+ params.urlParams = await this.parsePathParams(route, params.urlParams);
324
+ } catch (error) {
325
+ this.mastra.getLogger()?.error("Error parsing path params", { error: error instanceof Error ? {
326
+ message: error.message,
327
+ stack: error.stack
328
+ } : error });
329
+ if (isZodError(error)) {
330
+ const resolved = this.resolveValidationError(route, error, "path");
331
+ ctx.status = resolved.status;
332
+ ctx.body = resolved.body;
333
+ return;
334
+ }
335
+ ctx.status = 400;
336
+ ctx.body = {
337
+ error: "Invalid path parameters",
338
+ issues: [{
339
+ field: "unknown",
340
+ message: error instanceof Error ? error.message : "Unknown error"
341
+ }]
342
+ };
343
+ return;
344
+ }
345
+ const handlerParams = {
346
+ ...params.urlParams,
347
+ ...params.queryParams,
348
+ ...typeof params.body === "object" ? params.body : {},
349
+ requestContext: ctx.state.requestContext,
350
+ mastra: this.mastra,
351
+ tools: ctx.state.tools,
352
+ taskStore: ctx.state.taskStore,
353
+ abortSignal: ctx.state.abortSignal,
354
+ routePrefix: prefix,
355
+ request: toWebRequest(ctx)
356
+ };
357
+ const requestContext = ctx.state.requestContext;
358
+ if (this.mastra.getStudio?.()?.auth || this.mastra.getServer()?.auth) {
359
+ const hasPermission = await loadHasPermission();
360
+ if (hasPermission) {
361
+ const userPermissions = requestContext.get("mastra__userPermissions");
362
+ const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);
363
+ if (permissionError) {
364
+ ctx.status = permissionError.status;
365
+ ctx.body = {
366
+ error: permissionError.error,
367
+ message: permissionError.message
368
+ };
369
+ return;
370
+ }
371
+ }
372
+ }
373
+ const fgaError = await checkRouteFGA(this.mastra, route, requestContext, {
374
+ ...params.urlParams,
375
+ ...params.queryParams,
376
+ ...typeof params.body === "object" ? params.body : {}
377
+ });
378
+ if (fgaError) {
379
+ ctx.status = fgaError.status;
380
+ ctx.body = {
381
+ error: fgaError.error,
382
+ message: fgaError.message
383
+ };
384
+ return;
385
+ }
386
+ try {
387
+ const result = await route.handler(handlerParams);
388
+ await this.sendResponse(route, ctx, result, prefix);
389
+ } catch (error) {
390
+ const httpStatus = error && typeof error === "object" && "status" in error ? error.status : void 0;
391
+ if (!(typeof httpStatus === "number" && httpStatus >= 400 && httpStatus < 500)) this.mastra.getLogger()?.error("Error calling handler", {
392
+ error: error instanceof Error ? {
393
+ message: error.message,
394
+ stack: error.stack
395
+ } : error,
396
+ path: route.path,
397
+ method: route.method
398
+ });
399
+ if (error && typeof error === "object") {
400
+ if (!("status" in error)) {
401
+ if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) error.status = error.details.status;
402
+ }
403
+ }
404
+ if (await this.handleOnError(error, ctx)) return;
405
+ throw error;
406
+ }
407
+ }
408
+ async stream(route, ctx, result) {
409
+ ctx.respond = false;
410
+ const streamFormat = route.streamFormat || "stream";
411
+ const sseHeaders = streamFormat === "sse" ? {
412
+ "Content-Type": "text/event-stream",
413
+ "Cache-Control": "no-cache",
414
+ Connection: "keep-alive",
415
+ "X-Accel-Buffering": "no"
416
+ } : { "Content-Type": "text/plain" };
417
+ ctx.res.writeHead(200, {
418
+ ...sseHeaders,
419
+ "Transfer-Encoding": "chunked"
420
+ });
421
+ if (streamFormat === "sse" && route.sseFlushOnConnect) ctx.res.write(": connected\n\n");
422
+ const reader = (result instanceof ReadableStream ? result : result.fullStream).getReader();
423
+ ctx.res.on("close", () => {
424
+ reader.cancel("request aborted");
425
+ });
426
+ try {
427
+ while (true) {
428
+ const { done, value } = await reader.read();
429
+ if (done) break;
430
+ if (value) {
431
+ if (streamFormat === "sse" && typeof value === "string" && value.startsWith(":")) {
432
+ ctx.res.write(value);
433
+ continue;
434
+ }
435
+ const outputValue = this.streamOptions?.redact ?? true ? redactStreamChunk(value) : value;
436
+ const serialized = serializeStreamChunk(outputValue);
437
+ if (!serialized.ok) {
438
+ this.mastra.getLogger()?.error("Failed to serialize stream chunk, skipping", {
439
+ path: route.path,
440
+ chunkType: outputValue?.type,
441
+ error: serialized.error.message
442
+ });
443
+ continue;
444
+ }
445
+ if (streamFormat === "sse") ctx.res.write(`data: ${serialized.json}\n\n`);
446
+ else ctx.res.write(serialized.json + "");
447
+ }
448
+ }
449
+ } catch (error) {
450
+ this.mastra.getLogger()?.error("Error in stream processing", { error: error instanceof Error ? {
451
+ message: error.message,
452
+ stack: error.stack
453
+ } : error });
454
+ } finally {
455
+ ctx.res.end();
456
+ }
457
+ }
458
+ async getParams(route, ctx) {
459
+ const urlParams = ctx.params || {};
460
+ const queryParams = normalizeQueryParams(ctx.query || {});
461
+ let body;
462
+ let bodyParseError;
463
+ if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH" || route.method === "DELETE") if ((ctx.headers["content-type"] || "").includes("multipart/form-data")) try {
464
+ const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
465
+ body = await this.parseMultipartFormData(ctx, maxFileSize);
466
+ } catch (error) {
467
+ this.mastra.getLogger()?.error("Failed to parse multipart form data", { error: error instanceof Error ? {
468
+ message: error.message,
469
+ stack: error.stack
470
+ } : error });
471
+ if (error instanceof Error && error.message.toLowerCase().includes("size")) throw error;
472
+ bodyParseError = { message: error instanceof Error ? error.message : "Failed to parse multipart form data" };
473
+ }
474
+ else body = ctx.request.body;
475
+ return {
476
+ urlParams,
477
+ queryParams,
478
+ body,
479
+ bodyParseError
480
+ };
481
+ }
482
+ /**
483
+ * Parse multipart/form-data using @fastify/busboy.
484
+ * Converts file uploads to Buffers and parses JSON field values.
485
+ *
486
+ * @param ctx - The Koa context object
487
+ * @param maxFileSize - Optional maximum file size in bytes
488
+ */
489
+ parseMultipartFormData(ctx, maxFileSize) {
490
+ return new Promise((resolve, reject) => {
491
+ const result = {};
492
+ const busboy = new Busboy({
493
+ headers: { "content-type": ctx.headers["content-type"] },
494
+ limits: maxFileSize ? { fileSize: maxFileSize } : void 0
495
+ });
496
+ busboy.on("file", (fieldname, file) => {
497
+ const chunks = [];
498
+ let limitExceeded = false;
499
+ file.on("data", (chunk) => {
500
+ chunks.push(chunk);
501
+ });
502
+ file.on("limit", () => {
503
+ limitExceeded = true;
504
+ reject(/* @__PURE__ */ new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
505
+ });
506
+ file.on("end", () => {
507
+ if (!limitExceeded) result[fieldname] = Buffer.concat(chunks);
508
+ });
509
+ });
510
+ busboy.on("field", (fieldname, value) => {
511
+ try {
512
+ result[fieldname] = JSON.parse(value);
513
+ } catch {
514
+ result[fieldname] = value;
515
+ }
516
+ });
517
+ busboy.on("finish", () => {
518
+ resolve(result);
519
+ });
520
+ busboy.on("error", (error) => {
521
+ reject(error);
522
+ });
523
+ ctx.req.pipe(busboy);
524
+ });
525
+ }
526
+ async sendResponse(route, ctx, result, prefix) {
527
+ const resolvedPrefix = prefix ?? this.prefix ?? "";
528
+ if (result && typeof result === "object" && "__refreshHeaders" in result) {
529
+ const refreshHeaders = result.__refreshHeaders;
530
+ for (const [key, value] of Object.entries(refreshHeaders)) ctx.set(key, value);
531
+ delete result.__refreshHeaders;
532
+ }
533
+ if (route.responseType === "json") {
534
+ ctx.type = "application/json";
535
+ ctx.body = result === null || result === void 0 ? JSON.stringify(null) : result;
536
+ } else if (route.responseType === "stream") await this.stream(route, ctx, result);
537
+ else if (route.responseType === "datastream-response") {
538
+ ctx.respond = false;
539
+ const fetchResponse = result;
540
+ const headers = {};
541
+ fetchResponse.headers.forEach((value, key) => {
542
+ headers[key] = value;
543
+ });
544
+ ctx.res.writeHead(fetchResponse.status, headers);
545
+ if (fetchResponse.body) {
546
+ const reader = fetchResponse.body.getReader();
547
+ const onResError = (err) => {
548
+ this.mastra.getLogger()?.error("Error writing datastream response", { error: err instanceof Error ? {
549
+ message: err.message,
550
+ stack: err.stack
551
+ } : err });
552
+ reader.cancel("response write error");
553
+ };
554
+ ctx.res.once("error", onResError);
555
+ try {
556
+ while (true) {
557
+ const { done, value } = await reader.read();
558
+ if (done) break;
559
+ ctx.res.write(value);
560
+ }
561
+ } catch (error) {
562
+ this.mastra.getLogger()?.error("Error in datastream processing", { error: error instanceof Error ? {
563
+ message: error.message,
564
+ stack: error.stack
565
+ } : error });
566
+ } finally {
567
+ ctx.res.off("error", onResError);
568
+ ctx.res.end();
569
+ }
570
+ } else ctx.res.end();
571
+ } else if (route.responseType === "mcp-http") {
572
+ ctx.respond = false;
573
+ const { server, httpPath, mcpOptions: routeMcpOptions } = result;
574
+ try {
575
+ const rawReq = ctx.req;
576
+ if (ctx.request.body !== void 0) rawReq.body = ctx.request.body;
577
+ const options = {
578
+ ...this.mcpOptions,
579
+ ...routeMcpOptions
580
+ };
581
+ await server.startHTTP({
582
+ url: new URL(ctx.url, `http://${ctx.headers.host}`),
583
+ httpPath: `${resolvedPrefix}${httpPath}`,
584
+ req: rawReq,
585
+ res: ctx.res,
586
+ options: Object.keys(options).length > 0 ? options : void 0
587
+ });
588
+ } catch {
589
+ if (!ctx.res.headersSent) {
590
+ ctx.res.writeHead(500, { "Content-Type": "application/json" });
591
+ ctx.res.end(JSON.stringify({
592
+ jsonrpc: "2.0",
593
+ error: {
594
+ code: -32603,
595
+ message: "Internal server error"
596
+ },
597
+ id: null
598
+ }));
599
+ }
600
+ }
601
+ } else if (route.responseType === "mcp-sse") {
602
+ ctx.respond = false;
603
+ const { server, ssePath, messagePath } = result;
604
+ try {
605
+ const rawReq = ctx.req;
606
+ if (ctx.request.body !== void 0) rawReq.body = ctx.request.body;
607
+ await server.startSSE({
608
+ url: new URL(ctx.url, `http://${ctx.headers.host}`),
609
+ ssePath: `${resolvedPrefix}${ssePath}`,
610
+ messagePath: `${resolvedPrefix}${messagePath}`,
611
+ req: rawReq,
612
+ res: ctx.res
613
+ });
614
+ } catch {
615
+ if (!ctx.res.headersSent) {
616
+ ctx.res.writeHead(500, { "Content-Type": "application/json" });
617
+ ctx.res.end(JSON.stringify({ error: "Error handling MCP SSE request" }));
618
+ }
619
+ }
620
+ } else ctx.status = 500;
621
+ }
622
+ async registerRoute(app, route, { prefix: prefixParam } = {}) {
623
+ const prefix = prefixParam ?? this.prefix ?? "";
624
+ const koaPath = `${prefix}${route.path}`;
625
+ this.getRouteDispatcherGroup(app).routes.push({
626
+ route,
627
+ prefix,
628
+ koaPath,
629
+ pathRegex: this.pathToRegex(koaPath),
630
+ paramNames: this.extractParamNames(koaPath)
631
+ });
632
+ }
633
+ /**
634
+ * Convert Express-style path to regex for matching
635
+ */
636
+ pathToRegex(path) {
637
+ const PARAM_PLACEHOLDER = "\0PARAM\0";
638
+ const regexPath = path.replace(/:[^/]+/g, PARAM_PLACEHOLDER).replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(new RegExp(PARAM_PLACEHOLDER, "g"), "([^/]+)").replace(/\//g, "\\/");
639
+ return new RegExp(`^${regexPath}$`);
640
+ }
641
+ /**
642
+ * Extract parameter names from path
643
+ */
644
+ extractParamNames(path) {
645
+ return (path.match(/:[^/]+/g) || []).map((m) => m.slice(1));
646
+ }
647
+ async registerCustomApiRoutes() {
648
+ if (!await this.buildCustomRouteHandler()) return;
649
+ const server = this;
650
+ this.app.use(async function mastraCustomRouteDispatcher(ctx, next) {
651
+ const path = String(ctx.path || "/");
652
+ const method = String(ctx.method || "GET");
653
+ const matchedRoute = findMatchingCustomRoute(path, method, server.customApiRoutes ?? server.mastra.getServer()?.apiRoutes);
654
+ const shouldRunCustomRouteAuth = isProtectedCustomRoute(path, method, server.customRouteAuthConfig);
655
+ const shouldRunCustomRouteFGA = !!matchedRoute?.route.fga;
656
+ const customRouteAbortController = new AbortController();
657
+ const abortCustomRoute = () => {
658
+ customRouteAbortController.abort();
659
+ };
660
+ const abortCustomRouteIfOpen = () => {
661
+ if (!ctx.res.writableEnded) abortCustomRoute();
662
+ };
663
+ ctx.res.once("close", abortCustomRouteIfOpen);
664
+ ctx.res.once("error", abortCustomRouteIfOpen);
665
+ try {
666
+ if (shouldRunCustomRouteAuth || shouldRunCustomRouteFGA) {
667
+ const serverRoute = {
668
+ method: matchedRoute?.route.method ?? method,
669
+ path: matchedRoute?.route.path ?? path,
670
+ responseType: "json",
671
+ handler: async () => {},
672
+ requiresAuth: matchedRoute?.route.requiresAuth,
673
+ requiresPermission: matchedRoute?.route.requiresPermission,
674
+ fga: matchedRoute?.route.fga
675
+ };
676
+ if (shouldRunCustomRouteAuth) {
677
+ const authError = await server.checkRouteAuth(serverRoute, {
678
+ path,
679
+ method,
680
+ getHeader: (name) => ctx.headers[name.toLowerCase()],
681
+ getQuery: (name) => ctx.query[name],
682
+ requestContext: ctx.state.requestContext,
683
+ request: toWebRequest(ctx),
684
+ buildAuthorizeContext: () => toWebRequest(ctx)
685
+ });
686
+ if (authError) {
687
+ if (authError.headers) for (const [key, value] of Object.entries(authError.headers)) ctx.set(key, value);
688
+ if (authError.error) {
689
+ ctx.status = authError.status;
690
+ ctx.body = { error: authError.error };
691
+ return;
692
+ }
693
+ }
694
+ }
695
+ const requestContext = ctx.state.requestContext;
696
+ if (server.mastra.getStudio?.()?.auth || server.mastra.getServer()?.auth) {
697
+ const hasPermission = await loadHasPermission();
698
+ if (hasPermission) {
699
+ const userPermissions = requestContext.get("mastra__userPermissions");
700
+ const permissionError = server.checkRoutePermission(serverRoute, userPermissions, hasPermission, requestContext);
701
+ if (permissionError) {
702
+ ctx.status = permissionError.status;
703
+ ctx.body = {
704
+ error: permissionError.error,
705
+ message: permissionError.message
706
+ };
707
+ return;
708
+ }
709
+ }
710
+ }
711
+ const fgaError = await checkRouteFGA(server.mastra, serverRoute, ctx.state.requestContext, {
712
+ ...matchedRoute?.params ?? {},
713
+ ...ctx.query,
714
+ ...typeof ctx.request.body === "object" && ctx.request.body !== null ? ctx.request.body : {}
715
+ });
716
+ if (fgaError) {
717
+ ctx.status = fgaError.status;
718
+ ctx.body = {
719
+ error: fgaError.error,
720
+ message: fgaError.message
721
+ };
722
+ return;
723
+ }
724
+ }
725
+ const response = await server.handleCustomRouteRequest(`${ctx.protocol}://${ctx.host}${ctx.originalUrl || ctx.url}`, ctx.method, ctx.headers, ctx.request.body, ctx.state.requestContext, customRouteAbortController.signal);
726
+ if (!response) return next();
727
+ ctx.respond = false;
728
+ await server.writeCustomRouteResponse(response, ctx.res, customRouteAbortController.signal);
729
+ } finally {
730
+ ctx.res.off("close", abortCustomRouteIfOpen);
731
+ ctx.res.off("error", abortCustomRouteIfOpen);
732
+ }
733
+ });
734
+ }
735
+ registerContextMiddleware() {
736
+ this.app.use(this.createContextMiddleware());
737
+ }
738
+ registerAuthMiddleware() {}
739
+ registerHttpLoggingMiddleware() {
740
+ if (!this.httpLoggingConfig?.enabled) return;
741
+ const server = this;
742
+ this.app.use(async function mastraHttpLogger(ctx, next) {
743
+ if (!server.shouldLogRequest(ctx.path)) return next();
744
+ const start = Date.now();
745
+ const method = ctx.method;
746
+ const path = ctx.path;
747
+ await next();
748
+ const duration = Date.now() - start;
749
+ const status = ctx.status;
750
+ const level = server.httpLoggingConfig?.level || "info";
751
+ const logData = {
752
+ method,
753
+ path,
754
+ status,
755
+ duration: `${duration}ms`
756
+ };
757
+ if (server.httpLoggingConfig?.includeQueryParams) logData.query = ctx.query;
758
+ if (server.httpLoggingConfig?.includeHeaders) {
759
+ const headers = { ...ctx.headers };
760
+ (server.httpLoggingConfig.redactHeaders || []).forEach((h) => {
761
+ const key = h.toLowerCase();
762
+ if (headers[key] !== void 0) headers[key] = "[REDACTED]";
763
+ });
764
+ logData.headers = headers;
765
+ }
766
+ server.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);
767
+ });
768
+ }
870
769
  };
871
-
770
+ //#endregion
872
771
  export { MastraServer, createAuthMiddleware };
873
- //# sourceMappingURL=index.js.map
772
+
874
773
  //# sourceMappingURL=index.js.map