@mastra/deployer 0.2.6-alpha.1 → 0.2.6-alpha.10

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