@mastra/deployer 1.87.0-alpha.1 → 1.87.0-alpha.11

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.
@@ -3,7 +3,7 @@ name: mastra-deployer
3
3
  description: Documentation for @mastra/deployer. Use when working with @mastra/deployer APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/deployer"
6
- version: "1.87.0-alpha.1"
6
+ version: "1.87.0-alpha.11"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.87.0-alpha.1",
2
+ "version": "1.87.0-alpha.11",
3
3
  "package": "@mastra/deployer",
4
4
  "exports": {
5
5
  "Deployer": {
@@ -124,12 +124,12 @@ The build follows these steps:
124
124
 
125
125
  ## Environment variables
126
126
 
127
- | Variable | Description |
128
- | -------------------- | --------------------------------------------------------------------------- |
129
- | `PORT` | Server port (default: `4111`) |
130
- | `MASTRA_STUDIO_PATH` | Path to Studio build directory (default: `./playground`) |
131
- | `MASTRA_SKIP_DOTENV` | Skip loading `.env` files when set |
132
- | `NODE_OPTIONS` | Node.js options (e.g., `--max-old-space-size=4096` for build memory issues) |
127
+ | Variable | Description |
128
+ | -------------------- | ----------------------------------------------------------------------------------------- |
129
+ | `PORT` | Server port (default: `4111`) |
130
+ | `MASTRA_STUDIO_PATH` | Path to Studio build directory (default: the `studio` directory next to the built server) |
131
+ | `MASTRA_SKIP_DOTENV` | Skip loading `.env` files when set |
132
+ | `NODE_OPTIONS` | Node.js options (e.g., `--max-old-space-size=4096` for build memory issues) |
133
133
 
134
134
  ## Server endpoints
135
135
 
@@ -3628,6 +3628,18 @@ function cancelUnreadBodyOnAbort(response, signal) {
3628
3628
  if (signal.aborted) cancel();
3629
3629
  else signal.addEventListener("abort", cancel, { once: true });
3630
3630
  }
3631
+ /**
3632
+ * Releases an adapter-owned body branch that will not be forwarded. `Request.clone()` tees the body, so an unread
3633
+ * branch retains the whole body until GC. Cancelling the unused branch frees it while the forwarded branch streams.
3634
+ *
3635
+ * The cancel is intentionally fire-and-forget: fetch tee cancellation only settles once the sibling branch drains (or
3636
+ * is otherwise consumed), so awaiting it here would stall dispatch. Rejections are swallowed so cancellation failure
3637
+ * cannot turn into an unhandled rejection or replace the route response.
3638
+ */
3639
+ function releaseUnreadBody(body) {
3640
+ if (!body || body.locked) return;
3641
+ body.cancel("unused request body clone").catch(() => {});
3642
+ }
3631
3643
  const requestClones = /* @__PURE__ */ new WeakMap();
3632
3644
  /**
3633
3645
  * Clones a request and keeps the clone alive for as long as the request itself. Node 22 makes a request's body
@@ -3644,7 +3656,7 @@ function cloneRequest(request) {
3644
3656
  var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
3645
3657
  createContextMiddleware() {
3646
3658
  return async (c, next) => {
3647
- if (this.hasCustomRouteHandler && BODY_METHODS.has(c.req.method) && c.req.raw.body) c.set(MASTRA_PRISTINE_REQUEST_KEY, c.req.raw.clone());
3659
+ if (this.hasCustomRouteHandler && BODY_METHODS.has(c.req.method) && c.req.raw.body && this.matchCustomRoute(c.req.url, c.req.method)) c.set(MASTRA_PRISTINE_REQUEST_KEY, c.req.raw.clone());
3648
3660
  const originalJson = c.req.json.bind(c.req);
3649
3661
  let jsonPromise;
3650
3662
  c.req.json = () => {
@@ -4033,64 +4045,82 @@ var MastraServer = class extends _mastra_server_server_adapter.MastraServer {
4033
4045
  if (!await this.buildCustomRouteHandler(routes)) return;
4034
4046
  for (const route of routes) {
4035
4047
  const routeHandler = async (c) => {
4036
- const { match, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(c.req.url, c.req.method, c.req.path, route);
4037
- const authError = await this.checkRouteAuth(serverRoute, {
4038
- path: c.req.path,
4039
- method: c.req.method,
4040
- getHeader: (name) => c.req.header(name),
4041
- getQuery: (name) => c.req.query(name),
4042
- requestContext: c.get("requestContext"),
4043
- request: c.req.raw,
4044
- buildAuthorizeContext: () => c,
4045
- customRouteAuthConfig
4046
- });
4047
- if (authError) {
4048
- if (authError.headers) for (const [key, value] of Object.entries(authError.headers)) c.header(key, value);
4049
- if (authError.error) return c.json({ error: authError.error }, authError.status);
4050
- }
4051
- const permissionError = this.checkRouteRBAC(serverRoute, c.get("requestContext"));
4052
- if (permissionError) return c.json({
4053
- error: permissionError.error,
4054
- message: permissionError.message
4055
- }, permissionError.status);
4056
- const pristineRequest = c.get(MASTRA_PRISTINE_REQUEST_KEY) ?? c.req.raw;
4057
- let bodyParams = {};
4058
- if ((0, _mastra_server_server_adapter.getFGAProvider)(this.mastra, c.get("requestContext"))) {
4059
- const contentType = c.req.header("content-type");
4060
- if (contentType?.includes("application/json")) try {
4061
- const body = await pristineRequest.clone().json();
4062
- if (body && typeof body === "object" && !Array.isArray(body)) bodyParams = body;
4063
- } catch {
4064
- bodyParams = {};
4048
+ const originalRequest = c.req.raw;
4049
+ const pristineRequest = c.get(MASTRA_PRISTINE_REQUEST_KEY) ?? originalRequest;
4050
+ const hasPristine = pristineRequest !== originalRequest;
4051
+ let releasePristineBody = hasPristine;
4052
+ try {
4053
+ const { match, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(c.req.url, c.req.method, c.req.path, route);
4054
+ const authError = await this.checkRouteAuth(serverRoute, {
4055
+ path: c.req.path,
4056
+ method: c.req.method,
4057
+ getHeader: (name) => c.req.header(name),
4058
+ getQuery: (name) => c.req.query(name),
4059
+ requestContext: c.get("requestContext"),
4060
+ request: c.req.raw,
4061
+ buildAuthorizeContext: () => c,
4062
+ customRouteAuthConfig
4063
+ });
4064
+ if (authError) {
4065
+ if (authError.headers) for (const [key, value] of Object.entries(authError.headers)) c.header(key, value);
4066
+ if (authError.error) return c.json({ error: authError.error }, authError.status);
4065
4067
  }
4066
- else if (contentType?.includes("application/x-www-form-urlencoded") || contentType?.includes("multipart/form-data")) try {
4067
- bodyParams = Object.fromEntries(await pristineRequest.clone().formData());
4068
+ const permissionError = this.checkRouteRBAC(serverRoute, c.get("requestContext"));
4069
+ if (permissionError) return c.json({
4070
+ error: permissionError.error,
4071
+ message: permissionError.message
4072
+ }, permissionError.status);
4073
+ let bodyParams = {};
4074
+ if ((0, _mastra_server_server_adapter.getFGAProvider)(this.mastra, c.get("requestContext"))) {
4075
+ const contentType = c.req.header("content-type");
4076
+ if (contentType?.includes("application/json")) try {
4077
+ const body = await pristineRequest.clone().json();
4078
+ if (body && typeof body === "object" && !Array.isArray(body)) bodyParams = body;
4079
+ } catch {
4080
+ bodyParams = {};
4081
+ }
4082
+ else if (contentType?.includes("application/x-www-form-urlencoded") || contentType?.includes("multipart/form-data")) try {
4083
+ bodyParams = Object.fromEntries(await pristineRequest.clone().formData());
4084
+ } catch {
4085
+ bodyParams = {};
4086
+ }
4087
+ }
4088
+ const fgaError = await (0, _mastra_server_server_adapter.checkRouteFGA)(this.mastra, serverRoute, c.get("requestContext"), {
4089
+ ...Object.fromEntries(new URL(c.req.url).searchParams.entries()),
4090
+ ...bodyParams,
4091
+ ...match ? match.params : c.req.param()
4092
+ });
4093
+ if (fgaError) return c.json({
4094
+ error: fgaError.error,
4095
+ message: fgaError.message
4096
+ }, fgaError.status);
4097
+ const reqHeaders = {};
4098
+ c.req.raw.headers.forEach((v, k) => {
4099
+ reqHeaders[k] = v;
4100
+ });
4101
+ let executionCtx;
4102
+ try {
4103
+ executionCtx = c.executionCtx;
4068
4104
  } catch {
4069
- bodyParams = {};
4105
+ executionCtx = void 0;
4070
4106
  }
4107
+ const originalUntouched = originalRequest.body !== null && !originalRequest.bodyUsed && !originalRequest.body.locked;
4108
+ let requestBody;
4109
+ if (!hasPristine) requestBody = originalRequest.body;
4110
+ else if (originalUntouched) {
4111
+ requestBody = originalRequest.body;
4112
+ releasePristineBody = false;
4113
+ releaseUnreadBody(pristineRequest.body);
4114
+ } else {
4115
+ requestBody = pristineRequest.body;
4116
+ releasePristineBody = false;
4117
+ }
4118
+ const response = await this.handleCustomRouteRequest(c.req.url, c.req.method, reqHeaders, requestBody, c.get("requestContext"), c.req.raw.signal, executionCtx);
4119
+ if (!response) return c.json({ error: "Not Found" }, 404);
4120
+ return response;
4121
+ } finally {
4122
+ if (releasePristineBody) releaseUnreadBody(pristineRequest.body);
4071
4123
  }
4072
- const fgaError = await (0, _mastra_server_server_adapter.checkRouteFGA)(this.mastra, serverRoute, c.get("requestContext"), {
4073
- ...Object.fromEntries(new URL(c.req.url).searchParams.entries()),
4074
- ...bodyParams,
4075
- ...match ? match.params : c.req.param()
4076
- });
4077
- if (fgaError) return c.json({
4078
- error: fgaError.error,
4079
- message: fgaError.message
4080
- }, fgaError.status);
4081
- const reqHeaders = {};
4082
- c.req.raw.headers.forEach((v, k) => {
4083
- reqHeaders[k] = v;
4084
- });
4085
- let executionCtx;
4086
- try {
4087
- executionCtx = c.executionCtx;
4088
- } catch {
4089
- executionCtx = void 0;
4090
- }
4091
- const response = await this.handleCustomRouteRequest(c.req.url, c.req.method, reqHeaders, pristineRequest.body, c.get("requestContext"), c.req.raw.signal, executionCtx);
4092
- if (!response) return c.json({ error: "Not Found" }, 404);
4093
- return response;
4094
4124
  };
4095
4125
  const method = route.method.toLowerCase();
4096
4126
  this.app[method](route.path, routeHandler);
@@ -4851,6 +4881,103 @@ const getStudioPath = () => {
4851
4881
  }
4852
4882
  return process.env.MASTRA_STUDIO_PATH || (0, path.join)(__dirname$1, "studio");
4853
4883
  };
4884
+ const STUDIO_STATIC_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
4885
+ ".js",
4886
+ ".mjs",
4887
+ ".cjs",
4888
+ ".css",
4889
+ ".map",
4890
+ ".json",
4891
+ ".txt",
4892
+ ".xml",
4893
+ ".webmanifest",
4894
+ ".svg",
4895
+ ".png",
4896
+ ".jpg",
4897
+ ".jpeg",
4898
+ ".gif",
4899
+ ".webp",
4900
+ ".avif",
4901
+ ".ico",
4902
+ ".bmp",
4903
+ ".woff",
4904
+ ".woff2",
4905
+ ".ttf",
4906
+ ".otf",
4907
+ ".eot",
4908
+ ".wasm",
4909
+ ".mp4",
4910
+ ".webm",
4911
+ ".mp3",
4912
+ ".wav",
4913
+ ".pdf",
4914
+ ".zip",
4915
+ ".csv",
4916
+ ".tsv",
4917
+ ".dat",
4918
+ ".yml",
4919
+ ".yaml",
4920
+ ".toml",
4921
+ ".ini",
4922
+ ".log",
4923
+ ".md"
4924
+ ]);
4925
+ /**
4926
+ * Classify a path that is already known to be inside the enabled Studio mount as
4927
+ * a static-file request. `studioRelativePath` is the request path with the
4928
+ * configured Studio base removed (root mounting passes the original path).
4929
+ *
4930
+ * A request is static when it lives where Studio only ever serves files from —
4931
+ * `/assets/…` (Vite's hashed chunks), a top-level hidden asset folder such as
4932
+ * `/.well-known/…`, or a top-level non-`.html` file — when its last segment ends
4933
+ * in an extension the build serves files with, or when it maps to a real file in
4934
+ * the build. A *missing* file in any of those locations must still 404 rather
4935
+ * than silently become a successful HTML response, which is what the pre-fix
4936
+ * server did for every dotted path.
4937
+ *
4938
+ * Everything else is a client-side route and reaches the injected Studio HTML
4939
+ * fallback, so `/agents/lead.agent` and `/workflows/billing.v2/graph` work on a
4940
+ * hard load, as does any route that merely *contains* a dotted segment. The
4941
+ * decision never looks at the directories the build ships: a route may sit in a
4942
+ * directory whose name the build also uses, so `/agents/lead.agent` keeps working
4943
+ * even when a real `agents/` directory is part of the Studio build.
4944
+ *
4945
+ * Trade-off (maintainer decision, 2026-11-29, #30296): with no file behind it, a
4946
+ * suffixed last segment cannot be told apart from a missing asset. The decision
4947
+ * keeps the file: a route whose *last* segment names a file type is treated as a
4948
+ * missing file, so `/agents/release.json` and `/agents/report.csv` 404 by design.
4949
+ *
4950
+ * The Studio root is normalised to an absolute path before any lookup:
4951
+ * `getStudioPath()` can return a relative value (e.g. `MASTRA_STUDIO_PATH=studio`)
4952
+ * or one with a trailing separator, and the containment check has to compare like
4953
+ * with like or every lookup misses and real nested files fall through to the
4954
+ * HTML shell.
4955
+ */
4956
+ const isStudioStaticFileRequest = async (studioRelativePath) => {
4957
+ if (studioRelativePath.endsWith(".html")) return false;
4958
+ if (studioRelativePath.startsWith("/assets/")) return true;
4959
+ if (studioRelativePath.startsWith("/.")) return true;
4960
+ const withoutLeadingSlash = studioRelativePath.slice(1);
4961
+ const segments = withoutLeadingSlash.split("/");
4962
+ if (segments.length === 1 && withoutLeadingSlash.includes(".")) return true;
4963
+ const lastSegment = [...segments].reverse().find((segment) => segment.length > 0) ?? "";
4964
+ const extensionIndex = lastSegment.lastIndexOf(".");
4965
+ if (extensionIndex > 0 && extensionIndex < lastSegment.length - 1 && STUDIO_STATIC_FILE_EXTENSIONS.has(lastSegment.slice(extensionIndex).toLowerCase())) return true;
4966
+ const root = (0, path.resolve)(getStudioPath());
4967
+ const candidates = [studioRelativePath];
4968
+ try {
4969
+ const decoded = decodeURIComponent(studioRelativePath);
4970
+ if (decoded !== studioRelativePath) candidates.push(decoded);
4971
+ } catch {}
4972
+ for (const candidate of candidates) {
4973
+ const resolved = (0, path.resolve)(root, `.${candidate}`);
4974
+ if (!resolved.startsWith(`${root}${path.sep}`)) continue;
4975
+ try {
4976
+ if ((await (0, fs_promises.stat)(resolved)).isFile()) return true;
4977
+ } catch {}
4978
+ }
4979
+ return false;
4980
+ };
4854
4981
  function isSchemaApiRoute(route) {
4855
4982
  return "_mastraSchemaRoute" in route && route._mastraSchemaRoute === true;
4856
4983
  }
@@ -4889,6 +5016,39 @@ function getRouteCorsConfig(apiRoutes, pathname, method) {
4889
5016
  const route = (0, _mastra_server_auth.findMatchingCustomRoute)(pathname, method, apiRoutes)?.route;
4890
5017
  return route && !isSchemaApiRoute(route) ? route.cors : void 0;
4891
5018
  }
5019
+ const splitOnUnquoted = (headerValue, delimiter) => {
5020
+ const parts = [];
5021
+ let currentPart = "";
5022
+ let quoted = false;
5023
+ for (let index = 0; index < headerValue.length; index += 1) {
5024
+ const character = headerValue.charAt(index);
5025
+ if (quoted && character === "\\") {
5026
+ currentPart += character + headerValue.charAt(index + 1);
5027
+ index += 1;
5028
+ continue;
5029
+ }
5030
+ if (character === "\"") quoted = !quoted;
5031
+ else if (character === delimiter && !quoted) {
5032
+ parts.push(currentPart);
5033
+ currentPart = "";
5034
+ continue;
5035
+ }
5036
+ currentPart += character;
5037
+ }
5038
+ parts.push(currentPart);
5039
+ return parts;
5040
+ };
5041
+ function explicitlyAcceptsJson(acceptHeader) {
5042
+ if (!acceptHeader) return false;
5043
+ return splitOnUnquoted(acceptHeader, ",").some((mediaRange) => {
5044
+ const [mediaType, ...parameters] = splitOnUnquoted(mediaRange, ";");
5045
+ if (mediaType?.trim().toLowerCase() !== "application/json") return false;
5046
+ const quality = parameters.map((parameter) => parameter.trim().toLowerCase()).find((parameter) => parameter.startsWith("q="));
5047
+ if (quality === void 0) return true;
5048
+ const qualityValue = Number.parseFloat(quality.slice(2));
5049
+ return Number.isNaN(qualityValue) || qualityValue > 0;
5050
+ });
5051
+ }
4892
5052
  function getToolExports(tools) {
4893
5053
  try {
4894
5054
  return tools.reduce((acc, toolModule) => {
@@ -5071,9 +5231,13 @@ async function createHonoServer(mastra, options = { tools: {} }) {
5071
5231
  app.get("*", async (c, next) => {
5072
5232
  const requestPath = c.req.path;
5073
5233
  if (requestPath === apiPrefix || requestPath.startsWith(`${apiPrefix}/`) || requestPath.startsWith("/swagger-ui") || requestPath.startsWith("/openapi.json")) return await next();
5074
- if (requestPath.includes(".") && !requestPath.endsWith(".html")) return await next();
5234
+ if ((requestPath === "/web" || requestPath.startsWith("/web/")) && explicitlyAcceptsJson(c.req.header("Accept"))) return await next();
5075
5235
  const isStudioRoute = studioBasePath === "" || requestPath === studioBasePath || requestPath.startsWith(`${studioBasePath}/`);
5076
- if (options?.studio && isStudioRoute) {
5236
+ const servesStudio = Boolean(options?.studio && isStudioRoute);
5237
+ if (servesStudio) {
5238
+ if (await isStudioStaticFileRequest(requestPath.slice(studioBasePath.length))) return await next();
5239
+ } else if (requestPath.includes(".") && !requestPath.endsWith(".html")) return await next();
5240
+ if (servesStudio) {
5077
5241
  const studioPath = getStudioPath();
5078
5242
  let indexHtml = await (0, fs_promises.readFile)((0, path.join)(studioPath, "index.html"), "utf-8");
5079
5243
  const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);
@@ -1,5 +1,5 @@
1
1
  import type { Mastra } from '@mastra/core/mastra';
2
- import type { HonoBindings, HonoVariables } from '../_types/@mastra_hono@1.7.29-alpha.1/dist/index.js';
2
+ import type { HonoBindings, HonoVariables } from '../_types/@mastra_hono@1.7.29-alpha.11/dist/index.js';
3
3
  import { Hono } from 'hono';
4
4
  import type { ServerBundleOptions } from './types.js';
5
5
  type Bindings = HonoBindings;
@@ -1,8 +1,8 @@
1
1
  import "../index-CLddUTqr-FaVhUOQu.js";
2
2
  import { d as normalizeStudioBase, n as escapeStudioHtmlValue, o as injectStudioHtmlConfig } from "../utils-C8gwr-ur.js";
3
3
  import { createReadStream, existsSync, statSync } from "fs";
4
- import { readFile } from "fs/promises";
5
- import { dirname, join } from "path";
4
+ import { readFile, stat } from "fs/promises";
5
+ import { dirname, join, resolve, sep } from "path";
6
6
  import { Readable, Writable } from "stream";
7
7
  import { fileURLToPath } from "url";
8
8
  import * as https from "https";
@@ -3623,6 +3623,18 @@ function cancelUnreadBodyOnAbort(response, signal) {
3623
3623
  if (signal.aborted) cancel();
3624
3624
  else signal.addEventListener("abort", cancel, { once: true });
3625
3625
  }
3626
+ /**
3627
+ * Releases an adapter-owned body branch that will not be forwarded. `Request.clone()` tees the body, so an unread
3628
+ * branch retains the whole body until GC. Cancelling the unused branch frees it while the forwarded branch streams.
3629
+ *
3630
+ * The cancel is intentionally fire-and-forget: fetch tee cancellation only settles once the sibling branch drains (or
3631
+ * is otherwise consumed), so awaiting it here would stall dispatch. Rejections are swallowed so cancellation failure
3632
+ * cannot turn into an unhandled rejection or replace the route response.
3633
+ */
3634
+ function releaseUnreadBody(body) {
3635
+ if (!body || body.locked) return;
3636
+ body.cancel("unused request body clone").catch(() => {});
3637
+ }
3626
3638
  const requestClones = /* @__PURE__ */ new WeakMap();
3627
3639
  /**
3628
3640
  * Clones a request and keeps the clone alive for as long as the request itself. Node 22 makes a request's body
@@ -3639,7 +3651,7 @@ function cloneRequest(request) {
3639
3651
  var MastraServer$2 = class extends MastraServer {
3640
3652
  createContextMiddleware() {
3641
3653
  return async (c, next) => {
3642
- if (this.hasCustomRouteHandler && BODY_METHODS.has(c.req.method) && c.req.raw.body) c.set(MASTRA_PRISTINE_REQUEST_KEY, c.req.raw.clone());
3654
+ if (this.hasCustomRouteHandler && BODY_METHODS.has(c.req.method) && c.req.raw.body && this.matchCustomRoute(c.req.url, c.req.method)) c.set(MASTRA_PRISTINE_REQUEST_KEY, c.req.raw.clone());
3643
3655
  const originalJson = c.req.json.bind(c.req);
3644
3656
  let jsonPromise;
3645
3657
  c.req.json = () => {
@@ -4028,64 +4040,82 @@ var MastraServer$2 = class extends MastraServer {
4028
4040
  if (!await this.buildCustomRouteHandler(routes)) return;
4029
4041
  for (const route of routes) {
4030
4042
  const routeHandler = async (c) => {
4031
- const { match, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(c.req.url, c.req.method, c.req.path, route);
4032
- const authError = await this.checkRouteAuth(serverRoute, {
4033
- path: c.req.path,
4034
- method: c.req.method,
4035
- getHeader: (name) => c.req.header(name),
4036
- getQuery: (name) => c.req.query(name),
4037
- requestContext: c.get("requestContext"),
4038
- request: c.req.raw,
4039
- buildAuthorizeContext: () => c,
4040
- customRouteAuthConfig
4041
- });
4042
- if (authError) {
4043
- if (authError.headers) for (const [key, value] of Object.entries(authError.headers)) c.header(key, value);
4044
- if (authError.error) return c.json({ error: authError.error }, authError.status);
4045
- }
4046
- const permissionError = this.checkRouteRBAC(serverRoute, c.get("requestContext"));
4047
- if (permissionError) return c.json({
4048
- error: permissionError.error,
4049
- message: permissionError.message
4050
- }, permissionError.status);
4051
- const pristineRequest = c.get(MASTRA_PRISTINE_REQUEST_KEY) ?? c.req.raw;
4052
- let bodyParams = {};
4053
- if (getFGAProvider(this.mastra, c.get("requestContext"))) {
4054
- const contentType = c.req.header("content-type");
4055
- if (contentType?.includes("application/json")) try {
4056
- const body = await pristineRequest.clone().json();
4057
- if (body && typeof body === "object" && !Array.isArray(body)) bodyParams = body;
4058
- } catch {
4059
- bodyParams = {};
4043
+ const originalRequest = c.req.raw;
4044
+ const pristineRequest = c.get(MASTRA_PRISTINE_REQUEST_KEY) ?? originalRequest;
4045
+ const hasPristine = pristineRequest !== originalRequest;
4046
+ let releasePristineBody = hasPristine;
4047
+ try {
4048
+ const { match, serverRoute, customRouteAuthConfig } = this.resolveCustomRouteAuth(c.req.url, c.req.method, c.req.path, route);
4049
+ const authError = await this.checkRouteAuth(serverRoute, {
4050
+ path: c.req.path,
4051
+ method: c.req.method,
4052
+ getHeader: (name) => c.req.header(name),
4053
+ getQuery: (name) => c.req.query(name),
4054
+ requestContext: c.get("requestContext"),
4055
+ request: c.req.raw,
4056
+ buildAuthorizeContext: () => c,
4057
+ customRouteAuthConfig
4058
+ });
4059
+ if (authError) {
4060
+ if (authError.headers) for (const [key, value] of Object.entries(authError.headers)) c.header(key, value);
4061
+ if (authError.error) return c.json({ error: authError.error }, authError.status);
4060
4062
  }
4061
- else if (contentType?.includes("application/x-www-form-urlencoded") || contentType?.includes("multipart/form-data")) try {
4062
- bodyParams = Object.fromEntries(await pristineRequest.clone().formData());
4063
+ const permissionError = this.checkRouteRBAC(serverRoute, c.get("requestContext"));
4064
+ if (permissionError) return c.json({
4065
+ error: permissionError.error,
4066
+ message: permissionError.message
4067
+ }, permissionError.status);
4068
+ let bodyParams = {};
4069
+ if (getFGAProvider(this.mastra, c.get("requestContext"))) {
4070
+ const contentType = c.req.header("content-type");
4071
+ if (contentType?.includes("application/json")) try {
4072
+ const body = await pristineRequest.clone().json();
4073
+ if (body && typeof body === "object" && !Array.isArray(body)) bodyParams = body;
4074
+ } catch {
4075
+ bodyParams = {};
4076
+ }
4077
+ else if (contentType?.includes("application/x-www-form-urlencoded") || contentType?.includes("multipart/form-data")) try {
4078
+ bodyParams = Object.fromEntries(await pristineRequest.clone().formData());
4079
+ } catch {
4080
+ bodyParams = {};
4081
+ }
4082
+ }
4083
+ const fgaError = await checkRouteFGA(this.mastra, serverRoute, c.get("requestContext"), {
4084
+ ...Object.fromEntries(new URL(c.req.url).searchParams.entries()),
4085
+ ...bodyParams,
4086
+ ...match ? match.params : c.req.param()
4087
+ });
4088
+ if (fgaError) return c.json({
4089
+ error: fgaError.error,
4090
+ message: fgaError.message
4091
+ }, fgaError.status);
4092
+ const reqHeaders = {};
4093
+ c.req.raw.headers.forEach((v, k) => {
4094
+ reqHeaders[k] = v;
4095
+ });
4096
+ let executionCtx;
4097
+ try {
4098
+ executionCtx = c.executionCtx;
4063
4099
  } catch {
4064
- bodyParams = {};
4100
+ executionCtx = void 0;
4065
4101
  }
4102
+ const originalUntouched = originalRequest.body !== null && !originalRequest.bodyUsed && !originalRequest.body.locked;
4103
+ let requestBody;
4104
+ if (!hasPristine) requestBody = originalRequest.body;
4105
+ else if (originalUntouched) {
4106
+ requestBody = originalRequest.body;
4107
+ releasePristineBody = false;
4108
+ releaseUnreadBody(pristineRequest.body);
4109
+ } else {
4110
+ requestBody = pristineRequest.body;
4111
+ releasePristineBody = false;
4112
+ }
4113
+ const response = await this.handleCustomRouteRequest(c.req.url, c.req.method, reqHeaders, requestBody, c.get("requestContext"), c.req.raw.signal, executionCtx);
4114
+ if (!response) return c.json({ error: "Not Found" }, 404);
4115
+ return response;
4116
+ } finally {
4117
+ if (releasePristineBody) releaseUnreadBody(pristineRequest.body);
4066
4118
  }
4067
- const fgaError = await checkRouteFGA(this.mastra, serverRoute, c.get("requestContext"), {
4068
- ...Object.fromEntries(new URL(c.req.url).searchParams.entries()),
4069
- ...bodyParams,
4070
- ...match ? match.params : c.req.param()
4071
- });
4072
- if (fgaError) return c.json({
4073
- error: fgaError.error,
4074
- message: fgaError.message
4075
- }, fgaError.status);
4076
- const reqHeaders = {};
4077
- c.req.raw.headers.forEach((v, k) => {
4078
- reqHeaders[k] = v;
4079
- });
4080
- let executionCtx;
4081
- try {
4082
- executionCtx = c.executionCtx;
4083
- } catch {
4084
- executionCtx = void 0;
4085
- }
4086
- const response = await this.handleCustomRouteRequest(c.req.url, c.req.method, reqHeaders, pristineRequest.body, c.get("requestContext"), c.req.raw.signal, executionCtx);
4087
- if (!response) return c.json({ error: "Not Found" }, 404);
4088
- return response;
4089
4119
  };
4090
4120
  const method = route.method.toLowerCase();
4091
4121
  this.app[method](route.path, routeHandler);
@@ -4846,6 +4876,103 @@ const getStudioPath = () => {
4846
4876
  }
4847
4877
  return process.env.MASTRA_STUDIO_PATH || join(__dirname, "studio");
4848
4878
  };
4879
+ const STUDIO_STATIC_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
4880
+ ".js",
4881
+ ".mjs",
4882
+ ".cjs",
4883
+ ".css",
4884
+ ".map",
4885
+ ".json",
4886
+ ".txt",
4887
+ ".xml",
4888
+ ".webmanifest",
4889
+ ".svg",
4890
+ ".png",
4891
+ ".jpg",
4892
+ ".jpeg",
4893
+ ".gif",
4894
+ ".webp",
4895
+ ".avif",
4896
+ ".ico",
4897
+ ".bmp",
4898
+ ".woff",
4899
+ ".woff2",
4900
+ ".ttf",
4901
+ ".otf",
4902
+ ".eot",
4903
+ ".wasm",
4904
+ ".mp4",
4905
+ ".webm",
4906
+ ".mp3",
4907
+ ".wav",
4908
+ ".pdf",
4909
+ ".zip",
4910
+ ".csv",
4911
+ ".tsv",
4912
+ ".dat",
4913
+ ".yml",
4914
+ ".yaml",
4915
+ ".toml",
4916
+ ".ini",
4917
+ ".log",
4918
+ ".md"
4919
+ ]);
4920
+ /**
4921
+ * Classify a path that is already known to be inside the enabled Studio mount as
4922
+ * a static-file request. `studioRelativePath` is the request path with the
4923
+ * configured Studio base removed (root mounting passes the original path).
4924
+ *
4925
+ * A request is static when it lives where Studio only ever serves files from —
4926
+ * `/assets/…` (Vite's hashed chunks), a top-level hidden asset folder such as
4927
+ * `/.well-known/…`, or a top-level non-`.html` file — when its last segment ends
4928
+ * in an extension the build serves files with, or when it maps to a real file in
4929
+ * the build. A *missing* file in any of those locations must still 404 rather
4930
+ * than silently become a successful HTML response, which is what the pre-fix
4931
+ * server did for every dotted path.
4932
+ *
4933
+ * Everything else is a client-side route and reaches the injected Studio HTML
4934
+ * fallback, so `/agents/lead.agent` and `/workflows/billing.v2/graph` work on a
4935
+ * hard load, as does any route that merely *contains* a dotted segment. The
4936
+ * decision never looks at the directories the build ships: a route may sit in a
4937
+ * directory whose name the build also uses, so `/agents/lead.agent` keeps working
4938
+ * even when a real `agents/` directory is part of the Studio build.
4939
+ *
4940
+ * Trade-off (maintainer decision, 2026-11-29, #30296): with no file behind it, a
4941
+ * suffixed last segment cannot be told apart from a missing asset. The decision
4942
+ * keeps the file: a route whose *last* segment names a file type is treated as a
4943
+ * missing file, so `/agents/release.json` and `/agents/report.csv` 404 by design.
4944
+ *
4945
+ * The Studio root is normalised to an absolute path before any lookup:
4946
+ * `getStudioPath()` can return a relative value (e.g. `MASTRA_STUDIO_PATH=studio`)
4947
+ * or one with a trailing separator, and the containment check has to compare like
4948
+ * with like or every lookup misses and real nested files fall through to the
4949
+ * HTML shell.
4950
+ */
4951
+ const isStudioStaticFileRequest = async (studioRelativePath) => {
4952
+ if (studioRelativePath.endsWith(".html")) return false;
4953
+ if (studioRelativePath.startsWith("/assets/")) return true;
4954
+ if (studioRelativePath.startsWith("/.")) return true;
4955
+ const withoutLeadingSlash = studioRelativePath.slice(1);
4956
+ const segments = withoutLeadingSlash.split("/");
4957
+ if (segments.length === 1 && withoutLeadingSlash.includes(".")) return true;
4958
+ const lastSegment = [...segments].reverse().find((segment) => segment.length > 0) ?? "";
4959
+ const extensionIndex = lastSegment.lastIndexOf(".");
4960
+ if (extensionIndex > 0 && extensionIndex < lastSegment.length - 1 && STUDIO_STATIC_FILE_EXTENSIONS.has(lastSegment.slice(extensionIndex).toLowerCase())) return true;
4961
+ const root = resolve(getStudioPath());
4962
+ const candidates = [studioRelativePath];
4963
+ try {
4964
+ const decoded = decodeURIComponent(studioRelativePath);
4965
+ if (decoded !== studioRelativePath) candidates.push(decoded);
4966
+ } catch {}
4967
+ for (const candidate of candidates) {
4968
+ const resolved = resolve(root, `.${candidate}`);
4969
+ if (!resolved.startsWith(`${root}${sep}`)) continue;
4970
+ try {
4971
+ if ((await stat(resolved)).isFile()) return true;
4972
+ } catch {}
4973
+ }
4974
+ return false;
4975
+ };
4849
4976
  function isSchemaApiRoute(route) {
4850
4977
  return "_mastraSchemaRoute" in route && route._mastraSchemaRoute === true;
4851
4978
  }
@@ -4884,6 +5011,39 @@ function getRouteCorsConfig(apiRoutes, pathname, method) {
4884
5011
  const route = findMatchingCustomRoute(pathname, method, apiRoutes)?.route;
4885
5012
  return route && !isSchemaApiRoute(route) ? route.cors : void 0;
4886
5013
  }
5014
+ const splitOnUnquoted = (headerValue, delimiter) => {
5015
+ const parts = [];
5016
+ let currentPart = "";
5017
+ let quoted = false;
5018
+ for (let index = 0; index < headerValue.length; index += 1) {
5019
+ const character = headerValue.charAt(index);
5020
+ if (quoted && character === "\\") {
5021
+ currentPart += character + headerValue.charAt(index + 1);
5022
+ index += 1;
5023
+ continue;
5024
+ }
5025
+ if (character === "\"") quoted = !quoted;
5026
+ else if (character === delimiter && !quoted) {
5027
+ parts.push(currentPart);
5028
+ currentPart = "";
5029
+ continue;
5030
+ }
5031
+ currentPart += character;
5032
+ }
5033
+ parts.push(currentPart);
5034
+ return parts;
5035
+ };
5036
+ function explicitlyAcceptsJson(acceptHeader) {
5037
+ if (!acceptHeader) return false;
5038
+ return splitOnUnquoted(acceptHeader, ",").some((mediaRange) => {
5039
+ const [mediaType, ...parameters] = splitOnUnquoted(mediaRange, ";");
5040
+ if (mediaType?.trim().toLowerCase() !== "application/json") return false;
5041
+ const quality = parameters.map((parameter) => parameter.trim().toLowerCase()).find((parameter) => parameter.startsWith("q="));
5042
+ if (quality === void 0) return true;
5043
+ const qualityValue = Number.parseFloat(quality.slice(2));
5044
+ return Number.isNaN(qualityValue) || qualityValue > 0;
5045
+ });
5046
+ }
4887
5047
  function getToolExports(tools) {
4888
5048
  try {
4889
5049
  return tools.reduce((acc, toolModule) => {
@@ -5066,9 +5226,13 @@ async function createHonoServer(mastra, options = { tools: {} }) {
5066
5226
  app.get("*", async (c, next) => {
5067
5227
  const requestPath = c.req.path;
5068
5228
  if (requestPath === apiPrefix || requestPath.startsWith(`${apiPrefix}/`) || requestPath.startsWith("/swagger-ui") || requestPath.startsWith("/openapi.json")) return await next();
5069
- if (requestPath.includes(".") && !requestPath.endsWith(".html")) return await next();
5229
+ if ((requestPath === "/web" || requestPath.startsWith("/web/")) && explicitlyAcceptsJson(c.req.header("Accept"))) return await next();
5070
5230
  const isStudioRoute = studioBasePath === "" || requestPath === studioBasePath || requestPath.startsWith(`${studioBasePath}/`);
5071
- if (options?.studio && isStudioRoute) {
5231
+ const servesStudio = Boolean(options?.studio && isStudioRoute);
5232
+ if (servesStudio) {
5233
+ if (await isStudioStaticFileRequest(requestPath.slice(studioBasePath.length))) return await next();
5234
+ } else if (requestPath.includes(".") && !requestPath.endsWith(".html")) return await next();
5235
+ if (servesStudio) {
5072
5236
  const studioPath = getStudioPath();
5073
5237
  let indexHtml = await readFile(join(studioPath, "index.html"), "utf-8");
5074
5238
  const port = serverOptions?.port ?? (Number(process.env.PORT) || 4111);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/deployer",
3
- "version": "1.87.0-alpha.1",
3
+ "version": "1.87.0-alpha.11",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [
@@ -114,7 +114,7 @@
114
114
  "tinyglobby": "^0.2.17",
115
115
  "ws": "^8.23.0",
116
116
  "yaml": "^2.9.1",
117
- "@mastra/server": "1.87.0-alpha.1"
117
+ "@mastra/server": "1.87.0-alpha.11"
118
118
  },
119
119
  "devDependencies": {
120
120
  "@hono/node-server": "^2.1.3",
@@ -139,10 +139,10 @@
139
139
  "@internal/find-workspaces": "0.0.7",
140
140
  "@internal/lint": "0.0.152",
141
141
  "@internal/types-builder": "0.0.127",
142
- "@mastra/agent-browser": "0.7.0",
143
- "@mastra/core": "1.87.0-alpha.1",
144
- "@mastra/hono": "1.7.29-alpha.1",
145
- "@mastra/mcp": "^2.11.0"
142
+ "@mastra/agent-browser": "0.7.1-alpha.0",
143
+ "@mastra/core": "1.87.0-alpha.11",
144
+ "@mastra/hono": "1.7.29-alpha.11",
145
+ "@mastra/mcp": "^2.11.1-alpha.1"
146
146
  },
147
147
  "peerDependencies": {
148
148
  "@mastra/core": ">=1.85.1-0 <2.0.0-0"