@mastra/fastify 1.3.2 → 1.3.3-alpha.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # @mastra/fastify
2
2
 
3
+ ## 1.3.3-alpha.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Added error handling for datastream-response stream processing. The read loop now catches reader.read() rejections and logs them with context instead of silently terminating the response. Also added a listener on the response stream for socket-level write errors (backpressure, connection resets), which cancels the reader gracefully. ([#14862](https://github.com/mastra-ai/mastra/pull/14862))
8
+
9
+ - Updated dependencies [[`cbeec24`](https://github.com/mastra-ai/mastra/commit/cbeec24b3c97a1a296e7e461e66cc7f7d215dc50), [`cee146b`](https://github.com/mastra-ai/mastra/commit/cee146b5d858212e1df2b2730fc36d3ceda0e08d), [`aa0aeff`](https://github.com/mastra-ai/mastra/commit/aa0aeffa11efbef5e219fbd97bf43d263cfe3afe), [`2bcec65`](https://github.com/mastra-ai/mastra/commit/2bcec652d62b07eab15e9eb9822f70184526eede), [`ad9bded`](https://github.com/mastra-ai/mastra/commit/ad9bdedf86a824801f49928a8d40f6e31ff5450f), [`cbeec24`](https://github.com/mastra-ai/mastra/commit/cbeec24b3c97a1a296e7e461e66cc7f7d215dc50), [`208c0bb`](https://github.com/mastra-ai/mastra/commit/208c0bbacbf5a1da6318f2a0e0c544390e542ddc), [`f566ee7`](https://github.com/mastra-ai/mastra/commit/f566ee7d53a3da33a01103e2a5ac2070ddefe6b0)]:
10
+ - @mastra/core@1.20.0-alpha.0
11
+ - @mastra/server@1.20.0-alpha.0
12
+
3
13
  ## 1.3.2
4
14
 
5
15
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -496,13 +496,25 @@ var MastraServer = class extends serverAdapter.MastraServer {
496
496
  reply.status(fetchResponse.status);
497
497
  if (fetchResponse.body) {
498
498
  const reader = fetchResponse.body.getReader();
499
+ const onResError = (err) => {
500
+ this.mastra.getLogger()?.error("Error writing datastream response", {
501
+ error: err instanceof Error ? { message: err.message, stack: err.stack } : err
502
+ });
503
+ void reader.cancel("response write error");
504
+ };
505
+ reply.raw.once("error", onResError);
499
506
  try {
500
507
  while (true) {
501
508
  const { done, value } = await reader.read();
502
509
  if (done) break;
503
510
  reply.raw.write(value);
504
511
  }
512
+ } catch (error) {
513
+ this.mastra.getLogger()?.error("Error in datastream processing", {
514
+ error: error instanceof Error ? { message: error.message, stack: error.stack } : error
515
+ });
505
516
  } finally {
517
+ reply.raw.off("error", onResError);
506
518
  reply.raw.end();
507
519
  }
508
520
  } else {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../src/auth-middleware.ts","../src/index.ts"],"names":["initializer","_a","issue","error","issues","RequestContext","coreAuthMiddleware","toWebRequest","MastraServerBase","redactStreamChunk","normalizeQueryParams","busboy","Busboy","config","duration"],"mappings":";;;;;;;;AAGC;AAC+B,SAAS,YAAA,CAAa,IAAA,EAAMA,YAAAA,EAAa,MAAA,EAAQ;AAC7E,EAAA,SAAS,IAAA,CAAK,MAAM,GAAA,EAAK;AACrB,IAAA,IAAI,CAAC,KAAK,IAAA,EAAM;AACZ,MAAA,MAAA,CAAO,cAAA,CAAe,MAAM,MAAA,EAAQ;AAAA,QAChC,KAAA,EAAO;AAAA,UACH,GAAA;AAAA,UACA,MAAA,EAAQ,CAAA;AAAA,UACR,MAAA,sBAAY,GAAA;AAAI,SACpB;AAAA,QACA,UAAA,EAAY;AAAA,OACf,CAAA;AAAA,IACL;AACA,IAAA,IAAI,IAAA,CAAK,IAAA,CAAK,MAAA,C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AAAA,YACjB;AAAA,UACF,CAAC,CAAA;AACD,UAAA,OAAA,CAAQ,OAAA,GAAU,OAAA;AAAA,QACpB;AAEA,QAAA,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA,CAAE,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA,EAAIA,SAAQ,CAAA,EAAA,CAAA,EAAM,OAAO,CAAA;AAAA,MACzE,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware } from '@mastra/server/auth';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface FastifyAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: FastifyAuthMiddlewareOptions): preHandlerHookHandler {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n request.requestContext ??= new RequestContext();\n request.mastra ??= mastra;\n\n const path = String(request.url.split('?')[0] || '/');\n const method = String(request.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(request.customRouteAuthConfig ?? []);\n customRouteAuthConfig.set(`${method}:${path}`, true);\n\n const authHeader = request.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n const query = request.query as Record<string, string>;\n if (!token && query.apiKey) {\n token = query.apiKey || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: request.requestContext,\n rawRequest: toWebRequest(request),\n token,\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (result.action === 'error') {\n return reply.status(result.status).send(result.body);\n }\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n normalizeQueryParams,\n redactStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { FastifyInstance, FastifyReply, FastifyRequest, preHandlerHookHandler, RouteHandlerMethod } from 'fastify';\nimport { ZodError } from 'zod';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { FastifyAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Fastify request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\n// Extend Fastify types to include Mastra context\ndeclare module 'fastify' {\n interface FastifyRequest {\n mastra: Mastra;\n requestContext: RequestContext;\n tools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n}\n\nexport class MastraServer extends MastraServerBase<FastifyInstance, FastifyRequest, FastifyReply> {\n createContextMiddleware(): preHandlerHookHandler {\n return async (request: FastifyRequest, _reply: FastifyReply) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (request.method === 'POST' || request.method === 'PUT') {\n const contentType = request.headers['content-type'];\n if (contentType?.includes('application/json') && request.body) {\n const body = request.body as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (request.method === 'GET') {\n try {\n const query = request.query as Record<string, string>;\n const encodedRequestContext = query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n\n // Set context in request object\n request.requestContext = requestContext;\n request.mastra = this.mastra;\n request.tools = this.tools || {};\n if (this.taskStore) {\n request.taskStore = this.taskStore;\n }\n request.customRouteAuthConfig = this.customRouteAuthConfig;\n\n // Create abort controller for request cancellation\n const controller = new AbortController();\n request.raw.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!request.raw.complete) {\n controller.abort();\n }\n });\n request.abortSignal = controller.signal;\n };\n }\n\n async stream(route: ServerRoute, reply: FastifyReply, result: { fullStream: ReadableStream }): Promise<void> {\n // Capture headers set by plugins (e.g., @fastify/cors) BEFORE hijacking\n // reply.hijack() bypasses Fastify's response handling, so we need to preserve\n // any headers that were set by hooks/plugins and manually include them\n const rawHeaders = reply.getHeaders();\n // Filter out undefined values and conflicting headers (content-length, transfer-encoding)\n // Having both Content-Length and Transfer-Encoding: chunked violates RFC 7230\n const existingHeaders: Record<string, string | number | string[]> = {};\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value === undefined) continue;\n const lowerKey = key.toLowerCase();\n if (lowerKey === 'content-length' || lowerKey === 'transfer-encoding') continue;\n existingHeaders[key] = value;\n }\n\n // Hijack the reply to take control of the response\n // This is required when writing directly to reply.raw\n reply.hijack();\n\n const streamFormat = route.streamFormat || 'stream';\n\n // Write headers directly to the raw response, merging existing headers (like CORS)\n // with our stream-specific headers\n const sseHeaders =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n reply.raw.writeHead(200, {\n ...existingHeaders,\n ...sseHeaders,\n 'Transfer-Encoding': 'chunked',\n });\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n reply.raw.on('close', () => {\n void reader.cancel('request aborted');\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n if (streamFormat === 'sse') {\n reply.raw.write(`data: ${JSON.stringify(outputValue)}\\n\\n`);\n } else {\n reply.raw.write(JSON.stringify(outputValue) + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n reply.raw.end();\n }\n }\n\n async getParams(route: ServerRoute, request: FastifyRequest): Promise<ParsedRequestParams> {\n const urlParams = (request.params || {}) as Record<string, string>;\n // Fastify's request.query can contain string | string[] for repeated params\n const queryParams = normalizeQueryParams((request.query || {}) as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors, let others fall through to validation\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Fastify request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: FastifyRequest, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n });\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n });\n\n file.on('end', () => {\n if (!limitExceeded) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n // Pipe the raw request to busboy\n request.raw.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n reply: FastifyReply,\n result: unknown,\n request?: FastifyRequest,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n if (route.responseType === 'json') {\n await reply.send(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, reply, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Fastify response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => reply.header(key, value));\n reply.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n reply.raw.write(value);\n }\n } finally {\n reply.raw.end();\n }\n } else {\n reply.raw.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: rawReq,\n res: reply.raw,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n }),\n );\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw for SSE\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: rawReq,\n res: reply.raw,\n });\n // Response handled by startSSE\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(JSON.stringify({ error: 'Error handling MCP SSE request' }));\n }\n }\n } else {\n reply.status(500);\n }\n }\n\n async registerRoute(\n app: FastifyInstance,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const fullPath = `${prefix}${route.path}`;\n\n // Convert Express-style :param to Fastify-style :param (they're the same, but ensure consistency)\n const fastifyPath = fullPath;\n\n // Define the route handler\n const handler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const params = await this.getParams(route, request);\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: request.requestContext,\n mastra: this.mastra,\n tools: request.tools,\n taskStore: request.taskStore,\n abortSignal: request.abortSignal,\n routePrefix: prefix,\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);\n\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, reply, result, request, prefix);\n } catch (error) {\n this.mastra.getLogger()?.error('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n // Check if it's an HTTPException or MastraError with a status code\n let status = 500;\n if (error && typeof error === 'object') {\n // Check for direct status property (HTTPException)\n if ('status' in error) {\n status = (error as any).status;\n }\n // Check for MastraError with status in details\n else if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'status' in error.details\n ) {\n status = (error.details as any).status;\n }\n }\n await reply.status(status).send({ error: error instanceof Error ? error.message : 'Unknown error' });\n }\n };\n\n // Add body limit if configured\n const shouldApplyBodyLimit = this.bodyLimitOptions && ['POST', 'PUT', 'PATCH'].includes(route.method.toUpperCase());\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n\n const config = shouldApplyBodyLimit && maxSize ? { bodyLimit: maxSize } : undefined;\n\n // Handle ALL method by registering for each HTTP method\n // Fastify doesn't support 'ALL' method natively like Express\n if (route.method.toUpperCase() === 'ALL') {\n // Only register the main HTTP methods that MCP actually uses\n // Skip HEAD/OPTIONS to avoid potential conflicts with Fastify's auto-generated routes\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n try {\n app.route({\n method,\n url: fastifyPath,\n handler,\n config,\n });\n } catch (err) {\n // Skip duplicate route errors - can happen if route is registered multiple times\n if (err instanceof Error && err.message.includes('already declared')) {\n continue;\n }\n throw err;\n }\n }\n } else {\n app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: fastifyPath,\n handler,\n config,\n });\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n if (!(await this.buildCustomRouteHandler())) return;\n\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n\n for (const route of routes) {\n // Create pseudo ServerRoute for auth checking\n const serverRoute: ServerRoute = {\n method: route.method as any,\n path: route.path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: route.requiresAuth,\n };\n\n const fastifyHandler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Per-route auth check (same pattern as registerRoute)\n const authError = await this.checkRouteAuth(serverRoute, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n let hasPermission: ((userPerms: string[], required: string) => boolean) | undefined;\n try {\n ({ hasPermission } = await import('@mastra/core/auth/ee'));\n } catch {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n }\n\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `http://${request.headers.host}${request.url}`,\n request.method,\n request.headers as Record<string, string | string[] | undefined>,\n request.body,\n request.requestContext,\n );\n if (!response) {\n reply.status(404).send({ error: 'Not Found' });\n return;\n }\n reply.hijack();\n await this.writeCustomRouteResponse(response, reply.raw);\n };\n\n if (route.method === 'ALL') {\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n this.app.route({ method, url: route.path, handler: fastifyHandler });\n }\n } else {\n this.app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: route.path,\n handler: fastifyHandler,\n });\n }\n }\n }\n\n registerContextMiddleware(): void {\n // Override the default JSON parser to allow empty bodies\n // This matches Express behavior where empty POST requests with Content-Type: application/json are allowed\n this.app.removeContentTypeParser('application/json');\n this.app.addContentTypeParser('application/json', { parseAs: 'string' }, (_request, body, done) => {\n try {\n // Allow empty body\n if (!body || (typeof body === 'string' && body.trim() === '')) {\n done(null, undefined);\n return;\n }\n const parsed = JSON.parse(body as string);\n done(null, parsed);\n } catch (err) {\n done(err as Error, undefined);\n }\n });\n\n // Register content type parser for multipart/form-data\n // This allows Fastify to accept multipart requests without parsing them\n // We'll parse them manually in getParams using busboy\n this.app.addContentTypeParser('multipart/form-data', (_request, _payload, done) => {\n // Don't parse the body, we'll handle it manually with busboy\n done(null, undefined);\n });\n\n this.app.addHook('preHandler', this.createContextMiddleware());\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {\n const urlPath = request.url.split('?')[0]!;\n if (!this.shouldLogRequest(urlPath)) {\n return;\n }\n\n const start = Date.now();\n const method = request.method;\n const path = urlPath;\n\n reply.raw.once('finish', () => {\n const duration = Date.now() - start;\n const status = reply.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = request.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...request.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach((h: string) => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../src/auth-middleware.ts","../src/index.ts"],"names":["initializer","_a","issue","error","issues","RequestContext","coreAuthMiddleware","toWebRequest","MastraServerBase","redactStreamChunk","normalizeQueryParams","busboy","Busboy","config","duration"],"mappings":";;;;;;;;AAGC;AAC+B,SAAS,YAAA,CAAa,IAAA,EAAMA,YAAAA,EAAa,MAAA,EAAQ;AAC7E,EAAA,SAAS,IAAA,CAAK,MAAM,GAAA,EAAK;AACrB,IAAA,IAAI,CAAC,KAAK,IAAA,EAAM;AACZ,MAAA,MAAA,CAAO,cAAA,CAAe,MAAM,MAAA,EAAQ;AAAA,QAChC,KAAA,EAAO;AAAA,UACH,GAAA;AAAA,UACA,MAAA,EAAQ,CAAA;AAAA,UACR,MAAA,sBAAY,GAAA;AAAI,SACpB;AAAA,QACA,UAAA,EAAY;AAAA,OACf,CAAA;AAAA,IACL;AACA,IAAA,IAAI,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA,EAAG;AAC5B,MAAA;AAAA,IACJ;AACA,IAAA,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA;AACzB,IAAAA,YAAAA,CAAY,MAAM,GAAG,CAAA;AAErB,IAAA,MAAM,QAAQ,CAAA,CAAE,SAAA;AAChB,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA;AAC9B,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AAClC,MAAA,MAAM,CAAA,GAAI,KAAK,CAAC,CAAA;AAChB,MAAA,IAAI,EAAE,KAAK,IAAA,CAAA,EAAO;AACd,QAAA,IAAA,CAAK,CAAC,CAAA,GAAI,KAAA,CAAM,CAAC,CAAA,CAAE,KAAK,IAAI,CAAA;AAAA,MAChC;AAAA,IACJ;AAAA,EACJ;AAE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AAM,EAAE,WAAA,EAAY;AAC1B,YAAA,IAAI,OAAA,CAAQ,GAAG,CAAA,KAAM,MAAA,EAAW;AAC9B,cAAA,OAAA,CAAQ,GAAG,CAAA,GAAI,YAAA;AAAA,YACjB;AAAA,UACF,CAAC,CAAA;AACD,UAAA,OAAA,CAAQ,OAAA,GAAU,OAAA;AAAA,QACpB;AAEA,QAAA,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA,CAAE,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA,EAAIA,SAAQ,CAAA,EAAA,CAAA,EAAM,OAAO,CAAA;AAAA,MACzE,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware } from '@mastra/server/auth';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface FastifyAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: FastifyAuthMiddlewareOptions): preHandlerHookHandler {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n request.requestContext ??= new RequestContext();\n request.mastra ??= mastra;\n\n const path = String(request.url.split('?')[0] || '/');\n const method = String(request.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(request.customRouteAuthConfig ?? []);\n customRouteAuthConfig.set(`${method}:${path}`, true);\n\n const authHeader = request.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n const query = request.query as Record<string, string>;\n if (!token && query.apiKey) {\n token = query.apiKey || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: request.requestContext,\n rawRequest: toWebRequest(request),\n token,\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (result.action === 'error') {\n return reply.status(result.status).send(result.body);\n }\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n normalizeQueryParams,\n redactStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { FastifyInstance, FastifyReply, FastifyRequest, preHandlerHookHandler, RouteHandlerMethod } from 'fastify';\nimport { ZodError } from 'zod';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { FastifyAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Fastify request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\n// Extend Fastify types to include Mastra context\ndeclare module 'fastify' {\n interface FastifyRequest {\n mastra: Mastra;\n requestContext: RequestContext;\n tools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n}\n\nexport class MastraServer extends MastraServerBase<FastifyInstance, FastifyRequest, FastifyReply> {\n createContextMiddleware(): preHandlerHookHandler {\n return async (request: FastifyRequest, _reply: FastifyReply) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (request.method === 'POST' || request.method === 'PUT') {\n const contentType = request.headers['content-type'];\n if (contentType?.includes('application/json') && request.body) {\n const body = request.body as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (request.method === 'GET') {\n try {\n const query = request.query as Record<string, string>;\n const encodedRequestContext = query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n\n // Set context in request object\n request.requestContext = requestContext;\n request.mastra = this.mastra;\n request.tools = this.tools || {};\n if (this.taskStore) {\n request.taskStore = this.taskStore;\n }\n request.customRouteAuthConfig = this.customRouteAuthConfig;\n\n // Create abort controller for request cancellation\n const controller = new AbortController();\n request.raw.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!request.raw.complete) {\n controller.abort();\n }\n });\n request.abortSignal = controller.signal;\n };\n }\n\n async stream(route: ServerRoute, reply: FastifyReply, result: { fullStream: ReadableStream }): Promise<void> {\n // Capture headers set by plugins (e.g., @fastify/cors) BEFORE hijacking\n // reply.hijack() bypasses Fastify's response handling, so we need to preserve\n // any headers that were set by hooks/plugins and manually include them\n const rawHeaders = reply.getHeaders();\n // Filter out undefined values and conflicting headers (content-length, transfer-encoding)\n // Having both Content-Length and Transfer-Encoding: chunked violates RFC 7230\n const existingHeaders: Record<string, string | number | string[]> = {};\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value === undefined) continue;\n const lowerKey = key.toLowerCase();\n if (lowerKey === 'content-length' || lowerKey === 'transfer-encoding') continue;\n existingHeaders[key] = value;\n }\n\n // Hijack the reply to take control of the response\n // This is required when writing directly to reply.raw\n reply.hijack();\n\n const streamFormat = route.streamFormat || 'stream';\n\n // Write headers directly to the raw response, merging existing headers (like CORS)\n // with our stream-specific headers\n const sseHeaders =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n reply.raw.writeHead(200, {\n ...existingHeaders,\n ...sseHeaders,\n 'Transfer-Encoding': 'chunked',\n });\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n reply.raw.on('close', () => {\n void reader.cancel('request aborted');\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n if (streamFormat === 'sse') {\n reply.raw.write(`data: ${JSON.stringify(outputValue)}\\n\\n`);\n } else {\n reply.raw.write(JSON.stringify(outputValue) + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n reply.raw.end();\n }\n }\n\n async getParams(route: ServerRoute, request: FastifyRequest): Promise<ParsedRequestParams> {\n const urlParams = (request.params || {}) as Record<string, string>;\n // Fastify's request.query can contain string | string[] for repeated params\n const queryParams = normalizeQueryParams((request.query || {}) as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors, let others fall through to validation\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Fastify request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: FastifyRequest, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n });\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n });\n\n file.on('end', () => {\n if (!limitExceeded) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n // Pipe the raw request to busboy\n request.raw.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n reply: FastifyReply,\n result: unknown,\n request?: FastifyRequest,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n if (route.responseType === 'json') {\n await reply.send(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, reply, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Fastify response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => reply.header(key, value));\n reply.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n\n const onResError = (err: unknown) => {\n this.mastra.getLogger()?.error('Error writing datastream response', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n void reader.cancel('response write error');\n };\n reply.raw.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n reply.raw.write(value);\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in datastream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n reply.raw.off('error', onResError);\n reply.raw.end();\n }\n } else {\n reply.raw.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: rawReq,\n res: reply.raw,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n }),\n );\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw for SSE\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: rawReq,\n res: reply.raw,\n });\n // Response handled by startSSE\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(JSON.stringify({ error: 'Error handling MCP SSE request' }));\n }\n }\n } else {\n reply.status(500);\n }\n }\n\n async registerRoute(\n app: FastifyInstance,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const fullPath = `${prefix}${route.path}`;\n\n // Convert Express-style :param to Fastify-style :param (they're the same, but ensure consistency)\n const fastifyPath = fullPath;\n\n // Define the route handler\n const handler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const params = await this.getParams(route, request);\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: request.requestContext,\n mastra: this.mastra,\n tools: request.tools,\n taskStore: request.taskStore,\n abortSignal: request.abortSignal,\n routePrefix: prefix,\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);\n\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, reply, result, request, prefix);\n } catch (error) {\n this.mastra.getLogger()?.error('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n // Check if it's an HTTPException or MastraError with a status code\n let status = 500;\n if (error && typeof error === 'object') {\n // Check for direct status property (HTTPException)\n if ('status' in error) {\n status = (error as any).status;\n }\n // Check for MastraError with status in details\n else if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'status' in error.details\n ) {\n status = (error.details as any).status;\n }\n }\n await reply.status(status).send({ error: error instanceof Error ? error.message : 'Unknown error' });\n }\n };\n\n // Add body limit if configured\n const shouldApplyBodyLimit = this.bodyLimitOptions && ['POST', 'PUT', 'PATCH'].includes(route.method.toUpperCase());\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n\n const config = shouldApplyBodyLimit && maxSize ? { bodyLimit: maxSize } : undefined;\n\n // Handle ALL method by registering for each HTTP method\n // Fastify doesn't support 'ALL' method natively like Express\n if (route.method.toUpperCase() === 'ALL') {\n // Only register the main HTTP methods that MCP actually uses\n // Skip HEAD/OPTIONS to avoid potential conflicts with Fastify's auto-generated routes\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n try {\n app.route({\n method,\n url: fastifyPath,\n handler,\n config,\n });\n } catch (err) {\n // Skip duplicate route errors - can happen if route is registered multiple times\n if (err instanceof Error && err.message.includes('already declared')) {\n continue;\n }\n throw err;\n }\n }\n } else {\n app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: fastifyPath,\n handler,\n config,\n });\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n if (!(await this.buildCustomRouteHandler())) return;\n\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n\n for (const route of routes) {\n // Create pseudo ServerRoute for auth checking\n const serverRoute: ServerRoute = {\n method: route.method as any,\n path: route.path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: route.requiresAuth,\n };\n\n const fastifyHandler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Per-route auth check (same pattern as registerRoute)\n const authError = await this.checkRouteAuth(serverRoute, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n let hasPermission: ((userPerms: string[], required: string) => boolean) | undefined;\n try {\n ({ hasPermission } = await import('@mastra/core/auth/ee'));\n } catch {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n }\n\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `http://${request.headers.host}${request.url}`,\n request.method,\n request.headers as Record<string, string | string[] | undefined>,\n request.body,\n request.requestContext,\n );\n if (!response) {\n reply.status(404).send({ error: 'Not Found' });\n return;\n }\n reply.hijack();\n await this.writeCustomRouteResponse(response, reply.raw);\n };\n\n if (route.method === 'ALL') {\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n this.app.route({ method, url: route.path, handler: fastifyHandler });\n }\n } else {\n this.app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: route.path,\n handler: fastifyHandler,\n });\n }\n }\n }\n\n registerContextMiddleware(): void {\n // Override the default JSON parser to allow empty bodies\n // This matches Express behavior where empty POST requests with Content-Type: application/json are allowed\n this.app.removeContentTypeParser('application/json');\n this.app.addContentTypeParser('application/json', { parseAs: 'string' }, (_request, body, done) => {\n try {\n // Allow empty body\n if (!body || (typeof body === 'string' && body.trim() === '')) {\n done(null, undefined);\n return;\n }\n const parsed = JSON.parse(body as string);\n done(null, parsed);\n } catch (err) {\n done(err as Error, undefined);\n }\n });\n\n // Register content type parser for multipart/form-data\n // This allows Fastify to accept multipart requests without parsing them\n // We'll parse them manually in getParams using busboy\n this.app.addContentTypeParser('multipart/form-data', (_request, _payload, done) => {\n // Don't parse the body, we'll handle it manually with busboy\n done(null, undefined);\n });\n\n this.app.addHook('preHandler', this.createContextMiddleware());\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {\n const urlPath = request.url.split('?')[0]!;\n if (!this.shouldLogRequest(urlPath)) {\n return;\n }\n\n const start = Date.now();\n const method = request.method;\n const path = urlPath;\n\n reply.raw.once('finish', () => {\n const duration = Date.now() - start;\n const status = reply.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = request.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...request.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach((h: string) => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAElE,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EACL,YAAY,IAAI,gBAAgB,EAGjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,cAAc,EAAE,qBAAqB,EAAsB,MAAM,SAAS,CAAC;AAExH,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,YAAY,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AA4CtE,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAU,cAAc;QACtB,MAAM,EAAE,MAAM,CAAC;QACf,cAAc,EAAE,cAAc,CAAC;QAC/B,KAAK,EAAE,UAAU,CAAC;QAClB,WAAW,EAAE,WAAW,CAAC;QACzB,SAAS,EAAE,iBAAiB,CAAC;QAC7B,qBAAqB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KAC9C;CACF;AAED,qBAAa,YAAa,SAAQ,gBAAgB,CAAC,eAAe,EAAE,cAAc,EAAE,YAAY,CAAC;IAC/F,uBAAuB,IAAI,qBAAqB;IAgE1C,MAAM,CAAC,KAAK,EAAE,WAA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IAAI,IAAI;IA6BjC,sBAAsB,IAAI,IAAI;IAK9B,6BAA6B,IAAI,IAAI;CA+CtC"}
package/dist/index.js CHANGED
@@ -494,13 +494,25 @@ var MastraServer = class extends MastraServer$1 {
494
494
  reply.status(fetchResponse.status);
495
495
  if (fetchResponse.body) {
496
496
  const reader = fetchResponse.body.getReader();
497
+ const onResError = (err) => {
498
+ this.mastra.getLogger()?.error("Error writing datastream response", {
499
+ error: err instanceof Error ? { message: err.message, stack: err.stack } : err
500
+ });
501
+ void reader.cancel("response write error");
502
+ };
503
+ reply.raw.once("error", onResError);
497
504
  try {
498
505
  while (true) {
499
506
  const { done, value } = await reader.read();
500
507
  if (done) break;
501
508
  reply.raw.write(value);
502
509
  }
510
+ } catch (error) {
511
+ this.mastra.getLogger()?.error("Error in datastream processing", {
512
+ error: error instanceof Error ? { message: error.message, stack: error.stack } : error
513
+ });
503
514
  } finally {
515
+ reply.raw.off("error", onResError);
504
516
  reply.raw.end();
505
517
  }
506
518
  } else {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../src/auth-middleware.ts","../src/index.ts"],"names":["initializer","_a","issue","error","issues","toWebRequest","MastraServerBase","config","duration"],"mappings":";;;;;;AAGC;AAC+B,SAAS,YAAA,CAAa,IAAA,EAAMA,YAAAA,EAAa,MAAA,EAAQ;AAC7E,EAAA,SAAS,IAAA,CAAK,MAAM,GAAA,EAAK;AACrB,IAAA,IAAI,CAAC,KAAK,IAAA,EAAM;AACZ,MAAA,MAAA,CAAO,cAAA,CAAe,MAAM,MAAA,EAAQ;AAAA,QACh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AQ,CAAC,CAAA,KAAc;AACnC,YAAA,MAAM,GAAA,GAAM,EAAE,WAAA,EAAY;AAC1B,YAAA,IAAI,OAAA,CAAQ,GAAG,CAAA,KAAM,MAAA,EAAW;AAC9B,cAAA,OAAA,CAAQ,GAAG,CAAA,GAAI,YAAA;AAAA,YACjB;AAAA,UACF,CAAC,CAAA;AACD,UAAA,OAAA,CAAQ,OAAA,GAAU,OAAA;AAAA,QACpB;AAEA,QAAA,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA,CAAE,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA,EAAIA,SAAQ,CAAA,EAAA,CAAA,EAAM,OAAO,CAAA;AAAA,MACzE,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware } from '@mastra/server/auth';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface FastifyAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: FastifyAuthMiddlewareOptions): preHandlerHookHandler {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n request.requestContext ??= new RequestContext();\n request.mastra ??= mastra;\n\n const path = String(request.url.split('?')[0] || '/');\n const method = String(request.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(request.customRouteAuthConfig ?? []);\n customRouteAuthConfig.set(`${method}:${path}`, true);\n\n const authHeader = request.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n const query = request.query as Record<string, string>;\n if (!token && query.apiKey) {\n token = query.apiKey || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: request.requestContext,\n rawRequest: toWebRequest(request),\n token,\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (result.action === 'error') {\n return reply.status(result.status).send(result.body);\n }\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n normalizeQueryParams,\n redactStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { FastifyInstance, FastifyReply, FastifyRequest, preHandlerHookHandler, RouteHandlerMethod } from 'fastify';\nimport { ZodError } from 'zod';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { FastifyAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Fastify request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\n// Extend Fastify types to include Mastra context\ndeclare module 'fastify' {\n interface FastifyRequest {\n mastra: Mastra;\n requestContext: RequestContext;\n tools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n}\n\nexport class MastraServer extends MastraServerBase<FastifyInstance, FastifyRequest, FastifyReply> {\n createContextMiddleware(): preHandlerHookHandler {\n return async (request: FastifyRequest, _reply: FastifyReply) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (request.method === 'POST' || request.method === 'PUT') {\n const contentType = request.headers['content-type'];\n if (contentType?.includes('application/json') && request.body) {\n const body = request.body as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (request.method === 'GET') {\n try {\n const query = request.query as Record<string, string>;\n const encodedRequestContext = query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n\n // Set context in request object\n request.requestContext = requestContext;\n request.mastra = this.mastra;\n request.tools = this.tools || {};\n if (this.taskStore) {\n request.taskStore = this.taskStore;\n }\n request.customRouteAuthConfig = this.customRouteAuthConfig;\n\n // Create abort controller for request cancellation\n const controller = new AbortController();\n request.raw.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!request.raw.complete) {\n controller.abort();\n }\n });\n request.abortSignal = controller.signal;\n };\n }\n\n async stream(route: ServerRoute, reply: FastifyReply, result: { fullStream: ReadableStream }): Promise<void> {\n // Capture headers set by plugins (e.g., @fastify/cors) BEFORE hijacking\n // reply.hijack() bypasses Fastify's response handling, so we need to preserve\n // any headers that were set by hooks/plugins and manually include them\n const rawHeaders = reply.getHeaders();\n // Filter out undefined values and conflicting headers (content-length, transfer-encoding)\n // Having both Content-Length and Transfer-Encoding: chunked violates RFC 7230\n const existingHeaders: Record<string, string | number | string[]> = {};\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value === undefined) continue;\n const lowerKey = key.toLowerCase();\n if (lowerKey === 'content-length' || lowerKey === 'transfer-encoding') continue;\n existingHeaders[key] = value;\n }\n\n // Hijack the reply to take control of the response\n // This is required when writing directly to reply.raw\n reply.hijack();\n\n const streamFormat = route.streamFormat || 'stream';\n\n // Write headers directly to the raw response, merging existing headers (like CORS)\n // with our stream-specific headers\n const sseHeaders =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n reply.raw.writeHead(200, {\n ...existingHeaders,\n ...sseHeaders,\n 'Transfer-Encoding': 'chunked',\n });\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n reply.raw.on('close', () => {\n void reader.cancel('request aborted');\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n if (streamFormat === 'sse') {\n reply.raw.write(`data: ${JSON.stringify(outputValue)}\\n\\n`);\n } else {\n reply.raw.write(JSON.stringify(outputValue) + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n reply.raw.end();\n }\n }\n\n async getParams(route: ServerRoute, request: FastifyRequest): Promise<ParsedRequestParams> {\n const urlParams = (request.params || {}) as Record<string, string>;\n // Fastify's request.query can contain string | string[] for repeated params\n const queryParams = normalizeQueryParams((request.query || {}) as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors, let others fall through to validation\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Fastify request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: FastifyRequest, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n });\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n });\n\n file.on('end', () => {\n if (!limitExceeded) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n // Pipe the raw request to busboy\n request.raw.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n reply: FastifyReply,\n result: unknown,\n request?: FastifyRequest,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n if (route.responseType === 'json') {\n await reply.send(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, reply, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Fastify response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => reply.header(key, value));\n reply.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n reply.raw.write(value);\n }\n } finally {\n reply.raw.end();\n }\n } else {\n reply.raw.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: rawReq,\n res: reply.raw,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n }),\n );\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw for SSE\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: rawReq,\n res: reply.raw,\n });\n // Response handled by startSSE\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(JSON.stringify({ error: 'Error handling MCP SSE request' }));\n }\n }\n } else {\n reply.status(500);\n }\n }\n\n async registerRoute(\n app: FastifyInstance,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const fullPath = `${prefix}${route.path}`;\n\n // Convert Express-style :param to Fastify-style :param (they're the same, but ensure consistency)\n const fastifyPath = fullPath;\n\n // Define the route handler\n const handler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const params = await this.getParams(route, request);\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: request.requestContext,\n mastra: this.mastra,\n tools: request.tools,\n taskStore: request.taskStore,\n abortSignal: request.abortSignal,\n routePrefix: prefix,\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);\n\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, reply, result, request, prefix);\n } catch (error) {\n this.mastra.getLogger()?.error('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n // Check if it's an HTTPException or MastraError with a status code\n let status = 500;\n if (error && typeof error === 'object') {\n // Check for direct status property (HTTPException)\n if ('status' in error) {\n status = (error as any).status;\n }\n // Check for MastraError with status in details\n else if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'status' in error.details\n ) {\n status = (error.details as any).status;\n }\n }\n await reply.status(status).send({ error: error instanceof Error ? error.message : 'Unknown error' });\n }\n };\n\n // Add body limit if configured\n const shouldApplyBodyLimit = this.bodyLimitOptions && ['POST', 'PUT', 'PATCH'].includes(route.method.toUpperCase());\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n\n const config = shouldApplyBodyLimit && maxSize ? { bodyLimit: maxSize } : undefined;\n\n // Handle ALL method by registering for each HTTP method\n // Fastify doesn't support 'ALL' method natively like Express\n if (route.method.toUpperCase() === 'ALL') {\n // Only register the main HTTP methods that MCP actually uses\n // Skip HEAD/OPTIONS to avoid potential conflicts with Fastify's auto-generated routes\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n try {\n app.route({\n method,\n url: fastifyPath,\n handler,\n config,\n });\n } catch (err) {\n // Skip duplicate route errors - can happen if route is registered multiple times\n if (err instanceof Error && err.message.includes('already declared')) {\n continue;\n }\n throw err;\n }\n }\n } else {\n app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: fastifyPath,\n handler,\n config,\n });\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n if (!(await this.buildCustomRouteHandler())) return;\n\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n\n for (const route of routes) {\n // Create pseudo ServerRoute for auth checking\n const serverRoute: ServerRoute = {\n method: route.method as any,\n path: route.path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: route.requiresAuth,\n };\n\n const fastifyHandler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Per-route auth check (same pattern as registerRoute)\n const authError = await this.checkRouteAuth(serverRoute, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n let hasPermission: ((userPerms: string[], required: string) => boolean) | undefined;\n try {\n ({ hasPermission } = await import('@mastra/core/auth/ee'));\n } catch {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n }\n\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `http://${request.headers.host}${request.url}`,\n request.method,\n request.headers as Record<string, string | string[] | undefined>,\n request.body,\n request.requestContext,\n );\n if (!response) {\n reply.status(404).send({ error: 'Not Found' });\n return;\n }\n reply.hijack();\n await this.writeCustomRouteResponse(response, reply.raw);\n };\n\n if (route.method === 'ALL') {\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n this.app.route({ method, url: route.path, handler: fastifyHandler });\n }\n } else {\n this.app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: route.path,\n handler: fastifyHandler,\n });\n }\n }\n }\n\n registerContextMiddleware(): void {\n // Override the default JSON parser to allow empty bodies\n // This matches Express behavior where empty POST requests with Content-Type: application/json are allowed\n this.app.removeContentTypeParser('application/json');\n this.app.addContentTypeParser('application/json', { parseAs: 'string' }, (_request, body, done) => {\n try {\n // Allow empty body\n if (!body || (typeof body === 'string' && body.trim() === '')) {\n done(null, undefined);\n return;\n }\n const parsed = JSON.parse(body as string);\n done(null, parsed);\n } catch (err) {\n done(err as Error, undefined);\n }\n });\n\n // Register content type parser for multipart/form-data\n // This allows Fastify to accept multipart requests without parsing them\n // We'll parse them manually in getParams using busboy\n this.app.addContentTypeParser('multipart/form-data', (_request, _payload, done) => {\n // Don't parse the body, we'll handle it manually with busboy\n done(null, undefined);\n });\n\n this.app.addHook('preHandler', this.createContextMiddleware());\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {\n const urlPath = request.url.split('?')[0]!;\n if (!this.shouldLogRequest(urlPath)) {\n return;\n }\n\n const start = Date.now();\n const method = request.method;\n const path = urlPath;\n\n reply.raw.once('finish', () => {\n const duration = Date.now() - start;\n const status = reply.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = request.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...request.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach((h: string) => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/errors.js","../src/auth-middleware.ts","../src/index.ts"],"names":["initializer","_a","issue","error","issues","toWebRequest","MastraServerBase","config","duration"],"mappings":";;;;;;AAGC;AAC+B,SAAS,YAAA,CAAa,IAAA,EAAMA,YAAAA,EAAa,MAAA,EAAQ;AAC7E,EAAA,SAAS,IAAA,CAAK,MAAM,GAAA,EAAK;AACrB,IAAA,IAAI,CAAC,KAAK,IAAA,EAAM;AACZ,MAAA,MAAA,CAAO,cAAA,CAAe,MAAM,MAAA,EAAQ;AAAA,QAChC,KAAA,EAAO;AAAA,UACH,GAAA;AAAA,UACA,MAAA,EAAQ,CAAA;AAAA,UACR,MAAA,sBAAY,GAAA;AAAI,SACpB;AAAA,QACA,UAAA,EAAY;AAAA,OACf,CAAA;AAAA,IACL;AACA,IAAA,IAAI,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA,EAAG;AAC5B,MAAA;AAAA,IACJ;AACA,IAAA,IAAA,CAAK,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,IAAI,CAAA;AACzB,IAAAA,YAAAA,CAAY,MAAM,GAAG,CAAA;AAErB,IAAA,MAAM,QAAQ,CAAA,CAAE,SAAA;AAChB,IAAA,MAAM,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA;AAC9B,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AAClC,MAAA,MAAM,CAAA,GAAI,KAAK,CAAC,CAAA;AAChB,MAAA,IAAI,EAAE,KAAK,IAAA,CAAA,EAAO;AACd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AAkB,aAAA,IAAiB,EAAC;AAC/D,UAAA,aAAA,CAAc,OAAA,CAAQ,CAAC,CAAA,KAAc;AACnC,YAAA,MAAM,GAAA,GAAM,EAAE,WAAA,EAAY;AAC1B,YAAA,IAAI,OAAA,CAAQ,GAAG,CAAA,KAAM,MAAA,EAAW;AAC9B,cAAA,OAAA,CAAQ,GAAG,CAAA,GAAI,YAAA;AAAA,YACjB;AAAA,UACF,CAAC,CAAA;AACD,UAAA,OAAA,CAAQ,OAAA,GAAU,OAAA;AAAA,QACpB;AAEA,QAAA,IAAA,CAAK,MAAA,CAAO,KAAK,CAAA,CAAE,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA,EAAIA,SAAQ,CAAA,EAAA,CAAA,EAAM,OAAO,CAAA;AAAA,MACzE,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/** A special constant with type `never` */\nexport const NEVER = Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\nexport const globalConfig = {};\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepString = step.toString();\n let stepDecCount = (stepString.split(\".\")[1] || \"\").length;\n if (stepDecCount === 0 && /\\d?e-\\d?/.test(stepString)) {\n const match = stepString.match(/\\d?e-(\\d?)/);\n if (match?.[1]) {\n stepDecCount = Number.parseInt(match[1]);\n }\n }\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nconst EVALUATING = Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = cached(() => {\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = new Set([\"string\", \"number\", \"bigint\", \"boolean\", \"symbol\", \"undefined\"]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: [], // delete existing checks\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const full = { ...iss, path: iss.path ?? [] };\n // for backwards compatibility\n if (!iss.message) {\n const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\";\n full.message = message;\n }\n // delete (full as any).def;\n delete full.inst;\n delete full.continue;\n if (!ctx?.reportInput) {\n delete full.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues });\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues });\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, issue.path));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, issue.path);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { coreAuthMiddleware } from '@mastra/server/auth';\nimport type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify';\n\nexport interface FastifyAuthMiddlewareOptions {\n mastra: Mastra;\n requiresAuth?: boolean;\n}\n\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (!value) continue;\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\nexport function createAuthMiddleware({\n mastra,\n requiresAuth = true,\n}: FastifyAuthMiddlewareOptions): preHandlerHookHandler {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n if (!requiresAuth) {\n return;\n }\n\n const authConfig = mastra.getServer()?.auth;\n if (!authConfig) {\n return;\n }\n\n request.requestContext ??= new RequestContext();\n request.mastra ??= mastra;\n\n const path = String(request.url.split('?')[0] || '/');\n const method = String(request.method || 'GET');\n const customRouteAuthConfig = new Map<string, boolean>(request.customRouteAuthConfig ?? []);\n customRouteAuthConfig.set(`${method}:${path}`, true);\n\n const authHeader = request.headers.authorization;\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n const query = request.query as Record<string, string>;\n if (!token && query.apiKey) {\n token = query.apiKey || null;\n }\n\n const result = await coreAuthMiddleware({\n path,\n method,\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext: request.requestContext,\n rawRequest: toWebRequest(request),\n token,\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (result.action === 'error') {\n return reply.status(result.status).send(result.body);\n }\n };\n}\n","import { Busboy } from '@fastify/busboy';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { InMemoryTaskStore } from '@mastra/server/a2a/store';\nimport type { MCPHttpTransportResult, MCPSseTransportResult } from '@mastra/server/handlers/mcp';\nimport type { ParsedRequestParams, ServerRoute } from '@mastra/server/server-adapter';\nimport {\n MastraServer as MastraServerBase,\n normalizeQueryParams,\n redactStreamChunk,\n} from '@mastra/server/server-adapter';\nimport type { FastifyInstance, FastifyReply, FastifyRequest, preHandlerHookHandler, RouteHandlerMethod } from 'fastify';\nimport { ZodError } from 'zod';\nexport { createAuthMiddleware } from './auth-middleware';\nexport type { FastifyAuthMiddlewareOptions } from './auth-middleware';\n\ntype HasPermissionFn = (userPerms: string[], required: string) => boolean;\nlet _hasPermissionPromise: Promise<HasPermissionFn | undefined> | undefined;\nfunction loadHasPermission(): Promise<HasPermissionFn | undefined> {\n if (!_hasPermissionPromise) {\n _hasPermissionPromise = import('@mastra/core/auth/ee')\n .then(m => m.hasPermission)\n .catch(() => {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n return undefined;\n });\n }\n return _hasPermissionPromise;\n}\n\n/**\n * Convert Fastify request to Web API Request for cookie-based auth providers.\n */\nfunction toWebRequest(request: FastifyRequest): globalThis.Request {\n const protocol = request.protocol || 'http';\n const host = request.headers.host || 'localhost';\n const url = `${protocol}://${host}${request.url}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(request.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n value.forEach(v => headers.append(key, v));\n } else {\n headers.set(key, value);\n }\n }\n }\n\n return new globalThis.Request(url, {\n method: request.method,\n headers,\n });\n}\n\n// Extend Fastify types to include Mastra context\ndeclare module 'fastify' {\n interface FastifyRequest {\n mastra: Mastra;\n requestContext: RequestContext;\n tools: ToolsInput;\n abortSignal: AbortSignal;\n taskStore: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n }\n}\n\nexport class MastraServer extends MastraServerBase<FastifyInstance, FastifyRequest, FastifyReply> {\n createContextMiddleware(): preHandlerHookHandler {\n return async (request: FastifyRequest, _reply: FastifyReply) => {\n // Parse request context from request body and add to context\n let bodyRequestContext: Record<string, any> | undefined;\n let paramsRequestContext: Record<string, any> | undefined;\n\n // Parse request context from request body (POST/PUT)\n if (request.method === 'POST' || request.method === 'PUT') {\n const contentType = request.headers['content-type'];\n if (contentType?.includes('application/json') && request.body) {\n const body = request.body as { requestContext?: Record<string, any> };\n if (body.requestContext) {\n bodyRequestContext = body.requestContext;\n }\n }\n }\n\n // Parse request context from query params (GET)\n if (request.method === 'GET') {\n try {\n const query = request.query as Record<string, string>;\n const encodedRequestContext = query.requestContext;\n if (typeof encodedRequestContext === 'string') {\n // Try JSON first\n try {\n paramsRequestContext = JSON.parse(encodedRequestContext);\n } catch {\n // Fallback to base64(JSON)\n try {\n const json = Buffer.from(encodedRequestContext, 'base64').toString('utf-8');\n paramsRequestContext = JSON.parse(json);\n } catch {\n // ignore if still invalid\n }\n }\n }\n } catch {\n // ignore query parsing errors\n }\n }\n\n const requestContext = this.mergeRequestContext({ paramsRequestContext, bodyRequestContext });\n\n // Set context in request object\n request.requestContext = requestContext;\n request.mastra = this.mastra;\n request.tools = this.tools || {};\n if (this.taskStore) {\n request.taskStore = this.taskStore;\n }\n request.customRouteAuthConfig = this.customRouteAuthConfig;\n\n // Create abort controller for request cancellation\n const controller = new AbortController();\n request.raw.on('close', () => {\n // Only abort if the response wasn't successfully completed\n if (!request.raw.complete) {\n controller.abort();\n }\n });\n request.abortSignal = controller.signal;\n };\n }\n\n async stream(route: ServerRoute, reply: FastifyReply, result: { fullStream: ReadableStream }): Promise<void> {\n // Capture headers set by plugins (e.g., @fastify/cors) BEFORE hijacking\n // reply.hijack() bypasses Fastify's response handling, so we need to preserve\n // any headers that were set by hooks/plugins and manually include them\n const rawHeaders = reply.getHeaders();\n // Filter out undefined values and conflicting headers (content-length, transfer-encoding)\n // Having both Content-Length and Transfer-Encoding: chunked violates RFC 7230\n const existingHeaders: Record<string, string | number | string[]> = {};\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value === undefined) continue;\n const lowerKey = key.toLowerCase();\n if (lowerKey === 'content-length' || lowerKey === 'transfer-encoding') continue;\n existingHeaders[key] = value;\n }\n\n // Hijack the reply to take control of the response\n // This is required when writing directly to reply.raw\n reply.hijack();\n\n const streamFormat = route.streamFormat || 'stream';\n\n // Write headers directly to the raw response, merging existing headers (like CORS)\n // with our stream-specific headers\n const sseHeaders =\n streamFormat === 'sse'\n ? {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no',\n }\n : {\n 'Content-Type': 'text/plain',\n };\n\n reply.raw.writeHead(200, {\n ...existingHeaders,\n ...sseHeaders,\n 'Transfer-Encoding': 'chunked',\n });\n\n const readableStream = result instanceof ReadableStream ? result : result.fullStream;\n const reader = readableStream.getReader();\n\n reply.raw.on('close', () => {\n void reader.cancel('request aborted');\n });\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n if (value) {\n // Optionally redact sensitive data (system prompts, tool definitions, API keys) before sending to the client\n const shouldRedact = this.streamOptions?.redact ?? true;\n const outputValue = shouldRedact ? redactStreamChunk(value) : value;\n if (streamFormat === 'sse') {\n reply.raw.write(`data: ${JSON.stringify(outputValue)}\\n\\n`);\n } else {\n reply.raw.write(JSON.stringify(outputValue) + '\\x1E');\n }\n }\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in stream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n reply.raw.end();\n }\n }\n\n async getParams(route: ServerRoute, request: FastifyRequest): Promise<ParsedRequestParams> {\n const urlParams = (request.params || {}) as Record<string, string>;\n // Fastify's request.query can contain string | string[] for repeated params\n const queryParams = normalizeQueryParams((request.query || {}) as Record<string, unknown>);\n let body: unknown;\n let bodyParseError: { message: string } | undefined;\n\n if (route.method === 'POST' || route.method === 'PUT' || route.method === 'PATCH' || route.method === 'DELETE') {\n const contentType = request.headers['content-type'] || '';\n\n if (contentType.includes('multipart/form-data')) {\n try {\n const maxFileSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n body = await this.parseMultipartFormData(request, maxFileSize);\n } catch (error) {\n this.mastra.getLogger()?.error('Failed to parse multipart form data', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n // Re-throw size limit errors, let others fall through to validation\n if (error instanceof Error && error.message.toLowerCase().includes('size')) {\n throw error;\n }\n bodyParseError = {\n message: error instanceof Error ? error.message : 'Failed to parse multipart form data',\n };\n }\n } else {\n body = request.body;\n }\n }\n\n return { urlParams, queryParams, body, bodyParseError };\n }\n\n /**\n * Parse multipart/form-data using @fastify/busboy.\n * Converts file uploads to Buffers and parses JSON field values.\n *\n * @param request - The Fastify request object\n * @param maxFileSize - Optional maximum file size in bytes\n */\n private parseMultipartFormData(request: FastifyRequest, maxFileSize?: number): Promise<Record<string, unknown>> {\n return new Promise((resolve, reject) => {\n const result: Record<string, unknown> = {};\n\n const busboy = new Busboy({\n headers: {\n 'content-type': request.headers['content-type'] as string,\n },\n limits: maxFileSize ? { fileSize: maxFileSize } : undefined,\n });\n\n busboy.on('file', (fieldname: string, file: NodeJS.ReadableStream) => {\n const chunks: Buffer[] = [];\n let limitExceeded = false;\n\n file.on('data', (chunk: Buffer) => {\n chunks.push(chunk);\n });\n\n file.on('limit', () => {\n limitExceeded = true;\n reject(new Error(`File size limit exceeded${maxFileSize ? ` (max: ${maxFileSize} bytes)` : ''}`));\n });\n\n file.on('end', () => {\n if (!limitExceeded) {\n result[fieldname] = Buffer.concat(chunks);\n }\n });\n });\n\n busboy.on('field', (fieldname: string, value: string) => {\n // Try to parse JSON strings (like 'options')\n try {\n result[fieldname] = JSON.parse(value);\n } catch {\n result[fieldname] = value;\n }\n });\n\n busboy.on('finish', () => {\n resolve(result);\n });\n\n busboy.on('error', (error: Error) => {\n reject(error);\n });\n\n // Pipe the raw request to busboy\n request.raw.pipe(busboy);\n });\n }\n\n async sendResponse(\n route: ServerRoute,\n reply: FastifyReply,\n result: unknown,\n request?: FastifyRequest,\n prefix?: string,\n ): Promise<void> {\n const resolvedPrefix = prefix ?? this.prefix ?? '';\n\n if (route.responseType === 'json') {\n await reply.send(result);\n } else if (route.responseType === 'stream') {\n await this.stream(route, reply, result as { fullStream: ReadableStream });\n } else if (route.responseType === 'datastream-response') {\n // Handle AI SDK Response objects - pipe Response.body to Fastify response\n const fetchResponse = result as globalThis.Response;\n fetchResponse.headers.forEach((value, key) => reply.header(key, value));\n reply.status(fetchResponse.status);\n if (fetchResponse.body) {\n const reader = fetchResponse.body.getReader();\n\n const onResError = (err: unknown) => {\n this.mastra.getLogger()?.error('Error writing datastream response', {\n error: err instanceof Error ? { message: err.message, stack: err.stack } : err,\n });\n void reader.cancel('response write error');\n };\n reply.raw.once('error', onResError);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n reply.raw.write(value);\n }\n } catch (error) {\n this.mastra.getLogger()?.error('Error in datastream processing', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n } finally {\n reply.raw.off('error', onResError);\n reply.raw.end();\n }\n } else {\n reply.raw.end();\n }\n } else if (route.responseType === 'mcp-http') {\n // MCP Streamable HTTP transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, httpPath, mcpOptions: routeMcpOptions } = result as MCPHttpTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n // Merge class-level mcpOptions with route-specific options (route takes precedence)\n const options = { ...this.mcpOptions, ...routeMcpOptions };\n\n await server.startHTTP({\n url: new URL(request.url, `http://${request.headers.host}`),\n httpPath: `${resolvedPrefix}${httpPath}`,\n req: rawReq,\n res: reply.raw,\n options: Object.keys(options).length > 0 ? options : undefined,\n });\n // Response handled by startHTTP\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n }),\n );\n }\n }\n } else if (route.responseType === 'mcp-sse') {\n // MCP SSE transport - request is required\n if (!request) {\n await reply.status(500).send({ error: 'Request object required for MCP transport' });\n return;\n }\n\n const { server, ssePath, messagePath } = result as MCPSseTransportResult;\n\n try {\n // Hijack the response to bypass Fastify's response handling\n // This is required when we write directly to reply.raw for SSE\n reply.hijack();\n\n // Attach parsed body to raw request so MCP server's readJsonBody can use it\n // Fastify consumes the body stream, so we need to provide the pre-parsed body\n const rawReq = request.raw as typeof request.raw & { body?: unknown };\n if (request.body !== undefined) {\n rawReq.body = request.body;\n }\n\n await server.startSSE({\n url: new URL(request.url, `http://${request.headers.host}`),\n ssePath: `${resolvedPrefix}${ssePath}`,\n messagePath: `${resolvedPrefix}${messagePath}`,\n req: rawReq,\n res: reply.raw,\n });\n // Response handled by startSSE\n } catch {\n if (!reply.raw.headersSent) {\n reply.raw.writeHead(500, { 'Content-Type': 'application/json' });\n reply.raw.end(JSON.stringify({ error: 'Error handling MCP SSE request' }));\n }\n }\n } else {\n reply.status(500);\n }\n }\n\n async registerRoute(\n app: FastifyInstance,\n route: ServerRoute,\n { prefix: prefixParam }: { prefix?: string } = {},\n ): Promise<void> {\n // Default prefix to this.prefix if not provided, or empty string\n const prefix = prefixParam ?? this.prefix ?? '';\n\n const fullPath = `${prefix}${route.path}`;\n\n // Convert Express-style :param to Fastify-style :param (they're the same, but ensure consistency)\n const fastifyPath = fullPath;\n\n // Define the route handler\n const handler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Check route-level authentication/authorization\n const authError = await this.checkRouteAuth(route, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const params = await this.getParams(route, request);\n\n // Return 400 Bad Request if body parsing failed (e.g., malformed multipart data)\n if (params.bodyParseError) {\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'body', message: params.bodyParseError.message }],\n });\n }\n\n if (params.queryParams) {\n try {\n params.queryParams = await this.parseQueryParams(route, params.queryParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing query params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'query');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid query parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n if (params.body) {\n try {\n params.body = await this.parseBody(route, params.body);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing body', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'body');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid request body',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n // Parse path params through pathParamSchema for type coercion (e.g., z.coerce.number())\n if (params.urlParams) {\n try {\n params.urlParams = await this.parsePathParams(route, params.urlParams);\n } catch (error) {\n this.mastra.getLogger()?.error('Error parsing path params', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n });\n if (error instanceof ZodError) {\n const { status, body } = this.resolveValidationError(route, error, 'path');\n return reply.status(status).send(body);\n }\n return reply.status(400).send({\n error: 'Invalid path parameters',\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n });\n }\n }\n\n const handlerParams = {\n ...params.urlParams,\n ...params.queryParams,\n ...(typeof params.body === 'object' ? params.body : {}),\n requestContext: request.requestContext,\n mastra: this.mastra,\n tools: request.tools,\n taskStore: request.taskStore,\n abortSignal: request.abortSignal,\n routePrefix: prefix,\n };\n\n // Check route permission requirement (EE feature)\n // Uses convention-based permission derivation: permissions are auto-derived\n // from route path/method unless explicitly set or route is public\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n const hasPermission = await loadHasPermission();\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(route, userPermissions, hasPermission);\n\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n try {\n const result = await route.handler(handlerParams);\n await this.sendResponse(route, reply, result, request, prefix);\n } catch (error) {\n this.mastra.getLogger()?.error('Error calling handler', {\n error: error instanceof Error ? { message: error.message, stack: error.stack } : error,\n path: route.path,\n method: route.method,\n });\n // Check if it's an HTTPException or MastraError with a status code\n let status = 500;\n if (error && typeof error === 'object') {\n // Check for direct status property (HTTPException)\n if ('status' in error) {\n status = (error as any).status;\n }\n // Check for MastraError with status in details\n else if (\n 'details' in error &&\n error.details &&\n typeof error.details === 'object' &&\n 'status' in error.details\n ) {\n status = (error.details as any).status;\n }\n }\n await reply.status(status).send({ error: error instanceof Error ? error.message : 'Unknown error' });\n }\n };\n\n // Add body limit if configured\n const shouldApplyBodyLimit = this.bodyLimitOptions && ['POST', 'PUT', 'PATCH'].includes(route.method.toUpperCase());\n const maxSize = route.maxBodySize ?? this.bodyLimitOptions?.maxSize;\n\n const config = shouldApplyBodyLimit && maxSize ? { bodyLimit: maxSize } : undefined;\n\n // Handle ALL method by registering for each HTTP method\n // Fastify doesn't support 'ALL' method natively like Express\n if (route.method.toUpperCase() === 'ALL') {\n // Only register the main HTTP methods that MCP actually uses\n // Skip HEAD/OPTIONS to avoid potential conflicts with Fastify's auto-generated routes\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n try {\n app.route({\n method,\n url: fastifyPath,\n handler,\n config,\n });\n } catch (err) {\n // Skip duplicate route errors - can happen if route is registered multiple times\n if (err instanceof Error && err.message.includes('already declared')) {\n continue;\n }\n throw err;\n }\n }\n } else {\n app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: fastifyPath,\n handler,\n config,\n });\n }\n }\n\n async registerCustomApiRoutes(): Promise<void> {\n if (!(await this.buildCustomRouteHandler())) return;\n\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n\n for (const route of routes) {\n // Create pseudo ServerRoute for auth checking\n const serverRoute: ServerRoute = {\n method: route.method as any,\n path: route.path,\n responseType: 'json',\n handler: async () => {},\n requiresAuth: route.requiresAuth,\n };\n\n const fastifyHandler: RouteHandlerMethod = async (request: FastifyRequest, reply: FastifyReply) => {\n // Per-route auth check (same pattern as registerRoute)\n const authError = await this.checkRouteAuth(serverRoute, {\n path: String(request.url.split('?')[0] || '/'),\n method: String(request.method || 'GET'),\n getHeader: name => request.headers[name.toLowerCase()] as string | undefined,\n getQuery: name => (request.query as Record<string, string>)[name],\n requestContext: request.requestContext,\n request: toWebRequest(request),\n buildAuthorizeContext: () => toWebRequest(request),\n });\n\n if (authError) {\n return reply.status(authError.status).send({ error: authError.error });\n }\n\n const authConfig = this.mastra.getServer()?.auth;\n if (authConfig) {\n let hasPermission: ((userPerms: string[], required: string) => boolean) | undefined;\n try {\n ({ hasPermission } = await import('@mastra/core/auth/ee'));\n } catch {\n console.error(\n '[@mastra/fastify] Auth features require @mastra/core >= 1.6.0. Please upgrade: npm install @mastra/core@latest',\n );\n }\n\n if (hasPermission) {\n const userPermissions = request.requestContext.get('userPermissions') as string[] | undefined;\n const permissionError = this.checkRoutePermission(serverRoute, userPermissions, hasPermission);\n if (permissionError) {\n return reply.status(permissionError.status).send({\n error: permissionError.error,\n message: permissionError.message,\n });\n }\n }\n }\n\n const response = await this.handleCustomRouteRequest(\n `http://${request.headers.host}${request.url}`,\n request.method,\n request.headers as Record<string, string | string[] | undefined>,\n request.body,\n request.requestContext,\n );\n if (!response) {\n reply.status(404).send({ error: 'Not Found' });\n return;\n }\n reply.hijack();\n await this.writeCustomRouteResponse(response, reply.raw);\n };\n\n if (route.method === 'ALL') {\n const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;\n for (const method of methods) {\n this.app.route({ method, url: route.path, handler: fastifyHandler });\n }\n } else {\n this.app.route({\n method: route.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',\n url: route.path,\n handler: fastifyHandler,\n });\n }\n }\n }\n\n registerContextMiddleware(): void {\n // Override the default JSON parser to allow empty bodies\n // This matches Express behavior where empty POST requests with Content-Type: application/json are allowed\n this.app.removeContentTypeParser('application/json');\n this.app.addContentTypeParser('application/json', { parseAs: 'string' }, (_request, body, done) => {\n try {\n // Allow empty body\n if (!body || (typeof body === 'string' && body.trim() === '')) {\n done(null, undefined);\n return;\n }\n const parsed = JSON.parse(body as string);\n done(null, parsed);\n } catch (err) {\n done(err as Error, undefined);\n }\n });\n\n // Register content type parser for multipart/form-data\n // This allows Fastify to accept multipart requests without parsing them\n // We'll parse them manually in getParams using busboy\n this.app.addContentTypeParser('multipart/form-data', (_request, _payload, done) => {\n // Don't parse the body, we'll handle it manually with busboy\n done(null, undefined);\n });\n\n this.app.addHook('preHandler', this.createContextMiddleware());\n }\n\n registerAuthMiddleware(): void {\n // Auth is handled per-route in registerRoute() and registerCustomApiRoutes()\n // No global middleware needed\n }\n\n registerHttpLoggingMiddleware(): void {\n if (!this.httpLoggingConfig?.enabled) {\n return;\n }\n\n this.app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {\n const urlPath = request.url.split('?')[0]!;\n if (!this.shouldLogRequest(urlPath)) {\n return;\n }\n\n const start = Date.now();\n const method = request.method;\n const path = urlPath;\n\n reply.raw.once('finish', () => {\n const duration = Date.now() - start;\n const status = reply.statusCode;\n const level = this.httpLoggingConfig?.level || 'info';\n\n const logData: Record<string, any> = {\n method,\n path,\n status,\n duration: `${duration}ms`,\n };\n\n if (this.httpLoggingConfig?.includeQueryParams) {\n logData.query = request.query;\n }\n\n if (this.httpLoggingConfig?.includeHeaders) {\n const headers = { ...request.headers };\n const redactHeaders = this.httpLoggingConfig.redactHeaders || [];\n redactHeaders.forEach((h: string) => {\n const key = h.toLowerCase();\n if (headers[key] !== undefined) {\n headers[key] = '[REDACTED]';\n }\n });\n logData.headers = headers;\n }\n\n this.logger[level](`${method} ${path} ${status} ${duration}ms`, logData);\n });\n });\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/fastify",
3
- "version": "1.3.2",
3
+ "version": "1.3.3-alpha.0",
4
4
  "description": "Mastra Fastify adapter for the server",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -21,7 +21,7 @@
21
21
  "license": "Apache-2.0",
22
22
  "dependencies": {
23
23
  "@fastify/busboy": "^3.2.0",
24
- "@mastra/server": "1.19.0"
24
+ "@mastra/server": "1.20.0-alpha.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@ai-sdk/openai": "^2.0.99",
@@ -35,14 +35,14 @@
35
35
  "vitest": "4.0.18",
36
36
  "zod": "^4.3.6",
37
37
  "@internal/lint": "0.0.76",
38
- "@internal/server-adapter-test-utils": "0.0.9",
39
38
  "@internal/storage-test-utils": "0.0.72",
39
+ "@internal/server-adapter-test-utils": "0.0.9",
40
40
  "@internal/types-builder": "0.0.51",
41
- "@mastra/core": "1.19.0",
42
- "@mastra/evals": "1.2.0",
43
41
  "@mastra/libsql": "1.7.3",
44
- "@mastra/memory": "1.12.0",
45
- "@mastra/observability": "1.6.0"
42
+ "@mastra/evals": "1.2.0",
43
+ "@mastra/memory": "1.12.1-alpha.0",
44
+ "@mastra/observability": "1.7.0-alpha.0",
45
+ "@mastra/core": "1.20.0-alpha.0"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@mastra/core": ">=1.0.0-0 <2.0.0-0",