@mastra/deployer 0.2.5 → 0.2.6-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,33 @@
1
1
  'use strict';
2
2
 
3
+ var crypto = require('crypto');
3
4
  var promises = require('fs/promises');
4
5
  var path = require('path');
5
6
  var url = require('url');
6
7
  var http = require('http');
7
8
  var http2 = require('http2');
8
9
  var stream = require('stream');
9
- var crypto = require('crypto');
10
10
  var filepath = require('hono/utils/filepath');
11
11
  var mime = require('hono/utils/mime');
12
12
  var fs = require('fs');
13
13
  var html = require('hono/html');
14
+ var core = require('@mastra/core');
14
15
  var hono = require('hono');
15
16
  var bodyLimit = require('hono/body-limit');
16
17
  var cors = require('hono/cors');
17
18
  var logger = require('hono/logger');
18
19
  var httpException = require('hono/http-exception');
19
- var zod = require('zod');
20
+ var agents = require('@mastra/server/handlers/agents');
21
+ var logs = require('@mastra/server/handlers/logs');
22
+ var memory = require('@mastra/server/handlers/memory');
23
+ var network = require('@mastra/server/handlers/network');
20
24
  var agent = require('@mastra/core/agent');
21
- var core = require('@mastra/core');
25
+ var zod = require('zod');
26
+ var telemetry = require('@mastra/server/handlers/telemetry');
27
+ var tools = require('@mastra/server/handlers/tools');
28
+ var vector = require('@mastra/server/handlers/vector');
29
+ var voice = require('@mastra/server/handlers/voice');
30
+ var workflows = require('@mastra/server/handlers/workflows');
22
31
  var streaming = require('hono/streaming');
23
32
 
24
33
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -161,14 +170,14 @@ var newRequest = (incoming, defaultHostname) => {
161
170
  req[urlKey] = url.href;
162
171
  return req;
163
172
  };
