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