@mastra/koa 0.1.0-beta.15 → 0.1.0-beta.16

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 ADDED
@@ -0,0 +1,697 @@
1
+ import { Busboy } from '@fastify/busboy';
2
+ import { formatZodError } from '@mastra/server/handlers/error';
3
+ import { MastraServer as MastraServer$1, redactStreamChunk, normalizeQueryParams } from '@mastra/server/server-adapter';
4
+ import { isDevPlaygroundRequest, isProtectedPath, canAccessPublicly, checkRules, defaultAuthConfig } from '@mastra/server/auth';
5
+
6
+ // src/index.ts
7
+
8
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
9
+ var util;
10
+ (function(util2) {
11
+ util2.assertEqual = (_) => {
12
+ };
13
+ function assertIs(_arg) {
14
+ }
15
+ util2.assertIs = assertIs;
16
+ function assertNever(_x) {
17
+ throw new Error();
18
+ }
19
+ util2.assertNever = assertNever;
20
+ util2.arrayToEnum = (items) => {
21
+ const obj = {};
22
+ for (const item of items) {
23
+ obj[item] = item;
24
+ }
25
+ return obj;
26
+ };
27
+ util2.getValidEnumValues = (obj) => {
28
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
29
+ const filtered = {};
30
+ for (const k of validKeys) {
31
+ filtered[k] = obj[k];
32
+ }
33
+ return util2.objectValues(filtered);
34
+ };
35
+ util2.objectValues = (obj) => {
36
+ return util2.objectKeys(obj).map(function(e) {
37
+ return obj[e];
38
+ });
39
+ };
40
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
41
+ const keys = [];
42
+ for (const key in object) {
43
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
44
+ keys.push(key);
45
+ }
46
+ }
47
+ return keys;
48
+ };
49
+ util2.find = (arr, checker) => {
50
+ for (const item of arr) {
51
+ if (checker(item))
52
+ return item;
53
+ }
54
+ return void 0;
55
+ };
56
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
57
+ function joinValues(array, separator = " | ") {
58
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
59
+ }
60
+ util2.joinValues = joinValues;
61
+ util2.jsonStringifyReplacer = (_, value) => {
62
+ if (typeof value === "bigint") {
63
+ return value.toString();
64
+ }
65
+ return value;
66
+ };
67
+ })(util || (util = {}));
68
+ var objectUtil;
69
+ (function(objectUtil2) {
70
+ objectUtil2.mergeShapes = (first, second) => {
71
+ return {
72
+ ...first,
73
+ ...second
74
+ // second overwrites first
75
+ };
76
+ };
77
+ })(objectUtil || (objectUtil = {}));
78
+ util.arrayToEnum([
79
+ "string",
80
+ "nan",
81
+ "number",
82
+ "integer",
83
+ "float",
84
+ "boolean",
85
+ "date",
86
+ "bigint",
87
+ "symbol",
88
+ "function",
89
+ "undefined",
90
+ "null",
91
+ "array",
92
+ "object",
93
+ "unknown",
94
+ "promise",
95
+ "void",
96
+ "never",
97
+ "map",
98
+ "set"
99
+ ]);
100
+
101
+ // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
102
+ util.arrayToEnum([
103
+ "invalid_type",
104
+ "invalid_literal",
105
+ "custom",
106
+ "invalid_union",
107
+ "invalid_union_discriminator",
108
+ "invalid_enum_value",
109
+ "unrecognized_keys",
110
+ "invalid_arguments",
111
+ "invalid_return_type",
112
+ "invalid_date",
113
+ "invalid_string",
114
+ "too_small",
115
+ "too_big",
116
+ "invalid_intersection_types",
117
+ "not_multiple_of",
118
+ "not_finite"
119
+ ]);
120
+ var ZodError = class _ZodError extends Error {
121
+ get errors() {
122
+ return this.issues;
123
+ }
124
+ constructor(issues) {
125
+ super();
126
+ this.issues = [];
127
+ this.addIssue = (sub) => {
128
+ this.issues = [...this.issues, sub];
129
+ };
130
+ this.addIssues = (subs = []) => {
131
+ this.issues = [...this.issues, ...subs];
132
+ };
133
+ const actualProto = new.target.prototype;
134
+ if (Object.setPrototypeOf) {
135
+ Object.setPrototypeOf(this, actualProto);
136
+ } else {
137
+ this.__proto__ = actualProto;
138
+ }
139
+ this.name = "ZodError";
140
+ this.issues = issues;
141
+ }
142
+ format(_mapper) {
143
+ const mapper = _mapper || function(issue) {
144
+ return issue.message;
145
+ };
146
+ const fieldErrors = { _errors: [] };
147
+ const processError = (error) => {
148
+ for (const issue of error.issues) {
149
+ if (issue.code === "invalid_union") {
150
+ issue.unionErrors.map(processError);
151
+ } else if (issue.code === "invalid_return_type") {
152
+ processError(issue.returnTypeError);
153
+ } else if (issue.code === "invalid_arguments") {
154
+ processError(issue.argumentsError);
155
+ } else if (issue.path.length === 0) {
156
+ fieldErrors._errors.push(mapper(issue));
157
+ } else {
158
+ let curr = fieldErrors;
159
+ let i = 0;
160
+ while (i < issue.path.length) {
161
+ const el = issue.path[i];
162
+ const terminal = i === issue.path.length - 1;
163
+ if (!terminal) {
164
+ curr[el] = curr[el] || { _errors: [] };
165
+ } else {
166
+ curr[el] = curr[el] || { _errors: [] };
167
+ curr[el]._errors.push(mapper(issue));
168
+ }
169
+ curr = curr[el];
170
+ i++;
171
+ }
172
+ }
173
+ }
174
+ };
175
+ processError(this);
176
+ return fieldErrors;
177
+ }
178
+ static assert(value) {
179
+ if (!(value instanceof _ZodError)) {
180
+ throw new Error(`Not a ZodError: ${value}`);
181
+ }
182
+ }
183
+ toString() {
184
+ return this.message;
185
+ }
186
+ get message() {
187
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
188
+ }
189
+ get isEmpty() {
190
+ return this.issues.length === 0;
191
+ }
192
+ flatten(mapper = (issue) => issue.message) {
193
+ const fieldErrors = {};
194
+ const formErrors = [];
195
+ for (const sub of this.issues) {
196
+ if (sub.path.length > 0) {
197
+ const firstEl = sub.path[0];
198
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
199
+ fieldErrors[firstEl].push(mapper(sub));
200
+ } else {
201
+ formErrors.push(mapper(sub));
202
+ }
203
+ }
204
+ return { formErrors, fieldErrors };
205
+ }
206
+ get formErrors() {
207
+ return this.flatten();
208
+ }
209
+ };
210
+ ZodError.create = (issues) => {
211
+ const error = new ZodError(issues);
212
+ return error;
213
+ };
214
+ var authenticationMiddleware = async (ctx, next) => {
215
+ const mastra = ctx.state.mastra;
216
+ const authConfig = mastra.getServer()?.auth;
217
+ const customRouteAuthConfig = ctx.state.customRouteAuthConfig;
218
+ if (!authConfig) {
219
+ return next();
220
+ }
221
+ const path = String(ctx.path || "/");
222
+ const method = String(ctx.method || "GET");
223
+ const getHeader = (name) => ctx.headers[name.toLowerCase()];
224
+ if (isDevPlaygroundRequest(path, method, getHeader, authConfig)) {
225
+ return next();
226
+ }
227
+ if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {
228
+ return next();
229
+ }
230
+ if (canAccessPublicly(path, method, authConfig)) {
231
+ return next();
232
+ }
233
+ const authHeader = ctx.headers.authorization;
234
+ let token = authHeader ? authHeader.replace("Bearer ", "") : null;
235
+ const query = ctx.query;
236
+ if (!token && query.apiKey) {
237
+ token = query.apiKey || null;
238
+ }
239
+ if (!token) {
240
+ ctx.status = 401;
241
+ ctx.body = { error: "Authentication required" };
242
+ return;
243
+ }
244
+ try {
245
+ let user;
246
+ if (typeof authConfig.authenticateToken === "function") {
247
+ user = await authConfig.authenticateToken(token, ctx.request);
248
+ } else {
249
+ throw new Error("No token verification method configured");
250
+ }
251
+ if (!user) {
252
+ ctx.status = 401;
253
+ ctx.body = { error: "Invalid or expired token" };
254
+ return;
255
+ }
256
+ ctx.state.requestContext.set("user", user);
257
+ return next();
258
+ } catch (err) {
259
+ console.error(err);
260
+ ctx.status = 401;
261
+ ctx.body = { error: "Invalid or expired token" };
262
+ return;
263
+ }
264
+ };
265
+ var authorizationMiddleware = async (ctx, next) => {
266
+ const mastra = ctx.state.mastra;
267
+ const authConfig = mastra.getServer()?.auth;
268
+ const customRouteAuthConfig = ctx.state.customRouteAuthConfig;
269
+ if (!authConfig) {
270
+ return next();
271
+ }
272
+ const path = String(ctx.path || "/");
273
+ const method = String(ctx.method || "GET");
274
+ const getHeader = (name) => ctx.headers[name.toLowerCase()];
275
+ if (isDevPlaygroundRequest(path, method, getHeader, authConfig)) {
276
+ return next();
277
+ }
278
+ if (!isProtectedPath(path, method, authConfig, customRouteAuthConfig)) {
279
+ return next();
280
+ }
281
+ if (canAccessPublicly(path, method, authConfig)) {
282
+ return next();
283
+ }
284
+ const user = ctx.state.requestContext.get("user");
285
+ if ("authorizeUser" in authConfig && typeof authConfig.authorizeUser === "function") {
286
+ try {
287
+ const isAuthorized = await authConfig.authorizeUser(user, ctx.request);
288
+ if (isAuthorized) {
289
+ return next();
290
+ }
291
+ ctx.status = 403;
292
+ ctx.body = { error: "Access denied" };
293
+ return;
294
+ } catch (err) {
295
+ console.error(err);
296
+ ctx.status = 500;
297
+ ctx.body = { error: "Authorization error" };
298
+ return;
299
+ }
300
+ }
301
+ if ("authorize" in authConfig && typeof authConfig.authorize === "function") {
302
+ try {
303
+ const context = {
304
+ get: (key) => {
305
+ if (key === "mastra") return ctx.state.mastra;
306
+ if (key === "requestContext") return ctx.state.requestContext;
307
+ if (key === "tools") return ctx.state.tools;
308
+ if (key === "taskStore") return ctx.state.taskStore;
309
+ if (key === "customRouteAuthConfig") return ctx.state.customRouteAuthConfig;
310
+ return void 0;
311
+ },
312
+ req: ctx.request
313
+ };
314
+ const isAuthorized = await authConfig.authorize(path, method, user, context);
315
+ if (isAuthorized) {
316
+ return next();
317
+ }
318
+ ctx.status = 403;
319
+ ctx.body = { error: "Access denied" };
320
+ return;
321
+ } catch (err) {
322
+ console.error(err);
323
+ ctx.status = 500;
324
+ ctx.body = { error: "Authorization error" };
325
+ return;
326
+ }
327
+ }
328
+ if ("rules" in authConfig && authConfig.rules && authConfig.rules.length > 0) {
329
+ const isAuthorized = await checkRules(authConfig.rules, path, method, user);
330
+ if (isAuthorized) {
331
+ return next();
332
+ }
333
+ ctx.status = 403;
334
+ ctx.body = { error: "Access denied" };
335
+ return;
336
+ }
337
+ if (defaultAuthConfig.rules && defaultAuthConfig.rules.length > 0) {
338
+ const isAuthorized = await checkRules(defaultAuthConfig.rules, path, method, user);
339
+ if (isAuthorized) {
340
+ return next();
341
+ }
342
+ }
343
+ ctx.status = 403;
344
+ ctx.body = { error: "Access denied" };
345
+ };
346
+
347
+ // src/index.ts
348
+ var MastraServer = class extends MastraServer$1 {
349
+ createContextMiddleware() {
350
+ return async (ctx, next) => {
351
+ let bodyRequestContext;
352
+ let paramsRequestContext;
353
+ if (ctx.method === "POST" || ctx.method === "PUT") {
354
+ const contentType = ctx.headers["content-type"];
355
+ if (contentType?.includes("application/json") && ctx.request.body) {
356
+ const body = ctx.request.body;
357
+ if (body.requestContext) {
358
+ bodyRequestContext = body.requestContext;
359
+ }
360
+ }
361
+ }
362
+ if (ctx.method === "GET") {
363
+ try {
364
+ const query = ctx.query;
365
+ const encodedRequestContext = query.requestContext;
366
+ if (typeof encodedRequestContext === "string") {
367
+ try {
368
+ paramsRequestContext = JSON.parse(encodedRequestContext);
369
+ } catch {
370
+ try {
371
+ const json = Buffer.from(encodedRequestContext, "base64").toString("utf-8");
372
+ paramsRequestContext = JSON.parse(json);
373
+ } catch {
374
+ }
375
+ }
376
+ }
377
+ } catch {
378
+ }
379
+ }
380
+ const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });
381
+ ctx.state.requestContext = requestContext;
382
+ ctx.state.mastra = this.mastra;
383
+ ctx.state.tools = this.tools || {};
384
+ if (this.taskStore) {
385
+ ctx.state.taskStore = this.taskStore;
386
+ }
387
+ ctx.state.customRouteAuthConfig = this.customRouteAuthConfig;
388
+ const controller = new AbortController();
389
+ ctx.req.on("close", () => {
390
+ if (!ctx.res.writableEnded) {
391
+ controller.abort();
392
+ }
393
+ });
394
+ ctx.state.abortSignal = controller.signal;
395
+ await next();
396
+ };
397
+ }
398
+ async stream(route, ctx, result) {
399
+ ctx.respond = false;
400
+ ctx.res.writeHead(200, {
401
+ "Content-Type": "text/plain",
402
+ "Transfer-Encoding": "chunked"
403
+ });
404
+ const streamFormat = route.streamFormat || "stream";
405
+ const readableStream = result instanceof ReadableStream ? result : result.fullStream;
406
+ const reader = readableStream.getReader();
407
+ ctx.res.on("close", () => {
408
+ void reader.cancel("request aborted");
409
+ });
410
+ try {
411
+ while (true) {
412
+ const { done, value } = await reader.read();
413
+ if (done) break;
414
+ if (value) {
415
+ const shouldRedact = this.streamOptions?.redact ?? true;
416
+ const outputValue = shouldRedact ? redactStreamChunk(value) : value;
417
+ if (streamFormat === "sse") {
418
+ ctx.res.write(`data: ${JSON.stringify(outputValue)}
419
+
420
+ `);
421
+ } else {
422
+ ctx.res.write(JSON.stringify(outputValue) + "");
423
+ }
424
+ }
425
+ }
426
+ } catch (error) {
427
+ console.error(error);
428
+ } finally {
429
+ ctx.res.end();
430
+ }
431
+ }
432
+ async getParams(route, ctx) {
433
+ const urlParams = ctx.params || {};
434
+ const queryParams = normalizeQueryParams(ctx.query || {});
435
+ let body;
436
+ if (route.method === "POST" || route.method === "PUT" || route.method === "PATCH") {
437
+ const contentType = ctx.headers["content-type"] || "";
438
+ if (contentType.includes("multipart/form-data")) {
439
+ try {
440
+ const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;
441
+ body = await this.parseMultipartFormData(ctx, maxFileSize);
442
+ } catch (error) {
443
+ console.error("Failed to parse multipart form data:", error);
444
+ if (error instanceof Error && error.message.toLowerCase().includes("size")) {
445
+ throw error;
446
+ }
447
+ }
448
+ } else {
449
+ body = ctx.request.body;
450
+ }
451
+ }
452
+ return { urlParams, queryParams, body };
453
+ }
454
+ /**
455
+ * Parse multipart/form-data using @fastify/busboy.
456
+ * Converts file uploads to Buffers and parses JSON field values.
457
+ *
458
+ * @param ctx - The Koa context object
459
+ * @param maxFileSize - Optional maximum file size in bytes
460
+ */
461
+ parseMultipartFormData(ctx, maxFileSize) {
462
+ return new Promise((resolve, reject) => {
463
+ const result = {};
464
+ const busboy = new Busboy({
465
+ headers: {
466
+ "content-type": ctx.headers["content-type"]
467
+ },
468
+ limits: maxFileSize ? { fileSize: maxFileSize } : void 0
469
+ });
470
+ busboy.on("file", (fieldname, file) => {
471
+ const chunks = [];
472
+ let limitExceeded = false;
473
+ file.on("data", (chunk) => {
474
+ chunks.push(chunk);
475
+ });
476
+ file.on("limit", () => {
477
+ limitExceeded = true;
478
+ reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ""}`));
479
+ });
480
+ file.on("end", () => {
481
+ if (!limitExceeded) {
482
+ result[fieldname] = Buffer.concat(chunks);
483
+ }
484
+ });
485
+ });
486
+ busboy.on("field", (fieldname, value) => {
487
+ try {
488
+ result[fieldname] = JSON.parse(value);
489
+ } catch {
490
+ result[fieldname] = value;
491
+ }
492
+ });
493
+ busboy.on("finish", () => {
494
+ resolve(result);
495
+ });
496
+ busboy.on("error", (error) => {
497
+ reject(error);
498
+ });
499
+ ctx.req.pipe(busboy);
500
+ });
501
+ }
502
+ async sendResponse(route, ctx, result) {
503
+ if (route.responseType === "json") {
504
+ ctx.body = result;
505
+ } else if (route.responseType === "stream") {
506
+ await this.stream(route, ctx, result);
507
+ } else if (route.responseType === "datastream-response") {
508
+ ctx.respond = false;
509
+ const fetchResponse = result;
510
+ const headers = {};
511
+ fetchResponse.headers.forEach((value, key) => {
512
+ headers[key] = value;
513
+ });
514
+ ctx.res.writeHead(fetchResponse.status, headers);
515
+ if (fetchResponse.body) {
516
+ const reader = fetchResponse.body.getReader();
517
+ try {
518
+ while (true) {
519
+ const { done, value } = await reader.read();
520
+ if (done) break;
521
+ ctx.res.write(value);
522
+ }
523
+ } finally {
524
+ ctx.res.end();
525
+ }
526
+ } else {
527
+ ctx.res.end();
528
+ }
529
+ } else if (route.responseType === "mcp-http") {
530
+ ctx.respond = false;
531
+ const { server, httpPath } = result;
532
+ try {
533
+ const rawReq = ctx.req;
534
+ if (ctx.request.body !== void 0) {
535
+ rawReq.body = ctx.request.body;
536
+ }
537
+ await server.startHTTP({
538
+ url: new URL(ctx.url, `http://${ctx.headers.host}`),
539
+ httpPath,
540
+ req: rawReq,
541
+ res: ctx.res
542
+ });
543
+ } catch {
544
+ if (!ctx.res.headersSent) {
545
+ ctx.res.writeHead(500, { "Content-Type": "application/json" });
546
+ ctx.res.end(
547
+ JSON.stringify({
548
+ jsonrpc: "2.0",
549
+ error: { code: -32603, message: "Internal server error" },
550
+ id: null
551
+ })
552
+ );
553
+ }
554
+ }
555
+ } else if (route.responseType === "mcp-sse") {
556
+ ctx.respond = false;
557
+ const { server, ssePath, messagePath } = result;
558
+ try {
559
+ const rawReq = ctx.req;
560
+ if (ctx.request.body !== void 0) {
561
+ rawReq.body = ctx.request.body;
562
+ }
563
+ await server.startSSE({
564
+ url: new URL(ctx.url, `http://${ctx.headers.host}`),
565
+ ssePath,
566
+ messagePath,
567
+ req: rawReq,
568
+ res: ctx.res
569
+ });
570
+ } catch {
571
+ if (!ctx.res.headersSent) {
572
+ ctx.res.writeHead(500, { "Content-Type": "application/json" });
573
+ ctx.res.end(JSON.stringify({ error: "Error handling MCP SSE request" }));
574
+ }
575
+ }
576
+ } else {
577
+ ctx.status = 500;
578
+ }
579
+ }
580
+ async registerRoute(app, route, { prefix }) {
581
+ const fullPath = `${prefix}${route.path}`;
582
+ const koaPath = fullPath;
583
+ const handler = async (ctx, next) => {
584
+ const pathRegex = this.pathToRegex(koaPath);
585
+ const match = pathRegex.exec(ctx.path);
586
+ if (!match) {
587
+ await next();
588
+ return;
589
+ }
590
+ if (route.method.toUpperCase() !== "ALL" && ctx.method.toUpperCase() !== route.method.toUpperCase()) {
591
+ await next();
592
+ return;
593
+ }
594
+ const paramNames = this.extractParamNames(koaPath);
595
+ ctx.params = {};
596
+ paramNames.forEach((name, index) => {
597
+ ctx.params[name] = match[index + 1];
598
+ });
599
+ const params = await this.getParams(route, ctx);
600
+ if (params.queryParams) {
601
+ try {
602
+ params.queryParams = await this.parseQueryParams(route, params.queryParams);
603
+ } catch (error) {
604
+ console.error("Error parsing query params", error);
605
+ if (error instanceof ZodError) {
606
+ ctx.status = 400;
607
+ ctx.body = formatZodError(error, "query parameters");
608
+ return;
609
+ }
610
+ ctx.status = 400;
611
+ ctx.body = {
612
+ error: "Invalid query parameters",
613
+ issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
614
+ };
615
+ return;
616
+ }
617
+ }
618
+ if (params.body) {
619
+ try {
620
+ params.body = await this.parseBody(route, params.body);
621
+ } catch (error) {
622
+ console.error("Error parsing body:", error instanceof Error ? error.message : String(error));
623
+ if (error instanceof ZodError) {
624
+ ctx.status = 400;
625
+ ctx.body = formatZodError(error, "request body");
626
+ return;
627
+ }
628
+ ctx.status = 400;
629
+ ctx.body = {
630
+ error: "Invalid request body",
631
+ issues: [{ field: "unknown", message: error instanceof Error ? error.message : "Unknown error" }]
632
+ };
633
+ return;
634
+ }
635
+ }
636
+ const handlerParams = {
637
+ ...params.urlParams,
638
+ ...params.queryParams,
639
+ ...typeof params.body === "object" ? params.body : {},
640
+ requestContext: ctx.state.requestContext,
641
+ mastra: this.mastra,
642
+ tools: ctx.state.tools,
643
+ taskStore: ctx.state.taskStore,
644
+ abortSignal: ctx.state.abortSignal
645
+ };
646
+ try {
647
+ const result = await route.handler(handlerParams);
648
+ await this.sendResponse(route, ctx, result);
649
+ } catch (error) {
650
+ console.error("Error calling handler", error);
651
+ let status = 500;
652
+ if (error && typeof error === "object") {
653
+ if ("status" in error) {
654
+ status = error.status;
655
+ } else if ("details" in error && error.details && typeof error.details === "object" && "status" in error.details) {
656
+ status = error.details.status;
657
+ }
658
+ }
659
+ ctx.status = status;
660
+ ctx.body = { error: error instanceof Error ? error.message : "Unknown error" };
661
+ }
662
+ };
663
+ app.use(handler);
664
+ }
665
+ /**
666
+ * Convert Express-style path to regex for matching
667
+ */
668
+ pathToRegex(path) {
669
+ const PARAM_PLACEHOLDER = "\0PARAM\0";
670
+ const pathWithPlaceholders = path.replace(/:[^/]+/g, PARAM_PLACEHOLDER);
671
+ const escapedPath = pathWithPlaceholders.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
672
+ const regexPath = escapedPath.replace(new RegExp(PARAM_PLACEHOLDER, "g"), "([^/]+)").replace(/\//g, "\\/");
673
+ return new RegExp(`^${regexPath}$`);
674
+ }
675
+ /**
676
+ * Extract parameter names from path
677
+ */
678
+ extractParamNames(path) {
679
+ const matches = path.match(/:[^/]+/g) || [];
680
+ return matches.map((m) => m.slice(1));
681
+ }
682
+ registerContextMiddleware() {
683
+ this.app.use(this.createContextMiddleware());
684
+ }
685
+ registerAuthMiddleware() {
686
+ const authConfig = this.mastra.getServer()?.auth;
687
+ if (!authConfig) {
688
+ return;
689
+ }
690
+ this.app.use(authenticationMiddleware);
691
+ this.app.use(authorizationMiddleware);
692
+ }
693
+ };
694
+
695
+ export { MastraServer };
696
+ //# sourceMappingURL=index.js.map
697
+ //# sourceMappingURL=index.js.map