164
- function writeFromReadableStream(stream, writable) {
165
- if (stream.locked) {
173
+ function writeFromReadableStream(stream2, writable) {
174
+ if (stream2.locked) {
166
175
  throw new TypeError("ReadableStream is locked.");
167
176
  } else if (writable.destroyed) {
168
- stream.cancel();
177
+ stream2.cancel();
169
178
  return;
170
179
  }
171
- const reader = stream.getReader();
180
+ const reader = stream2.getReader();
172
181
  writable.on("close", cancel);
173
182
  writable.on("error", cancel);
174
183
  reader.read().then(flow, cancel);
@@ -366,7 +375,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
366
375
  const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
367
376
  const internalBody = getInternalBody(res);
368
377
  if (internalBody) {
369
- const { length, source, stream } = internalBody;
378
+ const { length, source, stream: stream2 } = internalBody;
370
379
  if (source instanceof Uint8Array && source.byteLength !== length) ; else {
371
380
  if (length) {
372
381
  resHeaderRecord["content-length"] = length;
@@ -377,7 +386,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
377
386
  } else if (source instanceof Blob) {
378
387
  outgoing.end(new Uint8Array(await source.arrayBuffer()));
379
388
  } else {
380
- await writeFromReadableStream(stream, outgoing);
389
+ await writeFromReadableStream(stream2, outgoing);
381
390
  }
382
391
  return;
383
392
  }
@@ -481,18 +490,18 @@ var ENCODINGS = {
481
490
  gzip: ".gz"
482
491
  };
483
492
  var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
484
- var createStreamBody = (stream) => {
493
+ var createStreamBody = (stream2) => {
485
494
  const body = new ReadableStream({
486
495
  start(controller) {
487
- stream.on("data", (chunk) => {
496
+ stream2.on("data", (chunk) => {
488
497
  controller.enqueue(chunk);
489
498
  });
490
- stream.on("end", () => {
499
+ stream2.on("end", () => {
491
500
  controller.close();
492
501
  });
493
502
  },
494
503
  cancel() {
495
- stream.destroy();
504
+ stream2.destroy();
496
505
  }
497
506
  });
498
507
  return body;
@@ -588,10 +597,10 @@ var serveStatic = (options = { root: "" }) => {
588
597
  end = size - 1;
589
598
  }
590
599
  const chunksize = end - start + 1;
591
- const stream = fs.createReadStream(path, { start, end });
600
+ const stream2 = fs.createReadStream(path, { start, end });
592
601
  c2.header("Content-Length", chunksize.toString());
593
602
  c2.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
594
- return c2.body(createStreamBody(stream), 206);
603
+ return c2.body(createStreamBody(stream2), 206);
595
604
  };
596
605
  };
597
606
  var RENDER_TYPE = {
@@ -838,2132 +847,64 @@ async function x(e2, t2, s3 = {}) {
838
847
  }
839
848
  return { docs: o2, components: n2 };
840
849
  }
841
-
842
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/double-indexed-kv.js
843
- var DoubleIndexedKV = class {
844
- constructor() {
845
- this.keyToValue = /* @__PURE__ */ new Map();
846
- this.valueToKey = /* @__PURE__ */ new Map();
847
- }
848
- set(key, value) {
849
- this.keyToValue.set(key, value);
850
- this.valueToKey.set(value, key);
851
- }
852
- getByKey(key) {
853
- return this.keyToValue.get(key);
854
- }
855
- getByValue(value) {
856
- return this.valueToKey.get(value);
857
- }
858
- clear() {
859
- this.keyToValue.clear();
860
- this.valueToKey.clear();
861
- }
862
- };
863
-
864
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/registry.js
865
- var Registry = class {
866
- constructor(generateIdentifier) {
867
- this.generateIdentifier = generateIdentifier;
868
- this.kv = new DoubleIndexedKV();
869
- }
870
- register(value, identifier) {
871
- if (this.kv.getByValue(value)) {
872
- return;
873
- }
874
- if (!identifier) {
875
- identifier = this.generateIdentifier(value);
876
- }
877
- this.kv.set(identifier, value);
878
- }
879
- clear() {
880
- this.kv.clear();
881
- }
882
- getIdentifier(value) {
883
- return this.kv.getByValue(value);
884
- }
885
- getValue(identifier) {
886
- return this.kv.getByKey(identifier);
887
- }
888
- };
889
-
890
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/class-registry.js
891
- var ClassRegistry = class extends Registry {
892
- constructor() {
893
- super((c2) => c2.name);
894
- this.classToAllowedProps = /* @__PURE__ */ new Map();
895
- }
896
- register(value, options) {
897
- if (typeof options === "object") {
898
- if (options.allowProps) {
899
- this.classToAllowedProps.set(value, options.allowProps);
900
- }
901
- super.register(value, options.identifier);
902
- } else {
903
- super.register(value, options);
904
- }
905
- }
906
- getAllowedProps(value) {
907
- return this.classToAllowedProps.get(value);
908
- }
909
- };
910
-
911
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/util.js
912
- function valuesOfObj(record) {
913
- if ("values" in Object) {
914
- return Object.values(record);
915
- }
916
- const values = [];
917
- for (const key in record) {
918
- if (record.hasOwnProperty(key)) {
919
- values.push(record[key]);
920
- }
921
- }
922
- return values;
923
- }
924
- function find(record, predicate) {
925
- const values = valuesOfObj(record);
926
- if ("find" in values) {
927
- return values.find(predicate);
928
- }
929
- const valuesNotNever = values;
930
- for (let i2 = 0; i2 < valuesNotNever.length; i2++) {
931
- const value = valuesNotNever[i2];
932
- if (predicate(value)) {
933
- return value;
934
- }
935
- }
936
- return void 0;
937
- }
938
- function forEach(record, run) {
939
- Object.entries(record).forEach(([key, value]) => run(value, key));
940
- }
941
- function includes(arr, value) {
942
- return arr.indexOf(value) !== -1;
943
- }
944
- function findArr(record, predicate) {
945
- for (let i2 = 0; i2 < record.length; i2++) {
946
- const value = record[i2];
947
- if (predicate(value)) {
948
- return value;
949
- }
950
- }
951
- return void 0;
952
- }
953
-
954
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/custom-transformer-registry.js
955
- var CustomTransformerRegistry = class {
956
- constructor() {
957
- this.transfomers = {};
958
- }
959
- register(transformer) {
960
- this.transfomers[transformer.name] = transformer;
961
- }
962
- findApplicable(v) {
963
- return find(this.transfomers, (transformer) => transformer.isApplicable(v));
964
- }
965
- findByName(name) {
966
- return this.transfomers[name];
967
- }
968
- };
969
-
970
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/is.js
971
- var getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);
972
- var isUndefined = (payload) => typeof payload === "undefined";
973
- var isNull = (payload) => payload === null;
974
- var isPlainObject = (payload) => {
975
- if (typeof payload !== "object" || payload === null)
976
- return false;
977
- if (payload === Object.prototype)
978
- return false;
979
- if (Object.getPrototypeOf(payload) === null)
980
- return true;
981
- return Object.getPrototypeOf(payload) === Object.prototype;
982
- };
983
- var isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;
984
- var isArray = (payload) => Array.isArray(payload);
985
- var isString = (payload) => typeof payload === "string";
986
- var isNumber = (payload) => typeof payload === "number" && !isNaN(payload);
987
- var isBoolean = (payload) => typeof payload === "boolean";
988
- var isRegExp = (payload) => payload instanceof RegExp;
989
- var isMap = (payload) => payload instanceof Map;
990
- var isSet = (payload) => payload instanceof Set;
991
- var isSymbol = (payload) => getType(payload) === "Symbol";
992
- var isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());
993
- var isError = (payload) => payload instanceof Error;
994
- var isNaNValue = (payload) => typeof payload === "number" && isNaN(payload);
995
- var isPrimitive = (payload) => isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload);
996
- var isBigint = (payload) => typeof payload === "bigint";
997
- var isInfinite = (payload) => payload === Infinity || payload === -Infinity;
998
- var isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);
999
- var isURL = (payload) => payload instanceof URL;
1000
-
1001
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/pathstringifier.js
1002
- var escapeKey = (key) => key.replace(/\./g, "\\.");
1003
- var stringifyPath = (path) => path.map(String).map(escapeKey).join(".");
1004
- var parsePath = (string) => {
1005
- const result = [];
1006
- let segment = "";
1007
- for (let i2 = 0; i2 < string.length; i2++) {
1008
- let char = string.charAt(i2);
1009
- const isEscapedDot = char === "\\" && string.charAt(i2 + 1) === ".";
1010
- if (isEscapedDot) {
1011
- segment += ".";
1012
- i2++;
1013
- continue;
1014
- }
1015
- const isEndOfSegment = char === ".";
1016
- if (isEndOfSegment) {
1017
- result.push(segment);
1018
- segment = "";
1019
- continue;
1020
- }
1021
- segment += char;
1022
- }
1023
- const lastSegment = segment;
1024
- result.push(lastSegment);
1025
- return result;
1026
- };
1027
-
1028
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/transformer.js
1029
- function simpleTransformation(isApplicable, annotation, transform, untransform) {
1030
- return {
1031
- isApplicable,
1032
- annotation,
1033
- transform,
1034
- untransform
1035
- };
1036
- }
1037
- var simpleRules = [
1038
- simpleTransformation(isUndefined, "undefined", () => null, () => void 0),
1039
- simpleTransformation(isBigint, "bigint", (v) => v.toString(), (v) => {
1040
- if (typeof BigInt !== "undefined") {
1041
- return BigInt(v);
1042
- }
1043
- console.error("Please add a BigInt polyfill.");
1044
- return v;
1045
- }),
1046
- simpleTransformation(isDate, "Date", (v) => v.toISOString(), (v) => new Date(v)),
1047
- simpleTransformation(isError, "Error", (v, superJson) => {
1048
- const baseError = {
1049
- name: v.name,
1050
- message: v.message
1051
- };
1052
- superJson.allowedErrorProps.forEach((prop) => {
1053
- baseError[prop] = v[prop];
1054
- });
1055
- return baseError;
1056
- }, (v, superJson) => {
1057
- const e2 = new Error(v.message);
1058
- e2.name = v.name;
1059
- e2.stack = v.stack;
1060
- superJson.allowedErrorProps.forEach((prop) => {
1061
- e2[prop] = v[prop];
1062
- });
1063
- return e2;
1064
- }),
1065
- simpleTransformation(isRegExp, "regexp", (v) => "" + v, (regex) => {
1066
- const body = regex.slice(1, regex.lastIndexOf("/"));
1067
- const flags = regex.slice(regex.lastIndexOf("/") + 1);
1068
- return new RegExp(body, flags);
1069
- }),
1070
- simpleTransformation(
1071
- isSet,
1072
- "set",
1073
- // (sets only exist in es6+)
1074
- // eslint-disable-next-line es5/no-es6-methods
1075
- (v) => [...v.values()],
1076
- (v) => new Set(v)
1077
- ),
1078
- simpleTransformation(isMap, "map", (v) => [...v.entries()], (v) => new Map(v)),
1079
- simpleTransformation((v) => isNaNValue(v) || isInfinite(v), "number", (v) => {
1080
- if (isNaNValue(v)) {
1081
- return "NaN";
1082
- }
1083
- if (v > 0) {
1084
- return "Infinity";
1085
- } else {
1086
- return "-Infinity";
1087
- }
1088
- }, Number),
1089
- simpleTransformation((v) => v === 0 && 1 / v === -Infinity, "number", () => {
1090
- return "-0";
1091
- }, Number),
1092
- simpleTransformation(isURL, "URL", (v) => v.toString(), (v) => new URL(v))
1093
- ];
1094
- function compositeTransformation(isApplicable, annotation, transform, untransform) {
1095
- return {
1096
- isApplicable,
1097
- annotation,
1098
- transform,
1099
- untransform
1100
- };
1101
- }
1102
- var symbolRule = compositeTransformation((s3, superJson) => {
1103
- if (isSymbol(s3)) {
1104
- const isRegistered = !!superJson.symbolRegistry.getIdentifier(s3);
1105
- return isRegistered;
1106
- }
1107
- return false;
1108
- }, (s3, superJson) => {
1109
- const identifier = superJson.symbolRegistry.getIdentifier(s3);
1110
- return ["symbol", identifier];
1111
- }, (v) => v.description, (_, a2, superJson) => {
1112
- const value = superJson.symbolRegistry.getValue(a2[1]);
1113
- if (!value) {
1114
- throw new Error("Trying to deserialize unknown symbol");
1115
- }
1116
- return value;
1117
- });
1118
- var constructorToName = [
1119
- Int8Array,
1120
- Uint8Array,
1121
- Int16Array,
1122
- Uint16Array,
1123
- Int32Array,
1124
- Uint32Array,
1125
- Float32Array,
1126
- Float64Array,
1127
- Uint8ClampedArray
1128
- ].reduce((obj, ctor) => {
1129
- obj[ctor.name] = ctor;
1130
- return obj;
1131
- }, {});
1132
- var typedArrayRule = compositeTransformation(isTypedArray, (v) => ["typed-array", v.constructor.name], (v) => [...v], (v, a2) => {
1133
- const ctor = constructorToName[a2[1]];
1134
- if (!ctor) {
1135
- throw new Error("Trying to deserialize unknown typed array");
1136
- }
1137
- return new ctor(v);
1138
- });
1139
- function isInstanceOfRegisteredClass(potentialClass, superJson) {
1140
- if (potentialClass?.constructor) {
1141
- const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);
1142
- return isRegistered;
1143
- }
1144
- return false;
1145
- }
1146
- var classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {
1147
- const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);
1148
- return ["class", identifier];
1149
- }, (clazz, superJson) => {
1150
- const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);
1151
- if (!allowedProps) {
1152
- return { ...clazz };
1153
- }
1154
- const result = {};
1155
- allowedProps.forEach((prop) => {
1156
- result[prop] = clazz[prop];
1157
- });
1158
- return result;
1159
- }, (v, a2, superJson) => {
1160
- const clazz = superJson.classRegistry.getValue(a2[1]);
1161
- if (!clazz) {
1162
- throw new Error(`Trying to deserialize unknown class '${a2[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);
1163
- }
1164
- return Object.assign(Object.create(clazz.prototype), v);
1165
- });
1166
- var customRule = compositeTransformation((value, superJson) => {
1167
- return !!superJson.customTransformerRegistry.findApplicable(value);
1168
- }, (value, superJson) => {
1169
- const transformer = superJson.customTransformerRegistry.findApplicable(value);
1170
- return ["custom", transformer.name];
1171
- }, (value, superJson) => {
1172
- const transformer = superJson.customTransformerRegistry.findApplicable(value);
1173
- return transformer.serialize(value);
1174
- }, (v, a2, superJson) => {
1175
- const transformer = superJson.customTransformerRegistry.findByName(a2[1]);
1176
- if (!transformer) {
1177
- throw new Error("Trying to deserialize unknown custom value");
1178
- }
1179
- return transformer.deserialize(v);
1180
- });
1181
- var compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
1182
- var transformValue = (value, superJson) => {
1183
- const applicableCompositeRule = findArr(compositeRules, (rule) => rule.isApplicable(value, superJson));
1184
- if (applicableCompositeRule) {
1185
- return {
1186
- value: applicableCompositeRule.transform(value, superJson),
1187
- type: applicableCompositeRule.annotation(value, superJson)
1188
- };
1189
- }
1190
- const applicableSimpleRule = findArr(simpleRules, (rule) => rule.isApplicable(value, superJson));
1191
- if (applicableSimpleRule) {
1192
- return {
1193
- value: applicableSimpleRule.transform(value, superJson),
1194
- type: applicableSimpleRule.annotation
1195
- };
1196
- }
1197
- return void 0;
1198
- };
1199
- var simpleRulesByAnnotation = {};
1200
- simpleRules.forEach((rule) => {
1201
- simpleRulesByAnnotation[rule.annotation] = rule;
1202
- });
1203
- var untransformValue = (json, type, superJson) => {
1204
- if (isArray(type)) {
1205
- switch (type[0]) {
1206
- case "symbol":
1207
- return symbolRule.untransform(json, type, superJson);
1208
- case "class":
1209
- return classRule.untransform(json, type, superJson);
1210
- case "custom":
1211
- return customRule.untransform(json, type, superJson);
1212
- case "typed-array":
1213
- return typedArrayRule.untransform(json, type, superJson);
1214
- default:
1215
- throw new Error("Unknown transformation: " + type);
1216
- }
1217
- } else {
1218
- const transformation = simpleRulesByAnnotation[type];
1219
- if (!transformation) {
1220
- throw new Error("Unknown transformation: " + type);
1221
- }
1222
- return transformation.untransform(json, superJson);
1223
- }
1224
- };
1225
-
1226
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/accessDeep.js
1227
- var getNthKey = (value, n2) => {
1228
- if (n2 > value.size)
1229
- throw new Error("index out of bounds");
1230
- const keys = value.keys();
1231
- while (n2 > 0) {
1232
- keys.next();
1233
- n2--;
1234
- }
1235
- return keys.next().value;
1236
- };
1237
- function validatePath(path) {
1238
- if (includes(path, "__proto__")) {
1239
- throw new Error("__proto__ is not allowed as a property");
1240
- }
1241
- if (includes(path, "prototype")) {
1242
- throw new Error("prototype is not allowed as a property");
1243
- }
1244
- if (includes(path, "constructor")) {
1245
- throw new Error("constructor is not allowed as a property");
1246
- }
1247
- }
1248
- var getDeep = (object, path) => {
1249
- validatePath(path);
1250
- for (let i2 = 0; i2 < path.length; i2++) {
1251
- const key = path[i2];
1252
- if (isSet(object)) {
1253
- object = getNthKey(object, +key);
1254
- } else if (isMap(object)) {
1255
- const row = +key;
1256
- const type = +path[++i2] === 0 ? "key" : "value";
1257
- const keyOfRow = getNthKey(object, row);
1258
- switch (type) {
1259
- case "key":
1260
- object = keyOfRow;
1261
- break;
1262
- case "value":
1263
- object = object.get(keyOfRow);
1264
- break;
1265
- }
1266
- } else {
1267
- object = object[key];
1268
- }
1269
- }
1270
- return object;
1271
- };
1272
- var setDeep = (object, path, mapper) => {
1273
- validatePath(path);
1274
- if (path.length === 0) {
1275
- return mapper(object);
1276
- }
1277
- let parent = object;
1278
- for (let i2 = 0; i2 < path.length - 1; i2++) {
1279
- const key = path[i2];
1280
- if (isArray(parent)) {
1281
- const index = +key;
1282
- parent = parent[index];
1283
- } else if (isPlainObject(parent)) {
1284
- parent = parent[key];
1285
- } else if (isSet(parent)) {
1286
- const row = +key;
1287
- parent = getNthKey(parent, row);
1288
- } else if (isMap(parent)) {
1289
- const isEnd = i2 === path.length - 2;
1290
- if (isEnd) {
1291
- break;
1292
- }
1293
- const row = +key;
1294
- const type = +path[++i2] === 0 ? "key" : "value";
1295
- const keyOfRow = getNthKey(parent, row);
1296
- switch (type) {
1297
- case "key":
1298
- parent = keyOfRow;
1299
- break;
1300
- case "value":
1301
- parent = parent.get(keyOfRow);
1302
- break;
1303
- }
1304
- }
1305
- }
1306
- const lastKey = path[path.length - 1];
1307
- if (isArray(parent)) {
1308
- parent[+lastKey] = mapper(parent[+lastKey]);
1309
- } else if (isPlainObject(parent)) {
1310
- parent[lastKey] = mapper(parent[lastKey]);
1311
- }
1312
- if (isSet(parent)) {
1313
- const oldValue = getNthKey(parent, +lastKey);
1314
- const newValue = mapper(oldValue);
1315
- if (oldValue !== newValue) {
1316
- parent.delete(oldValue);
1317
- parent.add(newValue);
1318
- }
1319
- }
1320
- if (isMap(parent)) {
1321
- const row = +path[path.length - 2];
1322
- const keyToRow = getNthKey(parent, row);
1323
- const type = +lastKey === 0 ? "key" : "value";
1324
- switch (type) {
1325
- case "key": {
1326
- const newKey = mapper(keyToRow);
1327
- parent.set(newKey, parent.get(keyToRow));
1328
- if (newKey !== keyToRow) {
1329
- parent.delete(keyToRow);
1330
- }
1331
- break;
1332
- }
1333
- case "value": {
1334
- parent.set(keyToRow, mapper(parent.get(keyToRow)));
1335
- break;
1336
- }
1337
- }
1338
- }
1339
- return object;
1340
- };
1341
-
1342
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/plainer.js
1343
- function traverse(tree, walker2, origin = []) {
1344
- if (!tree) {
1345
- return;
1346
- }
1347
- if (!isArray(tree)) {
1348
- forEach(tree, (subtree, key) => traverse(subtree, walker2, [...origin, ...parsePath(key)]));
1349
- return;
1350
- }
1351
- const [nodeValue, children] = tree;
1352
- if (children) {
1353
- forEach(children, (child, key) => {
1354
- traverse(child, walker2, [...origin, ...parsePath(key)]);
1355
- });
1356
- }
1357
- walker2(nodeValue, origin);
1358
- }
1359
- function applyValueAnnotations(plain, annotations, superJson) {
1360
- traverse(annotations, (type, path) => {
1361
- plain = setDeep(plain, path, (v) => untransformValue(v, type, superJson));
1362
- });
1363
- return plain;
1364
- }
1365
- function applyReferentialEqualityAnnotations(plain, annotations) {
1366
- function apply(identicalPaths, path) {
1367
- const object = getDeep(plain, parsePath(path));
1368
- identicalPaths.map(parsePath).forEach((identicalObjectPath) => {
1369
- plain = setDeep(plain, identicalObjectPath, () => object);
1370
- });
1371
- }
1372
- if (isArray(annotations)) {
1373
- const [root, other] = annotations;
1374
- root.forEach((identicalPath) => {
1375
- plain = setDeep(plain, parsePath(identicalPath), () => plain);
1376
- });
1377
- if (other) {
1378
- forEach(other, apply);
1379
- }
1380
- } else {
1381
- forEach(annotations, apply);
1382
- }
1383
- return plain;
1384
- }
1385
- var isDeep = (object, superJson) => isPlainObject(object) || isArray(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson);
1386
- function addIdentity(object, path, identities) {
1387
- const existingSet = identities.get(object);
1388
- if (existingSet) {
1389
- existingSet.push(path);
1390
- } else {
1391
- identities.set(object, [path]);
1392
- }
1393
- }
1394
- function generateReferentialEqualityAnnotations(identitites, dedupe) {
1395
- const result = {};
1396
- let rootEqualityPaths = void 0;
1397
- identitites.forEach((paths) => {
1398
- if (paths.length <= 1) {
1399
- return;
1400
- }
1401
- if (!dedupe) {
1402
- paths = paths.map((path) => path.map(String)).sort((a2, b) => a2.length - b.length);
1403
- }
1404
- const [representativePath, ...identicalPaths] = paths;
1405
- if (representativePath.length === 0) {
1406
- rootEqualityPaths = identicalPaths.map(stringifyPath);
1407
- } else {
1408
- result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);
1409
- }
1410
- });
1411
- if (rootEqualityPaths) {
1412
- if (isEmptyObject(result)) {
1413
- return [rootEqualityPaths];
1414
- } else {
1415
- return [rootEqualityPaths, result];
1416
- }
1417
- } else {
1418
- return isEmptyObject(result) ? void 0 : result;
1419
- }
1420
- }
1421
- var walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = /* @__PURE__ */ new Map()) => {
1422
- const primitive = isPrimitive(object);
1423
- if (!primitive) {
1424
- addIdentity(object, path, identities);
1425
- const seen = seenObjects.get(object);
1426
- if (seen) {
1427
- return dedupe ? {
1428
- transformedValue: null
1429
- } : seen;
1430
- }
1431
- }
1432
- if (!isDeep(object, superJson)) {
1433
- const transformed2 = transformValue(object, superJson);
1434
- const result2 = transformed2 ? {
1435
- transformedValue: transformed2.value,
1436
- annotations: [transformed2.type]
1437
- } : {
1438
- transformedValue: object
1439
- };
1440
- if (!primitive) {
1441
- seenObjects.set(object, result2);
1442
- }
1443
- return result2;
1444
- }
1445
- if (includes(objectsInThisPath, object)) {
1446
- return {
1447
- transformedValue: null
1448
- };
1449
- }
1450
- const transformationResult = transformValue(object, superJson);
1451
- const transformed = transformationResult?.value ?? object;
1452
- const transformedValue = isArray(transformed) ? [] : {};
1453
- const innerAnnotations = {};
1454
- forEach(transformed, (value, index) => {
1455
- if (index === "__proto__" || index === "constructor" || index === "prototype") {
1456
- throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);
1457
- }
1458
- const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);
1459
- transformedValue[index] = recursiveResult.transformedValue;
1460
- if (isArray(recursiveResult.annotations)) {
1461
- innerAnnotations[index] = recursiveResult.annotations;
1462
- } else if (isPlainObject(recursiveResult.annotations)) {
1463
- forEach(recursiveResult.annotations, (tree, key) => {
1464
- innerAnnotations[escapeKey(index) + "." + key] = tree;
1465
- });
1466
- }
850
+ function handleError(error, defaultMessage) {
851
+ const apiError = error;
852
+ throw new httpException.HTTPException(apiError.status || 500, {
853
+ message: apiError.message || defaultMessage
1467
854
  });
1468
- const result = isEmptyObject(innerAnnotations) ? {
1469
- transformedValue,
1470
- annotations: !!transformationResult ? [transformationResult.type] : void 0
1471
- } : {
1472
- transformedValue,
1473
- annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations
1474
- };
1475
- if (!primitive) {
1476
- seenObjects.set(object, result);
1477
- }
1478
- return result;
1479
- };
1480
-
1481
- // ../../node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js
1482
- function getType2(payload) {
1483
- return Object.prototype.toString.call(payload).slice(8, -1);
1484
- }
1485
- function isArray2(payload) {
1486
- return getType2(payload) === "Array";
1487
- }
1488
- function isPlainObject2(payload) {
1489
- if (getType2(payload) !== "Object")
1490
- return false;
1491
- const prototype = Object.getPrototypeOf(payload);
1492
- return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
1493
- }
1494
-
1495
- // ../../node_modules/.pnpm/copy-anything@3.0.5/node_modules/copy-anything/dist/index.js
1496
- function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
1497
- const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
1498
- if (propType === "enumerable")
1499
- carry[key] = newVal;
1500
- if (includeNonenumerable && propType === "nonenumerable") {
1501
- Object.defineProperty(carry, key, {
1502
- value: newVal,
1503
- enumerable: false,
1504
- writable: true,
1505
- configurable: true
1506
- });
1507
- }
1508
- }
1509
- function copy(target, options = {}) {
1510
- if (isArray2(target)) {
1511
- return target.map((item) => copy(item, options));
1512
- }
1513
- if (!isPlainObject2(target)) {
1514
- return target;
1515
- }
1516
- const props = Object.getOwnPropertyNames(target);
1517
- const symbols = Object.getOwnPropertySymbols(target);
1518
- return [...props, ...symbols].reduce((carry, key) => {
1519
- if (isArray2(options.props) && !options.props.includes(key)) {
1520
- return carry;
1521
- }
1522
- const val = target[key];
1523
- const newVal = copy(val, options);
1524
- assignProp(carry, key, newVal, target, options.nonenumerable);
1525
- return carry;
1526
- }, {});
1527
- }
1528
-
1529
- // ../../node_modules/.pnpm/superjson@2.2.2/node_modules/superjson/dist/index.js
1530
- var SuperJSON = class {
1531
- /**
1532
- * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.
1533
- */
1534
- constructor({ dedupe = false } = {}) {
1535
- this.classRegistry = new ClassRegistry();
1536
- this.symbolRegistry = new Registry((s3) => s3.description ?? "");
1537
- this.customTransformerRegistry = new CustomTransformerRegistry();
1538
- this.allowedErrorProps = [];
1539
- this.dedupe = dedupe;
1540
- }
1541
- serialize(object) {
1542
- const identities = /* @__PURE__ */ new Map();
1543
- const output = walker(object, identities, this, this.dedupe);
1544
- const res = {
1545
- json: output.transformedValue
1546
- };
1547
- if (output.annotations) {
1548
- res.meta = {
1549
- ...res.meta,
1550
- values: output.annotations
1551
- };
1552
- }
1553
- const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);
1554
- if (equalityAnnotations) {
1555
- res.meta = {
1556
- ...res.meta,
1557
- referentialEqualities: equalityAnnotations
1558
- };
1559
- }
1560
- return res;
1561
- }
1562
- deserialize(payload) {
1563
- const { json, meta } = payload;
1564
- let result = copy(json);
1565
- if (meta?.values) {
1566
- result = applyValueAnnotations(result, meta.values, this);
1567
- }
1568
- if (meta?.referentialEqualities) {
1569
- result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities);
1570
- }
1571
- return result;
1572
- }
1573
- stringify(object) {
1574
- return JSON.stringify(this.serialize(object));
1575
- }
1576
- parse(string) {
1577
- return this.deserialize(JSON.parse(string));
1578
- }
1579
- registerClass(v, options) {
1580
- this.classRegistry.register(v, options);
1581
- }
1582
- registerSymbol(v, identifier) {
1583
- this.symbolRegistry.register(v, identifier);
1584
- }
1585
- registerCustom(transformer, name) {
1586
- this.customTransformerRegistry.register({
1587
- name,
1588
- ...transformer
1589
- });
1590
- }
1591
- allowErrorProps(...props) {
1592
- this.allowedErrorProps.push(...props);
1593
- }
1594
- };
1595
- SuperJSON.defaultInstance = new SuperJSON();
1596
- SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);
1597
- SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);
1598
- SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);
1599
- SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);
1600
- SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);
1601
- SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);
1602
- SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);
1603
- SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);
1604
- var stringify = SuperJSON.stringify;
1605
-
1606
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/Options.js
1607
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
1608
- var defaultOptions = {
1609
- name: void 0,
1610
- $refStrategy: "root",
1611
- basePath: ["#"],
1612
- effectStrategy: "input",
1613
- pipeStrategy: "all",
1614
- dateStrategy: "format:date-time",
1615
- mapStrategy: "entries",
1616
- removeAdditionalStrategy: "passthrough",
1617
- allowedAdditionalProperties: true,
1618
- rejectedAdditionalProperties: false,
1619
- definitionPath: "definitions",
1620
- target: "jsonSchema7",
1621
- strictUnions: false,
1622
- definitions: {},
1623
- errorMessages: false,
1624
- markdownDescription: false,
1625
- patternStrategy: "escape",
1626
- applyRegexFlags: false,
1627
- emailStrategy: "format:email",
1628
- base64Strategy: "contentEncoding:base64",
1629
- nameStrategy: "ref"
1630
- };
1631
- var getDefaultOptions = (options) => typeof options === "string" ? {
1632
- ...defaultOptions,
1633
- name: options
1634
- } : {
1635
- ...defaultOptions,
1636
- ...options
1637
- };
1638
-
1639
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/Refs.js
1640
- var getRefs = (options) => {
1641
- const _options = getDefaultOptions(options);
1642
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1643
- return {
1644
- ..._options,
1645
- currentPath,
1646
- propertyPath: void 0,
1647
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
1648
- def._def,
1649
- {
1650
- def: def._def,
1651
- path: [..._options.basePath, _options.definitionPath, name],
1652
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1653
- jsonSchema: void 0
1654
- }
1655
- ]))
1656
- };
1657
- };
1658
-
1659
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
1660
- function addErrorMessage(res, key, errorMessage, refs) {
1661
- if (!refs?.errorMessages)
1662
- return;
1663
- if (errorMessage) {
1664
- res.errorMessage = {
1665
- ...res.errorMessage,
1666
- [key]: errorMessage
1667
- };
1668
- }
1669
- }
1670
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
1671
- res[key] = value;
1672
- addErrorMessage(res, key, errorMessage, refs);
1673
- }
1674
-
1675
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
1676
- function parseAnyDef() {
1677
- return {};
1678
- }
1679
- function parseArrayDef(def, refs) {
1680
- const res = {
1681
- type: "array"
1682
- };
1683
- if (def.type?._def && def.type?._def?.typeName !== zod.ZodFirstPartyTypeKind.ZodAny) {
1684
- res.items = parseDef(def.type._def, {
1685
- ...refs,
1686
- currentPath: [...refs.currentPath, "items"]
1687
- });
1688
- }
1689
- if (def.minLength) {
1690
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
1691
- }
1692
- if (def.maxLength) {
1693
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
1694
- }
1695
- if (def.exactLength) {
1696
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
1697
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
1698
- }
1699
- return res;
1700
- }
1701
-
1702
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
1703
- function parseBigintDef(def, refs) {
1704
- const res = {
1705
- type: "integer",
1706
- format: "int64"
1707
- };
1708
- if (!def.checks)
1709
- return res;
1710
- for (const check of def.checks) {
1711
- switch (check.kind) {
1712
- case "min":
1713
- if (refs.target === "jsonSchema7") {
1714
- if (check.inclusive) {
1715
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1716
- } else {
1717
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
1718
- }
1719
- } else {
1720
- if (!check.inclusive) {
1721
- res.exclusiveMinimum = true;
1722
- }
1723
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
1724
- }
1725
- break;
1726
- case "max":
1727
- if (refs.target === "jsonSchema7") {
1728
- if (check.inclusive) {
1729
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1730
- } else {
1731
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
1732
- }
1733
- } else {
1734
- if (!check.inclusive) {
1735
- res.exclusiveMaximum = true;
1736
- }
1737
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
1738
- }
1739
- break;
1740
- case "multipleOf":
1741
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
1742
- break;
1743
- }
1744
- }
1745
- return res;
1746
- }
1747
-
1748
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
1749
- function parseBooleanDef() {
1750
- return {
1751
- type: "boolean"
1752
- };
1753
- }
1754
-
1755
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
1756
- function parseBrandedDef(_def, refs) {
1757
- return parseDef(_def.type._def, refs);
1758
- }
1759
-
1760
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
1761
- var parseCatchDef = (def, refs) => {
1762
- return parseDef(def.innerType._def, refs);
1763
- };
1764
-
1765
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
1766
- function parseDateDef(def, refs, overrideDateStrategy) {
1767
- const strategy = overrideDateStrategy ?? refs.dateStrategy;
1768
- if (Array.isArray(strategy)) {
1769
- return {
1770
- anyOf: strategy.map((item, i2) => parseDateDef(def, refs, item))
1771
- };
1772
- }
1773
- switch (strategy) {
1774
- case "string":
1775
- case "format:date-time":
1776
- return {
1777
- type: "string",
1778
- format: "date-time"
1779
- };
1780
- case "format:date":
1781
- return {
1782
- type: "string",
1783
- format: "date"
1784
- };
1785
- case "integer":
1786
- return integerDateParser(def, refs);
1787
- }
1788
855
  }
1789
- var integerDateParser = (def, refs) => {
1790
- const res = {
1791
- type: "integer",
1792
- format: "unix-time"
1793
- };
1794
- if (refs.target === "openApi3") {
1795
- return res;
1796
- }
1797
- for (const check of def.checks) {
1798
- switch (check.kind) {
1799
- case "min":
1800
- setResponseValueAndErrors(
1801
- res,
1802
- "minimum",
1803
- check.value,
1804
- // This is in milliseconds
1805
- check.message,
1806
- refs
1807
- );
1808
- break;
1809
- case "max":
1810
- setResponseValueAndErrors(
1811
- res,
1812
- "maximum",
1813
- check.value,
1814
- // This is in milliseconds
1815
- check.message,
1816
- refs
1817
- );
1818
- break;
1819
- }
1820
- }
1821
- return res;
1822
- };
1823
-
1824
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
1825
- function parseDefaultDef(_def, refs) {
1826
- return {
1827
- ...parseDef(_def.innerType._def, refs),
1828
- default: _def.defaultValue()
1829
- };
1830
- }
1831
-
1832
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
1833
- function parseEffectsDef(_def, refs) {
1834
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
1835
- }
1836
-
1837
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
1838
- function parseEnumDef(def) {
1839
- return {
1840
- type: "string",
1841
- enum: Array.from(def.values)
1842
- };
1843
- }
1844
-
1845
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
1846
- var isJsonSchema7AllOfType = (type) => {
1847
- if ("type" in type && type.type === "string")
1848
- return false;
1849
- return "allOf" in type;
1850
- };
1851
- function parseIntersectionDef(def, refs) {
1852
- const allOf = [
1853
- parseDef(def.left._def, {
1854
- ...refs,
1855
- currentPath: [...refs.currentPath, "allOf", "0"]
1856
- }),
1857
- parseDef(def.right._def, {
1858
- ...refs,
1859
- currentPath: [...refs.currentPath, "allOf", "1"]
1860
- })
1861
- ].filter((x2) => !!x2);
1862
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
1863
- const mergedAllOf = [];
1864
- allOf.forEach((schema) => {
1865
- if (isJsonSchema7AllOfType(schema)) {
1866
- mergedAllOf.push(...schema.allOf);
1867
- if (schema.unevaluatedProperties === void 0) {
1868
- unevaluatedProperties = void 0;
1869
- }
1870
- } else {
1871
- let nestedSchema = schema;
1872
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
1873
- const { additionalProperties, ...rest } = schema;
1874
- nestedSchema = rest;
1875
- } else {
1876
- unevaluatedProperties = void 0;
1877
- }
1878
- mergedAllOf.push(nestedSchema);
1879
- }
1880
- });
1881
- return mergedAllOf.length ? {
1882
- allOf: mergedAllOf,
1883
- ...unevaluatedProperties
1884
- } : void 0;
1885
- }
1886
-
1887
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
1888
- function parseLiteralDef(def, refs) {
1889
- const parsedType = typeof def.value;
1890
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
1891
- return {
1892
- type: Array.isArray(def.value) ? "array" : "object"
1893
- };
1894
- }
1895
- if (refs.target === "openApi3") {
1896
- return {
1897
- type: parsedType === "bigint" ? "integer" : parsedType,
1898
- enum: [def.value]
1899
- };
1900
- }
1901
- return {
1902
- type: parsedType === "bigint" ? "integer" : parsedType,
1903
- const: def.value
1904
- };
1905
- }
1906
-
1907
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
1908
- var emojiRegex = void 0;
1909
- var zodPatterns = {
1910
- /**
1911
- * `c` was changed to `[cC]` to replicate /i flag
1912
- */
1913
- cuid: /^[cC][^\s-]{8,}$/,
1914
- cuid2: /^[0-9a-z]+$/,
1915
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
1916
- /**
1917
- * `a-z` was added to replicate /i flag
1918
- */
1919
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
1920
- /**
1921
- * Constructed a valid Unicode RegExp
1922
- *
1923
- * Lazily instantiate since this type of regex isn't supported
1924
- * in all envs (e.g. React Native).
1925
- *
1926
- * See:
1927
- * https://github.com/colinhacks/zod/issues/2433
1928
- * Fix in Zod:
1929
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
1930
- */
1931
- emoji: () => {
1932
- if (emojiRegex === void 0) {
1933
- emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
1934
- }
1935
- return emojiRegex;
1936
- },
1937
- /**
1938
- * Unused
1939
- */
1940
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
1941
- /**
1942
- * Unused
1943
- */
1944
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
1945
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
1946
- /**
1947
- * Unused
1948
- */
1949
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
1950
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
1951
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
1952
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
1953
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
1954
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
1955
- };
1956
- function parseStringDef(def, refs) {
1957
- const res = {
1958
- type: "string"
1959
- };
1960
- if (def.checks) {
1961
- for (const check of def.checks) {
1962
- switch (check.kind) {
1963
- case "min":
1964
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
1965
- break;
1966
- case "max":
1967
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
1968
- break;
1969
- case "email":
1970
- switch (refs.emailStrategy) {
1971
- case "format:email":
1972
- addFormat(res, "email", check.message, refs);
1973
- break;
1974
- case "format:idn-email":
1975
- addFormat(res, "idn-email", check.message, refs);
1976
- break;
1977
- case "pattern:zod":
1978
- addPattern(res, zodPatterns.email, check.message, refs);
1979
- break;
1980
- }
1981
- break;
1982
- case "url":
1983
- addFormat(res, "uri", check.message, refs);
1984
- break;
1985
- case "uuid":
1986
- addFormat(res, "uuid", check.message, refs);
1987
- break;
1988
- case "regex":
1989
- addPattern(res, check.regex, check.message, refs);
1990
- break;
1991
- case "cuid":
1992
- addPattern(res, zodPatterns.cuid, check.message, refs);
1993
- break;
1994
- case "cuid2":
1995
- addPattern(res, zodPatterns.cuid2, check.message, refs);
1996
- break;
1997
- case "startsWith":
1998
- addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
1999
- break;
2000
- case "endsWith":
2001
- addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
2002
- break;
2003
- case "datetime":
2004
- addFormat(res, "date-time", check.message, refs);
2005
- break;
2006
- case "date":
2007
- addFormat(res, "date", check.message, refs);
2008
- break;
2009
- case "time":
2010
- addFormat(res, "time", check.message, refs);
2011
- break;
2012
- case "duration":
2013
- addFormat(res, "duration", check.message, refs);
2014
- break;
2015
- case "length":
2016
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
2017
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
2018
- break;
2019
- case "includes": {
2020
- addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
2021
- break;
2022
- }
2023
- case "ip": {
2024
- if (check.version !== "v6") {
2025
- addFormat(res, "ipv4", check.message, refs);
2026
- }
2027
- if (check.version !== "v4") {
2028
- addFormat(res, "ipv6", check.message, refs);
2029
- }
2030
- break;
2031
- }
2032
- case "base64url":
2033
- addPattern(res, zodPatterns.base64url, check.message, refs);
2034
- break;
2035
- case "jwt":
2036
- addPattern(res, zodPatterns.jwt, check.message, refs);
2037
- break;
2038
- case "cidr": {
2039
- if (check.version !== "v6") {
2040
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
2041
- }
2042
- if (check.version !== "v4") {
2043
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
2044
- }
2045
- break;
2046
- }
2047
- case "emoji":
2048
- addPattern(res, zodPatterns.emoji(), check.message, refs);
2049
- break;
2050
- case "ulid": {
2051
- addPattern(res, zodPatterns.ulid, check.message, refs);
2052
- break;
2053
- }
2054
- case "base64": {
2055
- switch (refs.base64Strategy) {
2056
- case "format:binary": {
2057
- addFormat(res, "binary", check.message, refs);
2058
- break;
2059
- }
2060
- case "contentEncoding:base64": {
2061
- setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
2062
- break;
2063
- }
2064
- case "pattern:zod": {
2065
- addPattern(res, zodPatterns.base64, check.message, refs);
2066
- break;
2067
- }
2068
- }
2069
- break;
2070
- }
2071
- case "nanoid": {
2072
- addPattern(res, zodPatterns.nanoid, check.message, refs);
2073
- }
2074
- }
2075
- }
2076
- }
2077
- return res;
2078
- }
2079
- function escapeLiteralCheckValue(literal, refs) {
2080
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
2081
- }
2082
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
2083
- function escapeNonAlphaNumeric(source) {
2084
- let result = "";
2085
- for (let i2 = 0; i2 < source.length; i2++) {
2086
- if (!ALPHA_NUMERIC.has(source[i2])) {
2087
- result += "\\";
2088
- }
2089
- result += source[i2];
2090
- }
2091
- return result;
2092
- }
2093
- function addFormat(schema, value, message, refs) {
2094
- if (schema.format || schema.anyOf?.some((x2) => x2.format)) {
2095
- if (!schema.anyOf) {
2096
- schema.anyOf = [];
2097
- }
2098
- if (schema.format) {
2099
- schema.anyOf.push({
2100
- format: schema.format,
2101
- ...schema.errorMessage && refs.errorMessages && {
2102
- errorMessage: { format: schema.errorMessage.format }
2103
- }
2104
- });
2105
- delete schema.format;
2106
- if (schema.errorMessage) {
2107
- delete schema.errorMessage.format;
2108
- if (Object.keys(schema.errorMessage).length === 0) {
2109
- delete schema.errorMessage;
2110
- }
2111
- }
2112
- }
2113
- schema.anyOf.push({
2114
- format: value,
2115
- ...message && refs.errorMessages && { errorMessage: { format: message } }
2116
- });
2117
- } else {
2118
- setResponseValueAndErrors(schema, "format", value, message, refs);
2119
- }
2120
- }
2121
- function addPattern(schema, regex, message, refs) {
2122
- if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) {
2123
- if (!schema.allOf) {
2124
- schema.allOf = [];
2125
- }
2126
- if (schema.pattern) {
2127
- schema.allOf.push({
2128
- pattern: schema.pattern,
2129
- ...schema.errorMessage && refs.errorMessages && {
2130
- errorMessage: { pattern: schema.errorMessage.pattern }
2131
- }
2132
- });
2133
- delete schema.pattern;
2134
- if (schema.errorMessage) {
2135
- delete schema.errorMessage.pattern;
2136
- if (Object.keys(schema.errorMessage).length === 0) {
2137
- delete schema.errorMessage;
2138
- }
2139
- }
2140
- }
2141
- schema.allOf.push({
2142
- pattern: stringifyRegExpWithFlags(regex, refs),
2143
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
2144
- });
2145
- } else {
2146
- setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
2147
- }
2148
- }
2149
- function stringifyRegExpWithFlags(regex, refs) {
2150
- if (!refs.applyRegexFlags || !regex.flags) {
2151
- return regex.source;
2152
- }
2153
- const flags = {
2154
- i: regex.flags.includes("i"),
2155
- m: regex.flags.includes("m"),
2156
- s: regex.flags.includes("s")
2157
- // `.` matches newlines
2158
- };
2159
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
2160
- let pattern = "";
2161
- let isEscaped = false;
2162
- let inCharGroup = false;
2163
- let inCharRange = false;
2164
- for (let i2 = 0; i2 < source.length; i2++) {
2165
- if (isEscaped) {
2166
- pattern += source[i2];
2167
- isEscaped = false;
2168
- continue;
2169
- }
2170
- if (flags.i) {
2171
- if (inCharGroup) {
2172
- if (source[i2].match(/[a-z]/)) {
2173
- if (inCharRange) {
2174
- pattern += source[i2];
2175
- pattern += `${source[i2 - 2]}-${source[i2]}`.toUpperCase();
2176
- inCharRange = false;
2177
- } else if (source[i2 + 1] === "-" && source[i2 + 2]?.match(/[a-z]/)) {
2178
- pattern += source[i2];
2179
- inCharRange = true;
2180
- } else {
2181
- pattern += `${source[i2]}${source[i2].toUpperCase()}`;
2182
- }
2183
- continue;
2184
- }
2185
- } else if (source[i2].match(/[a-z]/)) {
2186
- pattern += `[${source[i2]}${source[i2].toUpperCase()}]`;
2187
- continue;
2188
- }
2189
- }
2190
- if (flags.m) {
2191
- if (source[i2] === "^") {
2192
- pattern += `(^|(?<=[\r
2193
- ]))`;
2194
- continue;
2195
- } else if (source[i2] === "$") {
2196
- pattern += `($|(?=[\r
2197
- ]))`;
2198
- continue;
2199
- }
2200
- }
2201
- if (flags.s && source[i2] === ".") {
2202
- pattern += inCharGroup ? `${source[i2]}\r
2203
- ` : `[${source[i2]}\r
2204
- ]`;
2205
- continue;
2206
- }
2207
- pattern += source[i2];
2208
- if (source[i2] === "\\") {
2209
- isEscaped = true;
2210
- } else if (inCharGroup && source[i2] === "]") {
2211
- inCharGroup = false;
2212
- } else if (!inCharGroup && source[i2] === "[") {
2213
- inCharGroup = true;
2214
- }
2215
- }
2216
- return pattern;
2217
- }
2218
-
2219
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
2220
- function parseRecordDef(def, refs) {
2221
- if (refs.target === "openAi") {
2222
- console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
2223
- }
2224
- if (refs.target === "openApi3" && def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodEnum) {
2225
- return {
2226
- type: "object",
2227
- required: def.keyType._def.values,
2228
- properties: def.keyType._def.values.reduce((acc, key) => ({
2229
- ...acc,
2230
- [key]: parseDef(def.valueType._def, {
2231
- ...refs,
2232
- currentPath: [...refs.currentPath, "properties", key]
2233
- }) ?? {}
2234
- }), {}),
2235
- additionalProperties: refs.rejectedAdditionalProperties
2236
- };
2237
- }
2238
- const schema = {
2239
- type: "object",
2240
- additionalProperties: parseDef(def.valueType._def, {
2241
- ...refs,
2242
- currentPath: [...refs.currentPath, "additionalProperties"]
2243
- }) ?? refs.allowedAdditionalProperties
2244
- };
2245
- if (refs.target === "openApi3") {
2246
- return schema;
2247
- }
2248
- if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
2249
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
2250
- return {
2251
- ...schema,
2252
- propertyNames: keyType
2253
- };
2254
- } else if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodEnum) {
2255
- return {
2256
- ...schema,
2257
- propertyNames: {
2258
- enum: def.keyType._def.values
2259
- }
2260
- };
2261
- } else if (def.keyType?._def.typeName === zod.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === zod.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
2262
- const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
2263
- return {
2264
- ...schema,
2265
- propertyNames: keyType
2266
- };
2267
- }
2268
- return schema;
2269
- }
2270
-
2271
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
2272
- function parseMapDef(def, refs) {
2273
- if (refs.mapStrategy === "record") {
2274
- return parseRecordDef(def, refs);
2275
- }
2276
- const keys = parseDef(def.keyType._def, {
2277
- ...refs,
2278
- currentPath: [...refs.currentPath, "items", "items", "0"]
2279
- }) || {};
2280
- const values = parseDef(def.valueType._def, {
2281
- ...refs,
2282
- currentPath: [...refs.currentPath, "items", "items", "1"]
2283
- }) || {};
2284
- return {
2285
- type: "array",
2286
- maxItems: 125,
2287
- items: {
2288
- type: "array",
2289
- items: [keys, values],
2290
- minItems: 2,
2291
- maxItems: 2
2292
- }
2293
- };
2294
- }
2295
-
2296
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
2297
- function parseNativeEnumDef(def) {
2298
- const object = def.values;
2299
- const actualKeys = Object.keys(def.values).filter((key) => {
2300
- return typeof object[object[key]] !== "number";
2301
- });
2302
- const actualValues = actualKeys.map((key) => object[key]);
2303
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
2304
- return {
2305
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
2306
- enum: actualValues
2307
- };
2308
- }
2309
-
2310
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
2311
- function parseNeverDef() {
2312
- return {
2313
- not: {}
2314
- };
2315
- }
2316
-
2317
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
2318
- function parseNullDef(refs) {
2319
- return refs.target === "openApi3" ? {
2320
- enum: ["null"],
2321
- nullable: true
2322
- } : {
2323
- type: "null"
2324
- };
2325
- }
2326
-
2327
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
2328
- var primitiveMappings = {
2329
- ZodString: "string",
2330
- ZodNumber: "number",
2331
- ZodBigInt: "integer",
2332
- ZodBoolean: "boolean",
2333
- ZodNull: "null"
2334
- };
2335
- function parseUnionDef(def, refs) {
2336
- if (refs.target === "openApi3")
2337
- return asAnyOf(def, refs);
2338
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
2339
- if (options.every((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) {
2340
- const types = options.reduce((types2, x2) => {
2341
- const type = primitiveMappings[x2._def.typeName];
2342
- return type && !types2.includes(type) ? [...types2, type] : types2;
2343
- }, []);
2344
- return {
2345
- type: types.length > 1 ? types : types[0]
2346
- };
2347
- } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) {
2348
- const types = options.reduce((acc, x2) => {
2349
- const type = typeof x2._def.value;
2350
- switch (type) {
2351
- case "string":
2352
- case "number":
2353
- case "boolean":
2354
- return [...acc, type];
2355
- case "bigint":
2356
- return [...acc, "integer"];
2357
- case "object":
2358
- if (x2._def.value === null)
2359
- return [...acc, "null"];
2360
- case "symbol":
2361
- case "undefined":
2362
- case "function":
2363
- default:
2364
- return acc;
2365
- }
2366
- }, []);
2367
- if (types.length === options.length) {
2368
- const uniqueTypes = types.filter((x2, i2, a2) => a2.indexOf(x2) === i2);
2369
- return {
2370
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
2371
- enum: options.reduce((acc, x2) => {
2372
- return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value];
2373
- }, [])
2374
- };
2375
- }
2376
- } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) {
2377
- return {
2378
- type: "string",
2379
- enum: options.reduce((acc, x2) => [
2380
- ...acc,
2381
- ...x2._def.values.filter((x3) => !acc.includes(x3))
2382
- ], [])
2383
- };
2384
- }
2385
- return asAnyOf(def, refs);
2386
- }
2387
- var asAnyOf = (def, refs) => {
2388
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i2) => parseDef(x2._def, {
2389
- ...refs,
2390
- currentPath: [...refs.currentPath, "anyOf", `${i2}`]
2391
- })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0));
2392
- return anyOf.length ? { anyOf } : void 0;
2393
- };
2394
-
2395
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
2396
- function parseNullableDef(def, refs) {
2397
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
2398
- if (refs.target === "openApi3") {
2399
- return {
2400
- type: primitiveMappings[def.innerType._def.typeName],
2401
- nullable: true
2402
- };
2403
- }
2404
- return {
2405
- type: [
2406
- primitiveMappings[def.innerType._def.typeName],
2407
- "null"
2408
- ]
2409
- };
2410
- }
2411
- if (refs.target === "openApi3") {
2412
- const base2 = parseDef(def.innerType._def, {
2413
- ...refs,
2414
- currentPath: [...refs.currentPath]
2415
- });
2416
- if (base2 && "$ref" in base2)
2417
- return { allOf: [base2], nullable: true };
2418
- return base2 && { ...base2, nullable: true };
2419
- }
2420
- const base = parseDef(def.innerType._def, {
2421
- ...refs,
2422
- currentPath: [...refs.currentPath, "anyOf", "0"]
2423
- });
2424
- return base && { anyOf: [base, { type: "null" }] };
2425
- }
2426
-
2427
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
2428
- function parseNumberDef(def, refs) {
2429
- const res = {
2430
- type: "number"
2431
- };
2432
- if (!def.checks)
2433
- return res;
2434
- for (const check of def.checks) {
2435
- switch (check.kind) {
2436
- case "int":
2437
- res.type = "integer";
2438
- addErrorMessage(res, "type", check.message, refs);
2439
- break;
2440
- case "min":
2441
- if (refs.target === "jsonSchema7") {
2442
- if (check.inclusive) {
2443
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
2444
- } else {
2445
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
2446
- }
2447
- } else {
2448
- if (!check.inclusive) {
2449
- res.exclusiveMinimum = true;
2450
- }
2451
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
2452
- }
2453
- break;
2454
- case "max":
2455
- if (refs.target === "jsonSchema7") {
2456
- if (check.inclusive) {
2457
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
2458
- } else {
2459
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
2460
- }
2461
- } else {
2462
- if (!check.inclusive) {
2463
- res.exclusiveMaximum = true;
2464
- }
2465
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
2466
- }
2467
- break;
2468
- case "multipleOf":
2469
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
2470
- break;
2471
- }
2472
- }
2473
- return res;
2474
- }
2475
- function parseObjectDef(def, refs) {
2476
- const forceOptionalIntoNullable = refs.target === "openAi";
2477
- const result = {
2478
- type: "object",
2479
- properties: {}
2480
- };
2481
- const required = [];
2482
- const shape = def.shape();
2483
- for (const propName in shape) {
2484
- let propDef = shape[propName];
2485
- if (propDef === void 0 || propDef._def === void 0) {
2486
- continue;
2487
- }
2488
- let propOptional = safeIsOptional(propDef);
2489
- if (propOptional && forceOptionalIntoNullable) {
2490
- if (propDef instanceof zod.ZodOptional) {
2491
- propDef = propDef._def.innerType;
2492
- }
2493
- if (!propDef.isNullable()) {
2494
- propDef = propDef.nullable();
2495
- }
2496
- propOptional = false;
2497
- }
2498
- const parsedDef = parseDef(propDef._def, {
2499
- ...refs,
2500
- currentPath: [...refs.currentPath, "properties", propName],
2501
- propertyPath: [...refs.currentPath, "properties", propName]
2502
- });
2503
- if (parsedDef === void 0) {
2504
- continue;
2505
- }
2506
- result.properties[propName] = parsedDef;
2507
- if (!propOptional) {
2508
- required.push(propName);
2509
- }
2510
- }
2511
- if (required.length) {
2512
- result.required = required;
2513
- }
2514
- const additionalProperties = decideAdditionalProperties(def, refs);
2515
- if (additionalProperties !== void 0) {
2516
- result.additionalProperties = additionalProperties;
2517
- }
2518
- return result;
2519
- }
2520
- function decideAdditionalProperties(def, refs) {
2521
- if (def.catchall._def.typeName !== "ZodNever") {
2522
- return parseDef(def.catchall._def, {
2523
- ...refs,
2524
- currentPath: [...refs.currentPath, "additionalProperties"]
2525
- });
2526
- }
2527
- switch (def.unknownKeys) {
2528
- case "passthrough":
2529
- return refs.allowedAdditionalProperties;
2530
- case "strict":
2531
- return refs.rejectedAdditionalProperties;
2532
- case "strip":
2533
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
2534
- }
2535
- }
2536
- function safeIsOptional(schema) {
2537
- try {
2538
- return schema.isOptional();
2539
- } catch {
2540
- return true;
2541
- }
2542
- }
2543
-
2544
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
2545
- var parseOptionalDef = (def, refs) => {
2546
- if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
2547
- return parseDef(def.innerType._def, refs);
2548
- }
2549
- const innerSchema = parseDef(def.innerType._def, {
2550
- ...refs,
2551
- currentPath: [...refs.currentPath, "anyOf", "1"]
2552
- });
2553
- return innerSchema ? {
2554
- anyOf: [
2555
- {
2556
- not: {}
2557
- },
2558
- innerSchema
2559
- ]
2560
- } : {};
2561
- };
2562
-
2563
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
2564
- var parsePipelineDef = (def, refs) => {
2565
- if (refs.pipeStrategy === "input") {
2566
- return parseDef(def.in._def, refs);
2567
- } else if (refs.pipeStrategy === "output") {
2568
- return parseDef(def.out._def, refs);
2569
- }
2570
- const a2 = parseDef(def.in._def, {
2571
- ...refs,
2572
- currentPath: [...refs.currentPath, "allOf", "0"]
2573
- });
2574
- const b = parseDef(def.out._def, {
2575
- ...refs,
2576
- currentPath: [...refs.currentPath, "allOf", a2 ? "1" : "0"]
2577
- });
2578
- return {
2579
- allOf: [a2, b].filter((x2) => x2 !== void 0)
2580
- };
2581
- };
2582
-
2583
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
2584
- function parsePromiseDef(def, refs) {
2585
- return parseDef(def.type._def, refs);
2586
- }
2587
-
2588
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
2589
- function parseSetDef(def, refs) {
2590
- const items = parseDef(def.valueType._def, {
2591
- ...refs,
2592
- currentPath: [...refs.currentPath, "items"]
2593
- });
2594
- const schema = {
2595
- type: "array",
2596
- uniqueItems: true,
2597
- items
2598
- };
2599
- if (def.minSize) {
2600
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
2601
- }
2602
- if (def.maxSize) {
2603
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
2604
- }
2605
- return schema;
2606
- }
2607
-
2608
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
2609
- function parseTupleDef(def, refs) {
2610
- if (def.rest) {
2611
- return {
2612
- type: "array",
2613
- minItems: def.items.length,
2614
- items: def.items.map((x2, i2) => parseDef(x2._def, {
2615
- ...refs,
2616
- currentPath: [...refs.currentPath, "items", `${i2}`]
2617
- })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []),
2618
- additionalItems: parseDef(def.rest._def, {
2619
- ...refs,
2620
- currentPath: [...refs.currentPath, "additionalItems"]
2621
- })
2622
- };
2623
- } else {
2624
- return {
2625
- type: "array",
2626
- minItems: def.items.length,
2627
- maxItems: def.items.length,
2628
- items: def.items.map((x2, i2) => parseDef(x2._def, {
2629
- ...refs,
2630
- currentPath: [...refs.currentPath, "items", `${i2}`]
2631
- })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], [])
2632
- };
2633
- }
2634
- }
2635
-
2636
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
2637
- function parseUndefinedDef() {
2638
- return {
2639
- not: {}
2640
- };
2641
- }
2642
-
2643
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
2644
- function parseUnknownDef() {
2645
- return {};
2646
- }
2647
-
2648
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
2649
- var parseReadonlyDef = (def, refs) => {
2650
- return parseDef(def.innerType._def, refs);
2651
- };
2652
-
2653
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/selectParser.js
2654
- var selectParser = (def, typeName, refs) => {
2655
- switch (typeName) {
2656
- case zod.ZodFirstPartyTypeKind.ZodString:
2657
- return parseStringDef(def, refs);
2658
- case zod.ZodFirstPartyTypeKind.ZodNumber:
2659
- return parseNumberDef(def, refs);
2660
- case zod.ZodFirstPartyTypeKind.ZodObject:
2661
- return parseObjectDef(def, refs);
2662
- case zod.ZodFirstPartyTypeKind.ZodBigInt:
2663
- return parseBigintDef(def, refs);
2664
- case zod.ZodFirstPartyTypeKind.ZodBoolean:
2665
- return parseBooleanDef();
2666
- case zod.ZodFirstPartyTypeKind.ZodDate:
2667
- return parseDateDef(def, refs);
2668
- case zod.ZodFirstPartyTypeKind.ZodUndefined:
2669
- return parseUndefinedDef();
2670
- case zod.ZodFirstPartyTypeKind.ZodNull:
2671
- return parseNullDef(refs);
2672
- case zod.ZodFirstPartyTypeKind.ZodArray:
2673
- return parseArrayDef(def, refs);
2674
- case zod.ZodFirstPartyTypeKind.ZodUnion:
2675
- case zod.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
2676
- return parseUnionDef(def, refs);
2677
- case zod.ZodFirstPartyTypeKind.ZodIntersection:
2678
- return parseIntersectionDef(def, refs);
2679
- case zod.ZodFirstPartyTypeKind.ZodTuple:
2680
- return parseTupleDef(def, refs);
2681
- case zod.ZodFirstPartyTypeKind.ZodRecord:
2682
- return parseRecordDef(def, refs);
2683
- case zod.ZodFirstPartyTypeKind.ZodLiteral:
2684
- return parseLiteralDef(def, refs);
2685
- case zod.ZodFirstPartyTypeKind.ZodEnum:
2686
- return parseEnumDef(def);
2687
- case zod.ZodFirstPartyTypeKind.ZodNativeEnum:
2688
- return parseNativeEnumDef(def);
2689
- case zod.ZodFirstPartyTypeKind.ZodNullable:
2690
- return parseNullableDef(def, refs);
2691
- case zod.ZodFirstPartyTypeKind.ZodOptional:
2692
- return parseOptionalDef(def, refs);
2693
- case zod.ZodFirstPartyTypeKind.ZodMap:
2694
- return parseMapDef(def, refs);
2695
- case zod.ZodFirstPartyTypeKind.ZodSet:
2696
- return parseSetDef(def, refs);
2697
- case zod.ZodFirstPartyTypeKind.ZodLazy:
2698
- return () => def.getter()._def;
2699
- case zod.ZodFirstPartyTypeKind.ZodPromise:
2700
- return parsePromiseDef(def, refs);
2701
- case zod.ZodFirstPartyTypeKind.ZodNaN:
2702
- case zod.ZodFirstPartyTypeKind.ZodNever:
2703
- return parseNeverDef();
2704
- case zod.ZodFirstPartyTypeKind.ZodEffects:
2705
- return parseEffectsDef(def, refs);
2706
- case zod.ZodFirstPartyTypeKind.ZodAny:
2707
- return parseAnyDef();
2708
- case zod.ZodFirstPartyTypeKind.ZodUnknown:
2709
- return parseUnknownDef();
2710
- case zod.ZodFirstPartyTypeKind.ZodDefault:
2711
- return parseDefaultDef(def, refs);
2712
- case zod.ZodFirstPartyTypeKind.ZodBranded:
2713
- return parseBrandedDef(def, refs);
2714
- case zod.ZodFirstPartyTypeKind.ZodReadonly:
2715
- return parseReadonlyDef(def, refs);
2716
- case zod.ZodFirstPartyTypeKind.ZodCatch:
2717
- return parseCatchDef(def, refs);
2718
- case zod.ZodFirstPartyTypeKind.ZodPipeline:
2719
- return parsePipelineDef(def, refs);
2720
- case zod.ZodFirstPartyTypeKind.ZodFunction:
2721
- case zod.ZodFirstPartyTypeKind.ZodVoid:
2722
- case zod.ZodFirstPartyTypeKind.ZodSymbol:
2723
- return void 0;
2724
- default:
2725
- return /* @__PURE__ */ ((_) => void 0)();
2726
- }
2727
- };
2728
-
2729
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/parseDef.js
2730
- function parseDef(def, refs, forceResolution = false) {
2731
- const seenItem = refs.seen.get(def);
2732
- if (refs.override) {
2733
- const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
2734
- if (overrideResult !== ignoreOverride) {
2735
- return overrideResult;
2736
- }
2737
- }
2738
- if (seenItem && !forceResolution) {
2739
- const seenSchema = get$ref(seenItem, refs);
2740
- if (seenSchema !== void 0) {
2741
- return seenSchema;
2742
- }
2743
- }
2744
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
2745
- refs.seen.set(def, newItem);
2746
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
2747
- const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
2748
- if (jsonSchema) {
2749
- addMeta(def, refs, jsonSchema);
2750
- }
2751
- if (refs.postProcess) {
2752
- const postProcessResult = refs.postProcess(jsonSchema, def, refs);
2753
- newItem.jsonSchema = jsonSchema;
2754
- return postProcessResult;
2755
- }
2756
- newItem.jsonSchema = jsonSchema;
2757
- return jsonSchema;
2758
- }
2759
- var get$ref = (item, refs) => {
2760
- switch (refs.$refStrategy) {
2761
- case "root":
2762
- return { $ref: item.path.join("/") };
2763
- case "relative":
2764
- return { $ref: getRelativePath(refs.currentPath, item.path) };
2765
- case "none":
2766
- case "seen": {
2767
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
2768
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
2769
- return {};
2770
- }
2771
- return refs.$refStrategy === "seen" ? {} : void 0;
2772
- }
2773
- }
2774
- };
2775
- var getRelativePath = (pathA, pathB) => {
2776
- let i2 = 0;
2777
- for (; i2 < pathA.length && i2 < pathB.length; i2++) {
2778
- if (pathA[i2] !== pathB[i2])
2779
- break;
2780
- }
2781
- return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/");
2782
- };
2783
- var addMeta = (def, refs, jsonSchema) => {
2784
- if (def.description) {
2785
- jsonSchema.description = def.description;
2786
- if (refs.markdownDescription) {
2787
- jsonSchema.markdownDescription = def.description;
2788
- }
2789
- }
2790
- return jsonSchema;
2791
- };
2792
-
2793
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
2794
- var zodToJsonSchema = (schema, options) => {
2795
- const refs = getRefs(options);
2796
- const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
2797
- ...acc,
2798
- [name2]: parseDef(schema2._def, {
2799
- ...refs,
2800
- currentPath: [...refs.basePath, refs.definitionPath, name2]
2801
- }, true) ?? {}
2802
- }), {}) : void 0;
2803
- const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
2804
- const main = parseDef(schema._def, name === void 0 ? refs : {
2805
- ...refs,
2806
- currentPath: [...refs.basePath, refs.definitionPath, name]
2807
- }, false) ?? {};
2808
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
2809
- if (title !== void 0) {
2810
- main.title = title;
2811
- }
2812
- const combined = name === void 0 ? definitions ? {
2813
- ...main,
2814
- [refs.definitionPath]: definitions
2815
- } : main : {
2816
- $ref: [
2817
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
2818
- refs.definitionPath,
2819
- name
2820
- ].join("/"),
2821
- [refs.definitionPath]: {
2822
- ...definitions,
2823
- [name]: main
2824
- }
2825
- };
2826
- if (refs.target === "jsonSchema7") {
2827
- combined.$schema = "http://json-schema.org/draft-07/schema#";
2828
- } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
2829
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
2830
- }
2831
- if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
2832
- console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
2833
- }
2834
- return combined;
2835
- };
2836
-
2837
- // ../../node_modules/.pnpm/zod-to-json-schema@3.24.4_zod@3.24.2/node_modules/zod-to-json-schema/dist/esm/index.js
2838
- var esm_default = zodToJsonSchema;
2839
- function handleError(error, defaultMessage) {
2840
- console.error(defaultMessage, error);
2841
- const apiError = error;
2842
- throw new httpException.HTTPException(apiError.status || 500, {
2843
- message: apiError.message || defaultMessage
2844
- });
2845
- }
2846
- function errorHandler(err, c2) {
2847
- if (err instanceof httpException.HTTPException) {
2848
- return c2.json({ error: err.message }, err.status);
856
+ function errorHandler(err, c2) {
857
+ if (err instanceof httpException.HTTPException) {
858
+ return c2.json({ error: err.message }, err.status);
2849
859
  }
2850
860
  console.error(err);
2851
861
  return c2.json({ error: "Internal Server Error" }, 500);
2852
862
  }
2853
- function validateBody(body) {
2854
- const errorResponse = Object.entries(body).reduce((acc, [key, value]) => {
2855
- if (!value) {
2856
- acc[key] = `${key} is required`;
2857
- }
2858
- return acc;
2859
- }, {});
2860
- if (Object.keys(errorResponse).length > 0) {
2861
- throw new httpException.HTTPException(400, { message: JSON.stringify(errorResponse) });
2862
- }
2863
- }
2864
-
2865
- // src/server/handlers/agents.ts
2866
- async function getAgentsHandler(c2) {
2867
- try {
2868
- const mastra = c2.get("mastra");
2869
- const agents = mastra.getAgents();
2870
- const serializedAgents = Object.entries(agents).reduce((acc, [_id, _agent]) => {
2871
- const agent = _agent;
2872
- const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc2, [key, tool]) => {
2873
- const _tool = tool;
2874
- acc2[key] = {
2875
- ..._tool,
2876
- inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
2877
- outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
2878
- };
2879
- return acc2;
2880
- }, {});
2881
- acc[_id] = {
2882
- name: agent.name,
2883
- instructions: agent.instructions,
2884
- tools: serializedAgentTools,
2885
- provider: agent.llm?.getProvider(),
2886
- modelId: agent.llm?.getModelId()
2887
- };
2888
- return acc;
2889
- }, {});
2890
- return c2.json(serializedAgents);
2891
- } catch (error) {
2892
- return handleError(error, "Error getting agents");
2893
- }
2894
- }
2895
- async function getAgentByIdHandler(c2) {
2896
- try {
2897
- const mastra = c2.get("mastra");
2898
- const agentId = c2.req.param("agentId");
2899
- const agent = mastra.getAgent(agentId);
2900
- if (!agent) {
2901
- throw new httpException.HTTPException(404, { message: "Agent not found" });
2902
- }
2903
- const serializedAgentTools = Object.entries(agent?.tools || {}).reduce((acc, [key, tool]) => {
2904
- const _tool = tool;
2905
- acc[key] = {
2906
- ..._tool,
2907
- inputSchema: _tool.inputSchema ? stringify(esm_default(_tool.inputSchema)) : void 0,
2908
- outputSchema: _tool.outputSchema ? stringify(esm_default(_tool.outputSchema)) : void 0
2909
- };
2910
- return acc;
2911
- }, {});
2912
- return c2.json({
2913
- name: agent.name,
2914
- instructions: agent.instructions,
2915
- tools: serializedAgentTools,
2916
- provider: agent.llm?.getProvider(),
2917
- modelId: agent.llm?.getModelId()
2918
- });
2919
- } catch (error) {
2920
- return handleError(error, "Error getting agent");
2921
- }
2922
- }
863
+
864
+ // src/server/handlers/agents.ts
865
+ async function getAgentsHandler(c2) {
866
+ const serializedAgents = await agents.getAgentsHandler({ mastra: c2.get("mastra") });
867
+ return c2.json(serializedAgents);
868
+ }
869
+ async function getAgentByIdHandler(c2) {
870
+ const mastra = c2.get("mastra");
871
+ const agentId = c2.req.param("agentId");
872
+ const result = await agents.getAgentByIdHandler({
873
+ mastra,
874
+ agentId
875
+ });
876
+ return c2.json(result);
877
+ }
2923
878
  async function getEvalsByAgentIdHandler(c2) {
2924
- try {
2925
- const mastra = c2.get("mastra");
2926
- const agentId = c2.req.param("agentId");
2927
- const agent = mastra.getAgent(agentId);
2928
- const evals = await mastra.storage?.getEvalsByAgentName?.(agent.name, "test") || [];
2929
- return c2.json({
2930
- id: agentId,
2931
- name: agent.name,
2932
- instructions: agent.instructions,
2933
- evals
2934
- });
2935
- } catch (error) {
2936
- return handleError(error, "Error getting test evals");
2937
- }
879
+ const mastra = c2.get("mastra");
880
+ const agentId = c2.req.param("agentId");
881
+ const result = await agents.getEvalsByAgentIdHandler({
882
+ mastra,
883
+ agentId
884
+ });
885
+ return c2.json(result);
2938
886
  }
2939
887
  async function getLiveEvalsByAgentIdHandler(c2) {
2940
- try {
2941
- const mastra = c2.get("mastra");
2942
- const agentId = c2.req.param("agentId");
2943
- const agent = mastra.getAgent(agentId);
2944
- const evals = await mastra.storage?.getEvalsByAgentName?.(agent.name, "live") || [];
2945
- return c2.json({
2946
- id: agentId,
2947
- name: agent.name,
2948
- instructions: agent.instructions,
2949
- evals
2950
- });
2951
- } catch (error) {
2952
- return handleError(error, "Error getting live evals");
2953
- }
888
+ const mastra = c2.get("mastra");
889
+ const agentId = c2.req.param("agentId");
890
+ const result = await agents.getLiveEvalsByAgentIdHandler({
891
+ mastra,
892
+ agentId
893
+ });
894
+ return c2.json(result);
2954
895
  }
2955
896
  async function generateHandler(c2) {
2956
897
  try {
2957
898
  const mastra = c2.get("mastra");
2958
899
  const agentId = c2.req.param("agentId");
2959
- const agent = mastra.getAgent(agentId);
2960
- if (!agent) {
2961
- throw new httpException.HTTPException(404, { message: "Agent not found" });
2962
- }
2963
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
2964
- validateBody({ messages });
900
+ const { resourceId, resourceid, ...body } = await c2.req.json();
2965
901
  const finalResourceId = resourceId ?? resourceid;
2966
- const result = await agent.generate(messages, { threadId, resourceId: finalResourceId, output, runId, ...rest });
902
+ const result = await agents.generateHandler({
903
+ mastra,
904
+ agentId,
905
+ resourceId: finalResourceId,
906
+ ...body
907
+ });
2967
908
  return c2.json(result);
2968
909
  } catch (error) {
2969
910
  return handleError(error, "Error generating from agent");
@@ -2973,26 +914,13 @@ async function streamGenerateHandler(c2) {
2973
914
  try {
2974
915
  const mastra = c2.get("mastra");
2975
916
  const agentId = c2.req.param("agentId");
2976
- const agent = mastra.getAgent(agentId);
2977
- if (!agent) {
2978
- throw new httpException.HTTPException(404, { message: "Agent not found" });
2979
- }
2980
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
2981
- validateBody({ messages });
917
+ const { resourceId, resourceid, ...body } = await c2.req.json();
2982
918
  const finalResourceId = resourceId ?? resourceid;
2983
- const streamResult = await agent.stream(messages, {
2984
- threadId,
919
+ const streamResponse = await agents.streamGenerateHandler({
920
+ mastra,
921
+ agentId,
2985
922
  resourceId: finalResourceId,
2986
- output,
2987
- runId,
2988
- ...rest
2989
- });
2990
- const streamResponse = output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
2991
- sendUsage: true,
2992
- sendReasoning: true,
2993
- getErrorMessage: (error) => {
2994
- return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
2995
- }
923
+ ...body
2996
924
  });
2997
925
  return streamResponse;
2998
926
  } catch (error) {
@@ -3030,7 +958,7 @@ async function setAgentInstructionsHandler(c2) {
3030
958
  // src/server/handlers/client.ts
3031
959
  var clients = /* @__PURE__ */ new Set();
3032
960
  function handleClientsRefresh(c2) {
3033
- const stream = new ReadableStream({
961
+ const stream2 = new ReadableStream({
3034
962
  start(controller) {
3035
963
  clients.add(controller);
3036
964
  controller.enqueue("data: connected\n\n");
@@ -3039,7 +967,7 @@ function handleClientsRefresh(c2) {
3039
967
  });
3040
968
  }
3041
969
  });
3042
- return new Response(stream, {
970
+ return new Response(stream2, {
3043
971
  headers: {
3044
972
  "Content-Type": "text/event-stream",
3045
973
  "Cache-Control": "no-cache",
@@ -3062,11 +990,11 @@ async function getLogsHandler(c2) {
3062
990
  try {
3063
991
  const mastra = c2.get("mastra");
3064
992
  const transportId = c2.req.query("transportId");
3065
- if (!transportId) {
3066
- throw new httpException.HTTPException(400, { message: "transportId is required" });
3067
- }
3068
- const logs = await mastra.getLogs(transportId);
3069
- return c2.json(logs);
993
+ const logs$1 = await logs.getLogsHandler({
994
+ mastra,
995
+ transportId
996
+ });
997
+ return c2.json(logs$1);
3070
998
  } catch (error) {
3071
999
  return handleError(error, "Error getting logs");
3072
1000
  }
@@ -3076,11 +1004,12 @@ async function getLogsByRunIdHandler(c2) {
3076
1004
  const mastra = c2.get("mastra");
3077
1005
  const runId = c2.req.param("runId");
3078
1006
  const transportId = c2.req.query("transportId");
3079
- if (!transportId) {
3080
- throw new httpException.HTTPException(400, { message: "transportId is required" });
3081
- }
3082
- const logs = await mastra.getLogsByRunId({ runId, transportId });
3083
- return c2.json(logs);
1007
+ const logs$1 = await logs.getLogsByRunIdHandler({
1008
+ mastra,
1009
+ runId,
1010
+ transportId
1011
+ });
1012
+ return c2.json(logs$1);
3084
1013
  } catch (error) {
3085
1014
  return handleError(error, "Error getting logs by run ID");
3086
1015
  }
@@ -3088,85 +1017,67 @@ async function getLogsByRunIdHandler(c2) {
3088
1017
  async function getLogTransports(c2) {
3089
1018
  try {
3090
1019
  const mastra = c2.get("mastra");
3091
- const logger2 = mastra.getLogger();
3092
- const transports = logger2.transports;
3093
- return c2.json({
3094
- transports: Object.keys(transports)
1020
+ const result = await logs.getLogTransports({
1021
+ mastra
3095
1022
  });
3096
- } catch (e2) {
3097
- return handleError(e2, "Error getting log Transports ");
3098
- }
3099
- }
3100
- function getMemoryFromContext(c2) {
3101
- const mastra = c2.get("mastra");
3102
- const agentId = c2.req.query("agentId");
3103
- const agent = agentId ? mastra.getAgent(agentId) : null;
3104
- if (agentId && !agent) {
3105
- throw new httpException.HTTPException(404, { message: "Agent not found" });
1023
+ return c2.json(result);
1024
+ } catch (error) {
1025
+ return handleError(error, "Error getting log Transports");
3106
1026
  }
3107
- const memory = agent?.getMemory?.() || mastra.memory;
3108
- return memory;
3109
1027
  }
3110
1028
  async function getMemoryStatusHandler(c2) {
3111
1029
  try {
3112
- const memory = getMemoryFromContext(c2);
3113
- if (!memory) {
3114
- return c2.json({ result: false });
3115
- }
3116
- return c2.json({ result: true });
1030
+ const mastra = c2.get("mastra");
1031
+ const agentId = c2.req.query("agentId");
1032
+ const result = await memory.getMemoryStatusHandler({
1033
+ mastra,
1034
+ agentId
1035
+ });
1036
+ return c2.json(result);
3117
1037
  } catch (error) {
3118
1038
  return handleError(error, "Error getting memory status");
3119
1039
  }
3120
1040
  }
3121
1041
  async function getThreadsHandler(c2) {
3122
1042
  try {
3123
- const { resourceid } = c2.req.query();
3124
- const memory = getMemoryFromContext(c2);
3125
- if (!memory) {
3126
- throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3127
- }
3128
- if (!resourceid) {
3129
- throw new httpException.HTTPException(400, { message: "Resource ID is required" });
3130
- }
3131
- const threads = await memory.getThreadsByResourceId({ resourceId: resourceid });
3132
- return c2.json(threads);
1043
+ const mastra = c2.get("mastra");
1044
+ const agentId = c2.req.query("agentId");
1045
+ const resourceId = c2.req.query("resourceid");
1046
+ const result = await memory.getThreadsHandler({
1047
+ mastra,
1048
+ agentId,
1049
+ resourceId
1050
+ });
1051
+ return c2.json(result);
3133
1052
  } catch (error) {
3134
1053
  return handleError(error, "Error getting threads");
3135
1054
  }
3136
1055
  }
3137
1056
  async function getThreadByIdHandler(c2) {
3138
1057
  try {
3139
- const memory = getMemoryFromContext(c2);
1058
+ const mastra = c2.get("mastra");
1059
+ const agentId = c2.req.query("agentId");
3140
1060
  const threadId = c2.req.param("threadId");
3141
- if (!memory) {
3142
- throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3143
- }
3144
- const thread = await memory.getThreadById({ threadId });
3145
- if (!thread) {
3146
- throw new httpException.HTTPException(404, { message: "Thread not found" });
3147
- }
3148
- return c2.json(thread);
1061
+ const result = await memory.getThreadByIdHandler({
1062
+ mastra,
1063
+ agentId,
1064
+ threadId
1065
+ });
1066
+ return c2.json(result);
3149
1067
  } catch (error) {
3150
1068
  return handleError(error, "Error getting thread");
3151
1069
  }
3152
1070
  }
3153
1071
  async function saveMessagesHandler(c2) {
3154
1072
  try {
3155
- const memory = getMemoryFromContext(c2);
3156
- const { messages } = await c2.req.json();
3157
- if (!memory) {
3158
- throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3159
- }
3160
- validateBody({ messages });
3161
- if (!Array.isArray(messages)) {
3162
- throw new httpException.HTTPException(400, { message: "Messages should be an array" });
3163
- }
3164
- const processedMessages = messages.map((message) => ({
3165
- ...message,
3166
- id: memory.generateId(),
3167
- createdAt: message.createdAt ? new Date(message.createdAt) : /* @__PURE__ */ new Date()
3168
- }));
3169
- const result = await memory.saveMessages({ messages: processedMessages, memoryConfig: {} });
1073
+ const mastra = c2.get("mastra");
1074
+ const agentId = c2.req.query("agentId");
1075
+ const body = await c2.req.json();
1076
+ const result = await memory.saveMessagesHandler({
1077
+ mastra,
1078
+ agentId,
1079
+ body
1080
+ });
3170
1081
  return c2.json(result);
3171
1082
  } catch (error) {
3172
1083
  return handleError(error, "Error saving messages");
@@ -3174,13 +1085,14 @@ async function saveMessagesHandler(c2) {
3174
1085
  }
3175
1086
  async function createThreadHandler(c2) {
3176
1087
  try {
3177
- const memory = getMemoryFromContext(c2);
3178
- const { title, metadata, resourceid, threadId } = await c2.req.json();
3179
- if (!memory) {
3180
- throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3181
- }
3182
- validateBody({ resourceid });
3183
- const result = await memory.createThread({ resourceId: resourceid, title, metadata, threadId });
1088
+ const mastra = c2.get("mastra");
1089
+ const agentId = c2.req.query("agentId");
1090
+ const body = await c2.req.json();
1091
+ const result = await memory.createThreadHandler({
1092
+ mastra,
1093
+ agentId,
1094
+ body
1095
+ });
3184
1096
  return c2.json(result);
3185
1097
  } catch (error) {
3186
1098
  return handleError(error, "Error saving thread to memory");
@@ -3188,26 +1100,16 @@ async function createThreadHandler(c2) {
3188
1100
  }
3189
1101
  async function updateThreadHandler(c2) {
3190
1102
  try {
3191
- const memory = getMemoryFromContext(c2);
1103
+ const mastra = c2.get("mastra");
1104
+ const agentId = c2.req.query("agentId");
3192
1105
  const threadId = c2.req.param("threadId");
3193
- const { title, metadata, resourceid } = await c2.req.json();
3194
- const updatedAt = /* @__PURE__ */ new Date();
3195
- if (!memory) {
3196
- throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3197
- }
3198
- const thread = await memory.getThreadById({ threadId });
3199
- if (!thread) {
3200
- throw new httpException.HTTPException(404, { message: "Thread not found" });
3201
- }
3202
- const updatedThread = {
3203
- ...thread,
3204
- title: title || thread.title,
3205
- metadata: metadata || thread.metadata,
3206
- resourceId: resourceid || thread.resourceId,
3207
- createdAt: thread.createdAt,
3208
- updatedAt
3209
- };
3210
- const result = await memory.saveThread({ thread: updatedThread });
1106
+ const body = await c2.req.json();
1107
+ const result = await memory.updateThreadHandler({
1108
+ mastra,
1109
+ agentId,
1110
+ threadId,
1111
+ body
1112
+ });
3211
1113
  return c2.json(result);
3212
1114
  } catch (error) {
3213
1115
  return handleError(error, "Error updating thread");
@@ -3215,33 +1117,29 @@ async function updateThreadHandler(c2) {
3215
1117
  }
3216
1118
  async function deleteThreadHandler(c2) {
3217
1119
  try {
3218
- const memory = getMemoryFromContext(c2);
1120
+ const mastra = c2.get("mastra");
1121
+ const agentId = c2.req.query("agentId");
3219
1122
  const threadId = c2.req.param("threadId");
3220
- if (!memory) {
3221
- throw new httpException.HTTPException(400, { message: "Memory is not initialized" });
3222
- }
3223
- const thread = await memory.getThreadById({ threadId });
3224
- if (!thread) {
3225
- throw new httpException.HTTPException(404, { message: "Thread not found" });
3226
- }
3227
- await memory.deleteThread(threadId);
3228
- return c2.json({ result: "Thread deleted" });
1123
+ const result = await memory.deleteThreadHandler({
1124
+ mastra,
1125
+ agentId,
1126
+ threadId
1127
+ });
1128
+ return c2.json(result);
3229
1129
  } catch (error) {
3230
1130
  return handleError(error, "Error deleting thread");
3231
1131
  }
3232
1132
  }
3233
1133
  async function getMessagesHandler(c2) {
3234
1134
  try {
3235
- const memory = getMemoryFromContext(c2);
1135
+ const mastra = c2.get("mastra");
1136
+ const agentId = c2.req.query("agentId");
3236
1137
  const threadId = c2.req.param("threadId");
3237
- if (!memory) {
3238
- return c2.json({ error: "Memory is not initialized" }, 400);
3239
- }
3240
- const thread = await memory.getThreadById({ threadId });
3241
- if (!thread) {
3242
- return c2.json({ error: "Thread not found" }, 404);
3243
- }
3244
- const result = await memory.query({ threadId });
1138
+ const result = await memory.getMessagesHandler({
1139
+ mastra,
1140
+ agentId,
1141
+ threadId
1142
+ });
3245
1143
  return c2.json(result);
3246
1144
  } catch (error) {
3247
1145
  return handleError(error, "Error getting messages");
@@ -3250,26 +1148,10 @@ async function getMessagesHandler(c2) {
3250
1148
  async function getNetworksHandler(c2) {
3251
1149
  try {
3252
1150
  const mastra = c2.get("mastra");
3253
- const networks = mastra.getNetworks();
3254
- const serializedNetworks = networks.map((network) => {
3255
- const routingAgent = network.getRoutingAgent();
3256
- const agents = network.getAgents();
3257
- return {
3258
- id: network.formatAgentId(routingAgent.name),
3259
- name: routingAgent.name,
3260
- instructions: routingAgent.instructions,
3261
- agents: agents.map((agent) => ({
3262
- name: agent.name,
3263
- provider: agent.llm?.getProvider(),
3264
- modelId: agent.llm?.getModelId()
3265
- })),
3266
- routingModel: {
3267
- provider: routingAgent.llm?.getProvider(),
3268
- modelId: routingAgent.llm?.getModelId()
3269
- }
3270
- };
1151
+ const networks = await network.getNetworksHandler({
1152
+ mastra
3271
1153
  });
3272
- return c2.json(serializedNetworks);
1154
+ return c2.json(networks);
3273
1155
  } catch (error) {
3274
1156
  return handleError(error, "Error getting networks");
3275
1157
  }
@@ -3278,31 +1160,11 @@ async function getNetworkByIdHandler(c2) {
3278
1160
  try {
3279
1161
  const mastra = c2.get("mastra");
3280
1162
  const networkId = c2.req.param("networkId");
3281
- const networks = mastra.getNetworks();
3282
- const network = networks.find((network2) => {
3283
- const routingAgent2 = network2.getRoutingAgent();
3284
- return network2.formatAgentId(routingAgent2.name) === networkId;
1163
+ const network$1 = await network.getNetworkByIdHandler({
1164
+ mastra,
1165
+ networkId
3285
1166
  });
3286
- if (!network) {
3287
- return c2.json({ error: "Network not found" }, 404);
3288
- }
3289
- const routingAgent = network.getRoutingAgent();
3290
- const agents = network.getAgents();
3291
- const serializedNetwork = {
3292
- id: network.formatAgentId(routingAgent.name),
3293
- name: routingAgent.name,
3294
- instructions: routingAgent.instructions,
3295
- agents: agents.map((agent) => ({
3296
- name: agent.name,
3297
- provider: agent.llm?.getProvider(),
3298
- modelId: agent.llm?.getModelId()
3299
- })),
3300
- routingModel: {
3301
- provider: routingAgent.llm?.getProvider(),
3302
- modelId: routingAgent.llm?.getModelId()
3303
- }
3304
- };
3305
- return c2.json(serializedNetwork);
1167
+ return c2.json(network$1);
3306
1168
  } catch (error) {
3307
1169
  return handleError(error, "Error getting network by ID");
3308
1170
  }
@@ -3311,14 +1173,12 @@ async function generateHandler2(c2) {
3311
1173
  try {
3312
1174
  const mastra = c2.get("mastra");
3313
1175
  const networkId = c2.req.param("networkId");
3314
- const network = mastra.getNetwork(networkId);
3315
- if (!network) {
3316
- throw new httpException.HTTPException(404, { message: "Network not found" });
3317
- }
3318
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
3319
- validateBody({ messages });
3320
- const finalResourceId = resourceId ?? resourceid;
3321
- const result = await network.generate(messages, { threadId, resourceId: finalResourceId, output, runId, ...rest });
1176
+ const body = await c2.req.json();
1177
+ const result = await network.generateHandler({
1178
+ mastra,
1179
+ networkId,
1180
+ body
1181
+ });
3322
1182
  return c2.json(result);
3323
1183
  } catch (error) {
3324
1184
  return handleError(error, "Error generating from network");
@@ -3328,26 +1188,11 @@ async function streamGenerateHandler2(c2) {
3328
1188
  try {
3329
1189
  const mastra = c2.get("mastra");
3330
1190
  const networkId = c2.req.param("networkId");
3331
- const network = mastra.getNetwork(networkId);
3332
- if (!network) {
3333
- throw new httpException.HTTPException(404, { message: "Network not found" });
3334
- }
3335
- const { messages, threadId, resourceid, resourceId, output, runId, ...rest } = await c2.req.json();
3336
- validateBody({ messages });
3337
- const finalResourceId = resourceId ?? resourceid;
3338
- const streamResult = await network.stream(messages, {
3339
- threadId,
3340
- resourceId: finalResourceId,
3341
- output,
3342
- runId,
3343
- ...rest
3344
- });
3345
- const streamResponse = output ? streamResult.toTextStreamResponse() : streamResult.toDataStreamResponse({
3346
- sendUsage: true,
3347
- sendReasoning: true,
3348
- getErrorMessage: (error) => {
3349
- return `An error occurred while processing your request. ${error instanceof Error ? error.message : JSON.stringify(error)}`;
3350
- }
1191
+ const body = await c2.req.json();
1192
+ const streamResponse = await network.streamGenerateHandler({
1193
+ mastra,
1194
+ networkId,
1195
+ body
3351
1196
  });
3352
1197
  return streamResponse;
3353
1198
  } catch (error) {
@@ -3471,96 +1316,64 @@ async function rootHandler(c2) {
3471
1316
  async function getTelemetryHandler(c2) {
3472
1317
  try {
3473
1318
  const mastra = c2.get("mastra");
3474
- const telemetry = mastra.getTelemetry();
3475
- const storage = mastra.getStorage();
3476
1319
  const { name, scope, page, perPage } = c2.req.query();
3477
1320
  const attribute = c2.req.queries("attribute");
3478
- if (!telemetry) {
3479
- throw new httpException.HTTPException(400, { message: "Telemetry is not initialized" });
3480
- }
3481
- if (!storage) {
3482
- throw new httpException.HTTPException(400, { message: "Storage is not initialized" });
3483
- }
3484
- const attributes = attribute ? Object.fromEntries(
3485
- (Array.isArray(attribute) ? attribute : [attribute]).map((attr) => {
3486
- const [key, value] = attr.split(":");
3487
- return [key, value];
3488
- })
3489
- ) : void 0;
3490
- const traces = await storage.getTraces({
3491
- name,
3492
- scope,
3493
- page: Number(page ?? 0),
3494
- perPage: Number(perPage ?? 100),
3495
- attributes
1321
+ const traces = await telemetry.getTelemetryHandler({
1322
+ mastra,
1323
+ body: { name, scope, page: Number(page ?? 0), perPage: Number(perPage ?? 100), attribute }
3496
1324
  });
3497
1325
  return c2.json({ traces });
3498
1326
  } catch (error) {
3499
- return handleError(error, "Error saving messages");
1327
+ return handleError(error, "Error getting telemetry traces");
3500
1328
  }
3501
1329
  }
3502
- async function getToolsHandler(c2) {
1330
+ async function storeTelemetryHandler(c2) {
3503
1331
  try {
3504
- const tools = c2.get("tools");
3505
- if (!tools) {
3506
- return c2.json({});
1332
+ const body = await c2.req.json();
1333
+ const mastra = c2.get("mastra");
1334
+ const result = await telemetry.storeTelemetryHandler({ mastra, body });
1335
+ if (result.status === "error") {
1336
+ return c2.json(result, 500);
3507
1337
  }
3508
- const serializedTools = Object.entries(tools).reduce(
3509
- (acc, [id, _tool]) => {
3510
- const tool = _tool;
3511
- acc[id] = {
3512
- ...tool,
3513
- inputSchema: tool.inputSchema ? stringify(esm_default(tool.inputSchema)) : void 0,
3514
- outputSchema: tool.outputSchema ? stringify(esm_default(tool.outputSchema)) : void 0
3515
- };
3516
- return acc;
3517
- },
3518
- {}
3519
- );
3520
- return c2.json(serializedTools);
1338
+ return c2.json(result, 200);
1339
+ } catch (error) {
1340
+ return handleError(error, "Error storing telemetry traces");
1341
+ }
1342
+ }
1343
+ async function getToolsHandler(c2) {
1344
+ try {
1345
+ const tools$1 = c2.get("tools");
1346
+ const result = await tools.getToolsHandler({
1347
+ tools: tools$1
1348
+ });
1349
+ return c2.json(result);
3521
1350
  } catch (error) {
3522
1351
  return handleError(error, "Error getting tools");
3523
1352
  }
3524
1353
  }
3525
1354
  async function getToolByIdHandler(c2) {
3526
1355
  try {
3527
- const tools = c2.get("tools");
1356
+ const tools$1 = c2.get("tools");
3528
1357
  const toolId = c2.req.param("toolId");
3529
- const tool = Object.values(tools || {}).find((tool2) => tool2.id === toolId);
3530
- if (!tool) {
3531
- throw new httpException.HTTPException(404, { message: "Tool not found" });
3532
- }
3533
- const serializedTool = {
3534
- ...tool,
3535
- inputSchema: tool.inputSchema ? stringify(esm_default(tool.inputSchema)) : void 0,
3536
- outputSchema: tool.outputSchema ? stringify(esm_default(tool.outputSchema)) : void 0
3537
- };
3538
- return c2.json(serializedTool);
1358
+ const result = await tools.getToolByIdHandler({
1359
+ tools: tools$1,
1360
+ toolId
1361
+ });
1362
+ return c2.json(result);
3539
1363
  } catch (error) {
3540
1364
  return handleError(error, "Error getting tool");
3541
1365
  }
3542
1366
  }
3543
- function executeToolHandler(tools) {
1367
+ function executeToolHandler(tools$1) {
3544
1368
  return async (c2) => {
3545
1369
  try {
1370
+ const mastra = c2.get("mastra");
3546
1371
  const toolId = decodeURIComponent(c2.req.param("toolId"));
3547
- const tool = Object.values(tools || {}).find((tool2) => tool2.id === toolId);
3548
- if (!tool) {
3549
- return c2.json({ error: "Tool not found" }, 404);
3550
- }
3551
- if (!tool?.execute) {
3552
- return c2.json({ error: "Tool is not executable" }, 400);
3553
- }
3554
1372
  const { data } = await c2.req.json();
3555
- const mastra = c2.get("mastra");
3556
- if (core.isVercelTool(tool)) {
3557
- const result2 = await tool.execute(data);
3558
- return c2.json(result2);
3559
- }
3560
- const result = await tool.execute({
3561
- context: data,
1373
+ const result = await tools.executeToolHandler(tools$1)({
3562
1374
  mastra,
3563
- runId: mastra.runId
1375
+ toolId,
1376
+ data
3564
1377
  });
3565
1378
  return c2.json(result);
3566
1379
  } catch (error) {
@@ -3573,45 +1386,28 @@ async function executeAgentToolHandler(c2) {
3573
1386
  const mastra = c2.get("mastra");
3574
1387
  const agentId = c2.req.param("agentId");
3575
1388
  const toolId = c2.req.param("toolId");
3576
- const agent = mastra.getAgent(agentId);
3577
- const tool = Object.values(agent?.tools || {}).find((tool2) => tool2.id === toolId);
3578
- if (!tool) {
3579
- throw new httpException.HTTPException(404, { message: "Tool not found" });
3580
- }
3581
- if (!tool?.execute) {
3582
- return c2.json({ error: "Tool is not executable" }, 400);
3583
- }
3584
1389
  const { data } = await c2.req.json();
3585
- if (core.isVercelTool(tool)) {
3586
- const result2 = await tool.execute(data);
3587
- return c2.json(result2);
3588
- }
3589
- const result = await tool.execute({
3590
- context: data,
1390
+ const result = await tools.executeAgentToolHandler({
3591
1391
  mastra,
3592
- runId: agentId
1392
+ agentId,
1393
+ toolId,
1394
+ data
3593
1395
  });
3594
1396
  return c2.json(result);
3595
1397
  } catch (error) {
3596
1398
  return handleError(error, "Error executing tool");
3597
1399
  }
3598
1400
  }
3599
- var getVector = (c2, vectorName) => {
3600
- const vector = c2.get("mastra").getVector(vectorName);
3601
- if (!vector) {
3602
- throw new httpException.HTTPException(404, { message: `Vector store ${vectorName} not found` });
3603
- }
3604
- return vector;
3605
- };
3606
1401
  async function upsertVectors(c2) {
3607
1402
  try {
1403
+ const mastra = c2.get("mastra");
3608
1404
  const vectorName = c2.req.param("vectorName");
3609
- const { indexName, vectors, metadata, ids } = await c2.req.json();
3610
- if (!indexName || !vectors || !Array.isArray(vectors)) {
3611
- throw new httpException.HTTPException(400, { message: "Invalid request body. indexName and vectors array are required." });
3612
- }
3613
- const vector = getVector(c2, vectorName);
3614
- const result = await vector.upsert({ indexName, vectors, metadata, ids });
1405
+ const body = await c2.req.json();
1406
+ const result = await vector.upsertVectors({
1407
+ mastra,
1408
+ vectorName,
1409
+ index: body
1410
+ });
3615
1411
  return c2.json({ ids: result });
3616
1412
  } catch (error) {
3617
1413
  return handleError(error, "Error upserting vectors");
@@ -3619,18 +1415,14 @@ async function upsertVectors(c2) {
3619
1415
  }
3620
1416
  async function createIndex(c2) {
3621
1417
  try {
1418
+ const mastra = c2.get("mastra");
3622
1419
  const vectorName = c2.req.param("vectorName");
3623
- const { indexName, dimension, metric } = await c2.req.json();
3624
- if (!indexName || typeof dimension !== "number" || dimension <= 0) {
3625
- throw new httpException.HTTPException(400, {
3626
- message: "Invalid request body. indexName and positive dimension number are required."
3627
- });
3628
- }
3629
- if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
3630
- throw new httpException.HTTPException(400, { message: "Invalid metric. Must be one of: cosine, euclidean, dotproduct" });
3631
- }
3632
- const vector = getVector(c2, vectorName);
3633
- await vector.createIndex({ indexName, dimension, metric });
1420
+ const body = await c2.req.json();
1421
+ await vector.createIndex({
1422
+ mastra,
1423
+ vectorName,
1424
+ index: body
1425
+ });
3634
1426
  return c2.json({ success: true });
3635
1427
  } catch (error) {
3636
1428
  return handleError(error, "Error creating index");
@@ -3638,13 +1430,14 @@ async function createIndex(c2) {
3638
1430
  }
3639
1431
  async function queryVectors(c2) {
3640
1432
  try {
1433
+ const mastra = c2.get("mastra");
3641
1434
  const vectorName = c2.req.param("vectorName");
3642
1435
  const { indexName, queryVector, topK = 10, filter, includeVector = false } = await c2.req.json();
3643
- if (!indexName || !queryVector || !Array.isArray(queryVector)) {
3644
- throw new httpException.HTTPException(400, { message: "Invalid request body. indexName and queryVector array are required." });
3645
- }
3646
- const vector = getVector(c2, vectorName);
3647
- const results = await vector.query({ indexName, queryVector, topK, filter, includeVector });
1436
+ const results = await vector.queryVectors({
1437
+ mastra,
1438
+ vectorName,
1439
+ query: { indexName, queryVector, topK, filter, includeVector }
1440
+ });
3648
1441
  return c2.json({ results });
3649
1442
  } catch (error) {
3650
1443
  return handleError(error, "Error querying vectors");
@@ -3652,23 +1445,30 @@ async function queryVectors(c2) {
3652
1445
  }
3653
1446
  async function listIndexes(c2) {
3654
1447
  try {
1448
+ const mastra = c2.get("mastra");
3655
1449
  const vectorName = c2.req.param("vectorName");
3656
- const vector = getVector(c2, vectorName);
3657
- const indexes = await vector.listIndexes();
3658
- return c2.json({ indexes: indexes.filter(Boolean) });
1450
+ const indexes = await vector.listIndexes({
1451
+ mastra,
1452
+ vectorName
1453
+ });
1454
+ return c2.json({ indexes });
3659
1455
  } catch (error) {
3660
1456
  return handleError(error, "Error listing indexes");
3661
1457
  }
3662
1458
  }
3663
1459
  async function describeIndex(c2) {
3664
1460
  try {
1461
+ const mastra = c2.get("mastra");
3665
1462
  const vectorName = c2.req.param("vectorName");
3666
1463
  const indexName = c2.req.param("indexName");
3667
1464
  if (!indexName) {
3668
1465
  throw new httpException.HTTPException(400, { message: "Index name is required" });
3669
1466
  }
3670
- const vector = getVector(c2, vectorName);
3671
- const stats = await vector.describeIndex(indexName);
1467
+ const stats = await vector.describeIndex({
1468
+ mastra,
1469
+ vectorName,
1470
+ indexName
1471
+ });
3672
1472
  return c2.json({
3673
1473
  dimension: stats.dimension,
3674
1474
  count: stats.count,
@@ -3680,13 +1480,17 @@ async function describeIndex(c2) {
3680
1480
  }
3681
1481
  async function deleteIndex(c2) {
3682
1482
  try {
1483
+ const mastra = c2.get("mastra");
3683
1484
  const vectorName = c2.req.param("vectorName");
3684
1485
  const indexName = c2.req.param("indexName");
3685
1486
  if (!indexName) {
3686
1487
  throw new httpException.HTTPException(400, { message: "Index name is required" });
3687
1488
  }
3688
- const vector = getVector(c2, vectorName);
3689
- await vector.deleteIndex(indexName);
1489
+ await vector.deleteIndex({
1490
+ mastra,
1491
+ vectorName,
1492
+ indexName
1493
+ });
3690
1494
  return c2.json({ success: true });
3691
1495
  } catch (error) {
3692
1496
  return handleError(error, "Error deleting index");
@@ -3696,14 +1500,10 @@ async function getSpeakersHandler(c2) {
3696
1500
  try {
3697
1501
  const mastra = c2.get("mastra");
3698
1502
  const agentId = c2.req.param("agentId");
3699
- const agent = mastra.getAgent(agentId);
3700
- if (!agent) {
3701
- throw new httpException.HTTPException(404, { message: "Agent not found" });
3702
- }
3703
- if (!agent.voice) {
3704
- throw new httpException.HTTPException(400, { message: "Agent does not have voice capabilities" });
3705
- }
3706
- const speakers = await agent.getSpeakers();
1503
+ const speakers = await voice.getSpeakersHandler({
1504
+ mastra,
1505
+ agentId
1506
+ });
3707
1507
  return c2.json(speakers);
3708
1508
  } catch (error) {
3709
1509
  return handleError(error, "Error getting speakers");
@@ -3713,16 +1513,12 @@ async function speakHandler(c2) {
3713
1513
  try {
3714
1514
  const mastra = c2.get("mastra");
3715
1515
  const agentId = c2.req.param("agentId");
3716
- const agent = mastra.getAgent(agentId);
3717
- if (!agent) {
3718
- throw new httpException.HTTPException(404, { message: "Agent not found" });
3719
- }
3720
- if (!agent.voice) {
3721
- throw new httpException.HTTPException(400, { message: "Agent does not have voice capabilities" });
3722
- }
3723
1516
  const { input, options } = await c2.req.json();
3724
- await validateBody({ input });
3725
- const audioStream = await agent.voice.speak(input, options);
1517
+ const audioStream = await voice.generateSpeechHandler({
1518
+ mastra,
1519
+ agentId,
1520
+ body: { text: input, speakerId: options?.speakerId }
1521
+ });
3726
1522
  c2.header("Content-Type", `audio/${options?.filetype ?? "mp3"}`);
3727
1523
  c2.header("Transfer-Encoding", "chunked");
3728
1524
  return c2.body(audioStream);
@@ -3734,14 +1530,6 @@ async function listenHandler(c2) {
3734
1530
  try {
3735
1531
  const mastra = c2.get("mastra");
3736
1532
  const agentId = c2.req.param("agentId");
3737
- const agent = mastra.getAgent(agentId);
3738
- const logger2 = mastra.getLogger();
3739
- if (!agent) {
3740
- throw new httpException.HTTPException(404, { message: "Agent not found" });
3741
- }
3742
- if (!agent.voice) {
3743
- throw new httpException.HTTPException(400, { message: "Agent does not have voice capabilities" });
3744
- }
3745
1533
  const formData = await c2.req.formData();
3746
1534
  const audioFile = formData.get("audio");
3747
1535
  const options = formData.get("options");
@@ -3749,19 +1537,19 @@ async function listenHandler(c2) {
3749
1537
  throw new httpException.HTTPException(400, { message: "Audio file is required" });
3750
1538
  }
3751
1539
  const audioData = await audioFile.arrayBuffer();
3752
- const audioStream = new stream.Readable();
3753
- audioStream.push(Buffer.from(audioData));
3754
- audioStream.push(null);
3755
- let parsedOptions;
1540
+ let parsedOptions = {};
3756
1541
  try {
3757
1542
  parsedOptions = options ? JSON.parse(options) : {};
3758
- } catch (error) {
3759
- if (error instanceof SyntaxError) {
3760
- logger2.error("Invalid JSON in options:", error);
3761
- }
3762
- parsedOptions = {};
1543
+ } catch {
3763
1544
  }
3764
- const transcription = await agent.voice.listen(audioStream, parsedOptions);
1545
+ const transcription = await voice.transcribeSpeechHandler({
1546
+ mastra,
1547
+ agentId,
1548
+ body: {
1549
+ audioData: Buffer.from(audioData),
1550
+ options: parsedOptions
1551
+ }
1552
+ });
3765
1553
  return c2.json({ text: transcription });
3766
1554
  } catch (error) {
3767
1555
  return handleError(error, "Error transcribing speech");
@@ -3770,28 +1558,10 @@ async function listenHandler(c2) {
3770
1558
  async function getWorkflowsHandler(c2) {
3771
1559
  try {
3772
1560
  const mastra = c2.get("mastra");
3773
- const workflows = mastra.getWorkflows({ serialized: false });
3774
- const _workflows = Object.entries(workflows).reduce((acc, [key, workflow]) => {
3775
- acc[key] = {
3776
- stepGraph: workflow.stepGraph,
3777
- stepSubscriberGraph: workflow.stepSubscriberGraph,
3778
- serializedStepGraph: workflow.serializedStepGraph,
3779
- serializedStepSubscriberGraph: workflow.serializedStepSubscriberGraph,
3780
- name: workflow.name,
3781
- triggerSchema: workflow.triggerSchema ? stringify(esm_default(workflow.triggerSchema)) : void 0,
3782
- steps: Object.entries(workflow.steps).reduce((acc2, [key2, step]) => {
3783
- const _step = step;
3784
- acc2[key2] = {
3785
- ..._step,
3786
- inputSchema: _step.inputSchema ? stringify(esm_default(_step.inputSchema)) : void 0,
3787
- outputSchema: _step.outputSchema ? stringify(esm_default(_step.outputSchema)) : void 0
3788
- };
3789
- return acc2;
3790
- }, {})
3791
- };
3792
- return acc;
3793
- }, {});
3794
- return c2.json(_workflows);
1561
+ const workflows$1 = await workflows.getWorkflowsHandler({
1562
+ mastra
1563
+ });
1564
+ return c2.json(workflows$1);
3795
1565
  } catch (error) {
3796
1566
  return handleError(error, "Error getting workflows");
3797
1567
  }
@@ -3800,30 +1570,11 @@ async function getWorkflowByIdHandler(c2) {
3800
1570
  try {
3801
1571
  const mastra = c2.get("mastra");
3802
1572
  const workflowId = c2.req.param("workflowId");
3803
- const workflow = mastra.getWorkflow(workflowId);
3804
- const triggerSchema = workflow?.triggerSchema;
3805
- const stepGraph = workflow.stepGraph;
3806
- const stepSubscriberGraph = workflow.stepSubscriberGraph;
3807
- const serializedStepGraph = workflow.serializedStepGraph;
3808
- const serializedStepSubscriberGraph = workflow.serializedStepSubscriberGraph;
3809
- const serializedSteps = Object.entries(workflow.steps).reduce((acc, [key, step]) => {
3810
- const _step = step;
3811
- acc[key] = {
3812
- ..._step,
3813
- inputSchema: _step.inputSchema ? stringify(esm_default(_step.inputSchema)) : void 0,
3814
- outputSchema: _step.outputSchema ? stringify(esm_default(_step.outputSchema)) : void 0
3815
- };
3816
- return acc;
3817
- }, {});
3818
- return c2.json({
3819
- name: workflow.name,
3820
- triggerSchema: triggerSchema ? stringify(esm_default(triggerSchema)) : void 0,
3821
- steps: serializedSteps,
3822
- stepGraph,
3823
- stepSubscriberGraph,
3824
- serializedStepGraph,
3825
- serializedStepSubscriberGraph
1573
+ const workflow = await workflows.getWorkflowByIdHandler({
1574
+ mastra,
1575
+ workflowId
3826
1576
  });
1577
+ return c2.json(workflow);
3827
1578
  } catch (error) {
3828
1579
  return handleError(error, "Error getting workflow");
3829
1580
  }
@@ -3832,18 +1583,13 @@ async function startAsyncWorkflowHandler(c2) {
3832
1583
  try {
3833
1584
  const mastra = c2.get("mastra");
3834
1585
  const workflowId = c2.req.param("workflowId");
3835
- const workflow = mastra.getWorkflow(workflowId);
3836
- const body = await c2.req.json();
1586
+ const triggerData = await c2.req.json();
3837
1587
  const runId = c2.req.query("runId");
3838
- if (!runId) {
3839
- throw new httpException.HTTPException(400, { message: "runId required to start run" });
3840
- }
3841
- const run = workflow.getRun(runId);
3842
- if (!run) {
3843
- throw new httpException.HTTPException(404, { message: "Workflow run not found" });
3844
- }
3845
- const result = await run.start({
3846
- triggerData: body
1588
+ const result = await workflows.startAsyncWorkflowHandler({
1589
+ mastra,
1590
+ workflowId,
1591
+ runId,
1592
+ triggerData
3847
1593
  });
3848
1594
  return c2.json(result);
3849
1595
  } catch (error) {
@@ -3854,10 +1600,13 @@ async function createRunHandler(c2) {
3854
1600
  try {
3855
1601
  const mastra = c2.get("mastra");
3856
1602
  const workflowId = c2.req.param("workflowId");
3857
- const workflow = mastra.getWorkflow(workflowId);
3858
1603
  const prevRunId = c2.req.query("runId");
3859
- const { runId } = workflow.createRun({ runId: prevRunId });
3860
- return c2.json({ runId });
1604
+ const result = await workflows.createRunHandler({
1605
+ mastra,
1606
+ workflowId,
1607
+ runId: prevRunId
1608
+ });
1609
+ return c2.json(result);
3861
1610
  } catch (e2) {
3862
1611
  return handleError(e2, "Error creating run");
3863
1612
  }
@@ -3866,54 +1615,51 @@ async function startWorkflowRunHandler(c2) {
3866
1615
  try {
3867
1616
  const mastra = c2.get("mastra");
3868
1617
  const workflowId = c2.req.param("workflowId");
3869
- const workflow = mastra.getWorkflow(workflowId);
3870
- const body = await c2.req.json();
1618
+ const triggerData = await c2.req.json();
3871
1619
  const runId = c2.req.query("runId");
3872
- if (!runId) {
3873
- throw new httpException.HTTPException(400, { message: "runId required to start run" });
3874
- }
3875
- const run = workflow.getRun(runId);
3876
- if (!run) {
3877
- throw new httpException.HTTPException(404, { message: "Workflow run not found" });
3878
- }
3879
- run.start({
3880
- triggerData: body
1620
+ await workflows.startWorkflowRunHandler({
1621
+ mastra,
1622
+ workflowId,
1623
+ runId,
1624
+ triggerData
3881
1625
  });
3882
1626
  return c2.json({ message: "Workflow run started" });
3883
1627
  } catch (e2) {
3884
1628
  return handleError(e2, "Error starting workflow run");
3885
1629
  }
3886
1630
  }
3887
- async function watchWorkflowHandler(c2) {
1631
+ function watchWorkflowHandler(c2) {
3888
1632
  try {
3889
1633
  const mastra = c2.get("mastra");
3890
1634
  const logger2 = mastra.getLogger();
3891
1635
  const workflowId = c2.req.param("workflowId");
3892
- const workflow = mastra.getWorkflow(workflowId);
3893
1636
  const runId = c2.req.query("runId");
3894
1637
  if (!runId) {
3895
1638
  throw new httpException.HTTPException(400, { message: "runId required to watch workflow" });
3896
1639
  }
3897
- const run = workflow.getRun(runId);
3898
- if (!run) {
3899
- throw new httpException.HTTPException(404, { message: "Workflow run not found" });
3900
- }
3901
- return streaming.streamText(
1640
+ return streaming.stream(
3902
1641
  c2,
3903
- async (stream) => {
3904
- return new Promise((_resolve, _reject) => {
3905
- let unwatch = run.watch(({ activePaths, context, runId: runId2, timestamp, suspendedSteps }) => {
3906
- void stream.write(JSON.stringify({ activePaths, context, runId: runId2, timestamp, suspendedSteps }) + "");
1642
+ async (stream2) => {
1643
+ try {
1644
+ const result = await workflows.watchWorkflowHandler({
1645
+ mastra,
1646
+ workflowId,
1647
+ runId
3907
1648
  });
3908
- stream.onAbort(() => {
3909
- unwatch?.();
1649
+ stream2.onAbort(() => {
1650
+ if (!result.locked) {
1651
+ return result.cancel();
1652
+ }
3910
1653
  });
3911
- });
1654
+ for await (const chunk of result) {
1655
+ await stream2.write(chunk.toString() + "");
1656
+ }
1657
+ } catch (err) {
1658
+ console.log(err);
1659
+ }
3912
1660
  },
3913
- async (err, stream) => {
1661
+ async (err) => {
3914
1662
  logger2.error("Error in watch stream: " + err?.message);
3915
- stream.abort();
3916
- await stream.close();
3917
1663
  }
3918
1664
  );
3919
1665
  } catch (error) {
@@ -3924,19 +1670,16 @@ async function resumeAsyncWorkflowHandler(c2) {
3924
1670
  try {
3925
1671
  const mastra = c2.get("mastra");
3926
1672
  const workflowId = c2.req.param("workflowId");
3927
- const workflow = mastra.getWorkflow(workflowId);
3928
1673
  const runId = c2.req.query("runId");
3929
1674
  const { stepId, context } = await c2.req.json();
3930
1675
  if (!runId) {
3931
1676
  throw new httpException.HTTPException(400, { message: "runId required to resume workflow" });
3932
1677
  }
3933
- const run = workflow.getRun(runId);
3934
- if (!run) {
3935
- throw new httpException.HTTPException(404, { message: "Workflow run not found" });
3936
- }
3937
- const result = await run.resume({
3938
- stepId,
3939
- context
1678
+ const result = await workflows.resumeAsyncWorkflowHandler({
1679
+ mastra,
1680
+ workflowId,
1681
+ runId,
1682
+ body: { stepId, context }
3940
1683
  });
3941
1684
  return c2.json(result);
3942
1685
  } catch (error) {
@@ -3947,19 +1690,16 @@ async function resumeWorkflowHandler(c2) {
3947
1690
  try {
3948
1691
  const mastra = c2.get("mastra");
3949
1692
  const workflowId = c2.req.param("workflowId");
3950
- const workflow = mastra.getWorkflow(workflowId);
3951
1693
  const runId = c2.req.query("runId");
3952
1694
  const { stepId, context } = await c2.req.json();
3953
1695
  if (!runId) {
3954
1696
  throw new httpException.HTTPException(400, { message: "runId required to resume workflow" });
3955
1697
  }
3956
- const run = workflow.getRun(runId);
3957
- if (!run) {
3958
- throw new httpException.HTTPException(404, { message: "Workflow run not found" });
3959
- }
3960
- run.resume({
3961
- stepId,
3962
- context
1698
+ await workflows.resumeWorkflowHandler({
1699
+ mastra,
1700
+ workflowId,
1701
+ runId,
1702
+ body: { stepId, context }
3963
1703
  });
3964
1704
  return c2.json({ message: "Workflow run resumed" });
3965
1705
  } catch (error) {
@@ -4094,7 +1834,7 @@ async function createHonoServer(mastra, options = {}) {
4094
1834
  cors.cors({
4095
1835
  origin: "*",
4096
1836
  allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
4097
- allowHeaders: ["Content-Type", "Authorization"],
1837
+ allowHeaders: ["Content-Type", "Authorization", "x-mastra-client-type"],
4098
1838
  exposeHeaders: ["Content-Length", "X-Requested-With"],
4099
1839
  credentials: false,
4100
1840
  maxAge: 3600
@@ -4114,13 +1854,67 @@ async function createHonoServer(mastra, options = {}) {
4114
1854
  c2.set("mastra", mastra);
4115
1855
  c2.set("tools", tools);
4116
1856
  c2.set("playground", options.playground === true);
4117
- await next();
1857
+ const requestId = c2.req.header("x-request-id") ?? crypto.randomUUID();
1858
+ const span = core.Telemetry.getActiveSpan();
1859
+ if (span) {
1860
+ span.setAttribute("http.request_id", requestId);
1861
+ span.updateName(`${c2.req.method} ${c2.req.path}`);
1862
+ const newCtx = core.Telemetry.setBaggage({
1863
+ "http.request_id": requestId
1864
+ });
1865
+ await new Promise((resolve) => {
1866
+ core.Telemetry.withContext(newCtx, async () => {
1867
+ await next();
1868
+ resolve(true);
1869
+ });
1870
+ });
1871
+ } else {
1872
+ await next();
1873
+ }
4118
1874
  });
4119
1875
  const bodyLimitOptions = {
4120
1876
  maxSize: 4.5 * 1024 * 1024,
4121
1877
  // 4.5 MB,
4122
1878
  onError: (c2) => c2.json({ error: "Request body too large" }, 413)
4123
1879
  };
1880
+ const server = mastra.getServer();
1881
+ const routes = server?.apiRoutes;
1882
+ if (server?.middleware) {
1883
+ const normalizedMiddlewares = Array.isArray(server.middleware) ? server.middleware : [server.middleware];
1884
+ const middlewares = normalizedMiddlewares.map((middleware2) => {
1885
+ if (typeof middleware2 === "function") {
1886
+ return {
1887
+ path: "*",
1888
+ handler: middleware2
1889
+ };
1890
+ }
1891
+ return middleware2;
1892
+ });
1893
+ for (const middleware2 of middlewares) {
1894
+ app.use(middleware2.path, middleware2.handler);
1895
+ }
1896
+ }
1897
+ if (routes) {
1898
+ for (const route of routes) {
1899
+ const middlewares = [];
1900
+ if (route.middleware) {
1901
+ middlewares.push(...Array.isArray(route.middleware) ? route.middleware : [route.middleware]);
1902
+ }
1903
+ if (route.openapi) {
1904
+ middlewares.push(h(route.openapi));
1905
+ }
1906
+ console.log({ path: route.path, middlewares });
1907
+ if (route.method === "GET") {
1908
+ app.get(route.path, ...middlewares, route.handler);
1909
+ } else if (route.method === "POST") {
1910
+ app.post(route.path, ...middlewares, route.handler);
1911
+ } else if (route.method === "PUT") {
1912
+ app.put(route.path, ...middlewares, route.handler);
1913
+ } else if (route.method === "DELETE") {
1914
+ app.delete(route.path, ...middlewares, route.handler);
1915
+ }
1916
+ }
1917
+ }
4124
1918
  app.get(
4125
1919
  "/api",
4126
1920
  h({
@@ -5242,6 +3036,19 @@ async function createHonoServer(mastra, options = {}) {
5242
3036
  }),
5243
3037
  getTelemetryHandler
5244
3038
  );
3039
+ app.post(
3040
+ "/api/telemetry",
3041
+ h({
3042
+ description: "Store telemetry",
3043
+ tags: ["telemetry"],
3044
+ responses: {
3045
+ 200: {
3046
+ description: "Traces stored"
3047
+ }
3048
+ }
3049
+ }),
3050
+ storeTelemetryHandler
3051
+ );
5245
3052
  app.get(
5246
3053
  "/api/workflows",
5247
3054
  h({