@mastra/deployer 0.3.3 → 0.3.4-alpha.1

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.
@@ -18,8 +18,12 @@ var cors = require('hono/cors');
18
18
  var logger = require('hono/logger');
19
19
  var timeout = require('hono/timeout');
20
20
  var httpException = require('hono/http-exception');
21
+ var a2a = require('@mastra/server/handlers/a2a');
22
+ var streaming = require('hono/streaming');
21
23
  var agents = require('@mastra/server/handlers/agents');
22
24
  var logs = require('@mastra/server/handlers/logs');
25
+ var util = require('util');
26
+ var buffer = require('buffer');
23
27
  var memory = require('@mastra/server/handlers/memory');
24
28
  var network = require('@mastra/server/handlers/network');
25
29
  var agent = require('@mastra/core/agent');
@@ -28,13 +32,13 @@ var telemetry = require('@mastra/server/handlers/telemetry');
28
32
  var tools = require('@mastra/server/handlers/tools');
29
33
  var vector = require('@mastra/server/handlers/vector');
30
34
  var vNextWorkflows = require('@mastra/server/handlers/vNextWorkflows');
31
- var streaming = require('hono/streaming');
32
35
  var voice = require('@mastra/server/handlers/voice');
33
36
  var workflows = require('@mastra/server/handlers/workflows');
34
37
 
35
38
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
36
39
 
37
40
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
41
+ var util__default = /*#__PURE__*/_interopDefault(util);
38
42
 
39
43
  // src/server/index.ts
40
44
  var RequestError = class extends Error {
@@ -159,27 +163,48 @@ Object.setPrototypeOf(requestPrototype, Request.prototype);
159
163
  var newRequest = (incoming, defaultHostname) => {
160
164
  const req = Object.create(requestPrototype);
161
165
  req[incomingKey] = incoming;
166
+ const incomingUrl = incoming.url || "";
167
+ if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
168
+ (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
169
+ if (incoming instanceof http2.Http2ServerRequest) {
170
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
171
+ }
172
+ try {
173
+ const url2 = new URL(incomingUrl);
174
+ req[urlKey] = url2.href;
175
+ } catch (e2) {
176
+ throw new RequestError("Invalid absolute URL", { cause: e2 });
177
+ }
178
+ return req;
179
+ }
162
180
  const host = (incoming instanceof http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
163
181
  if (!host) {
164
182
  throw new RequestError("Missing host header");
165
183
  }
166
- const url = new URL(
167
- `${incoming instanceof http2.Http2ServerRequest || incoming.socket && incoming.socket.encrypted ? "https" : "http"}://${host}${incoming.url}`
168
- );
184
+ let scheme;
185
+ if (incoming instanceof http2.Http2ServerRequest) {
186
+ scheme = incoming.scheme;
187
+ if (!(scheme === "http" || scheme === "https")) {
188
+ throw new RequestError("Unsupported scheme");
189
+ }
190
+ } else {
191
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
192
+ }
193
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
169
194
  if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
170
195
  throw new RequestError("Invalid host header");
171
196
  }
172
197
  req[urlKey] = url.href;
173
198
  return req;
174
199
  };
175
- function writeFromReadableStream(stream3, writable) {
176
- if (stream3.locked) {
200
+ function writeFromReadableStream(stream4, writable) {
201
+ if (stream4.locked) {
177
202
  throw new TypeError("ReadableStream is locked.");
178
203
  } else if (writable.destroyed) {
179
- stream3.cancel();
204
+ stream4.cancel();
180
205
  return;
181
206
  }
182
- const reader = stream3.getReader();
207
+ const reader = stream4.getReader();
183
208
  writable.on("close", cancel);
184
209
  writable.on("error", cancel);
185
210
  reader.read().then(flow, cancel);
@@ -377,7 +402,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
377
402
  const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
378
403
  const internalBody = getInternalBody(res);
379
404
  if (internalBody) {
380
- const { length, source, stream: stream3 } = internalBody;
405
+ const { length, source, stream: stream4 } = internalBody;
381
406
  if (source instanceof Uint8Array && source.byteLength !== length) ; else {
382
407
  if (length) {
383
408
  resHeaderRecord["content-length"] = length;
@@ -388,7 +413,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
388
413
  } else if (source instanceof Blob) {
389
414
  outgoing.end(new Uint8Array(await source.arrayBuffer()));
390
415
  } else {
391
- await writeFromReadableStream(stream3, outgoing);
416
+ await writeFromReadableStream(stream4, outgoing);
392
417
  }
393
418
  return;
394
419
  }
@@ -461,7 +486,7 @@ var getRequestListener = (fetchCallback, options = {}) => {
461
486
  }
462
487
  }
463
488
  try {
464
- return responseViaResponseObject(res, outgoing, options);
489
+ return await responseViaResponseObject(res, outgoing, options);
465
490
  } catch (e2) {
466
491
  return handleResponseError(e2, outgoing);
467
492
  }
@@ -492,18 +517,18 @@ var ENCODINGS = {
492
517
  gzip: ".gz"
493
518
  };
494
519
  var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
495
- var createStreamBody = (stream3) => {
520
+ var createStreamBody = (stream4) => {
496
521
  const body = new ReadableStream({
497
522
  start(controller) {
498
- stream3.on("data", (chunk) => {
523
+ stream4.on("data", (chunk) => {
499
524
  controller.enqueue(chunk);
500
525
  });
501
- stream3.on("end", () => {
526
+ stream4.on("end", () => {
502
527
  controller.close();
503
528
  });
504
529
  },
505
530
  cancel() {
506
- stream3.destroy();
531
+ stream4.destroy();
507
532
  }
508
533
  });
509
534
  return body;
@@ -599,10 +624,10 @@ var serveStatic = (options = { root: "" }) => {
599
624
  end = size - 1;
600
625
  }
601
626
  const chunksize = end - start + 1;
602
- const stream3 = fs.createReadStream(path, { start, end });
627
+ const stream4 = fs.createReadStream(path, { start, end });
603
628
  c2.header("Content-Length", chunksize.toString());
604
629
  c2.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
605
- return c2.body(createStreamBody(stream3), 206);
630
+ return c2.body(createStreamBody(stream4), 206);
606
631
  };
607
632
  };
608
633
  var RENDER_TYPE = {
@@ -723,7 +748,7 @@ var middleware = (options) => async (c2) => {
723
748
  );
724
749
  };
725
750
 
726
- // ../../node_modules/.pnpm/hono-openapi@0.4.6_hono@4.7.4_openapi-types@12.1.3_zod@3.24.3/node_modules/hono-openapi/utils.js
751
+ // ../../node_modules/.pnpm/hono-openapi@0.4.6_hono@4.7.7_openapi-types@12.1.3_zod@3.24.4/node_modules/hono-openapi/utils.js
727
752
  var e = Symbol("openapi");
728
753
  var s2 = ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
729
754
  var n = (e2) => e2.charAt(0).toUpperCase() + e2.slice(1);
@@ -849,6 +874,59 @@ async function x(e2, t2, s3 = {}) {
849
874
  }
850
875
  return { docs: o2, components: n2 };
851
876
  }
877
+ async function getAgentCardByIdHandler(c2) {
878
+ const mastra = c2.get("mastra");
879
+ const agentId = c2.req.param("agentId");
880
+ const runtimeContext = c2.get("runtimeContext");
881
+ const result = await a2a.getAgentCardByIdHandler({
882
+ mastra,
883
+ agentId,
884
+ runtimeContext
885
+ });
886
+ return c2.json(result);
887
+ }
888
+ async function getAgentExecutionHandler(c2) {
889
+ const mastra = c2.get("mastra");
890
+ const agentId = c2.req.param("agentId");
891
+ const runtimeContext = c2.get("runtimeContext");
892
+ const logger2 = mastra.getLogger();
893
+ const body = await c2.req.json();
894
+ if (!["tasks/send", "tasks/sendSubscribe", "tasks/get", "tasks/cancel"].includes(body.method)) {
895
+ return c2.json({ error: { message: `Unsupported method: ${body.method}`, code: "invalid_method" } }, 400);
896
+ }
897
+ const result = await a2a.getAgentExecutionHandler({
898
+ mastra,
899
+ agentId,
900
+ runtimeContext,
901
+ requestId: crypto.randomUUID(),
902
+ method: body.method,
903
+ params: body.params,
904
+ logger: logger2
905
+ });
906
+ if (body.method === "tasks/sendSubscribe") {
907
+ return streaming.stream(
908
+ c2,
909
+ async (stream4) => {
910
+ try {
911
+ stream4.onAbort(() => {
912
+ if (!result.locked) {
913
+ return result.cancel();
914
+ }
915
+ });
916
+ for await (const chunk of result) {
917
+ await stream4.write(JSON.stringify(chunk) + "");
918
+ }
919
+ } catch (err) {
920
+ logger2.error("Error in tasks/sendSubscribe stream: " + err?.message);
921
+ }
922
+ },
923
+ async (err) => {
924
+ logger2.error("Error in tasks/sendSubscribe stream: " + err?.message);
925
+ }
926
+ );
927
+ }
928
+ return c2.json(result);
929
+ }
852
930
  function handleError(error, defaultMessage) {
853
931
  const apiError = error;
854
932
  throw new httpException.HTTPException(apiError.status || 500, {
@@ -949,93 +1027,2010 @@ async function setAgentInstructionsHandler(c2) {
949
1027
  if (!agentId || !instructions) {
950
1028
  return c2.json({ error: "Missing required fields" }, 400);
951
1029
  }
952
- const mastra = c2.get("mastra");
953
- const agent = mastra.getAgent(agentId);
954
- if (!agent) {
955
- return c2.json({ error: "Agent not found" }, 404);
1030
+ const mastra = c2.get("mastra");
1031
+ const agent = mastra.getAgent(agentId);
1032
+ if (!agent) {
1033
+ return c2.json({ error: "Agent not found" }, 404);
1034
+ }
1035
+ agent.__updateInstructions(instructions);
1036
+ return c2.json(
1037
+ {
1038
+ instructions
1039
+ },
1040
+ 200
1041
+ );
1042
+ } catch (error) {
1043
+ return handleError(error, "Error setting agent instructions");
1044
+ }
1045
+ }
1046
+
1047
+ // src/server/handlers/client.ts
1048
+ var clients = /* @__PURE__ */ new Set();
1049
+ function handleClientsRefresh(c2) {
1050
+ const stream4 = new ReadableStream({
1051
+ start(controller) {
1052
+ clients.add(controller);
1053
+ controller.enqueue("data: connected\n\n");
1054
+ c2.req.raw.signal.addEventListener("abort", () => {
1055
+ clients.delete(controller);
1056
+ });
1057
+ }
1058
+ });
1059
+ return new Response(stream4, {
1060
+ headers: {
1061
+ "Content-Type": "text/event-stream",
1062
+ "Cache-Control": "no-cache",
1063
+ Connection: "keep-alive",
1064
+ "Access-Control-Allow-Origin": "*"
1065
+ }
1066
+ });
1067
+ }
1068
+ function handleTriggerClientsRefresh(c2) {
1069
+ clients.forEach((controller) => {
1070
+ try {
1071
+ controller.enqueue("data: refresh\n\n");
1072
+ } catch {
1073
+ clients.delete(controller);
1074
+ }
1075
+ });
1076
+ return c2.json({ success: true, clients: clients.size });
1077
+ }
1078
+ async function getLogsHandler(c2) {
1079
+ try {
1080
+ const mastra = c2.get("mastra");
1081
+ const transportId = c2.req.query("transportId");
1082
+ const logs$1 = await logs.getLogsHandler({
1083
+ mastra,
1084
+ transportId
1085
+ });
1086
+ return c2.json(logs$1);
1087
+ } catch (error) {
1088
+ return handleError(error, "Error getting logs");
1089
+ }
1090
+ }
1091
+ async function getLogsByRunIdHandler(c2) {
1092
+ try {
1093
+ const mastra = c2.get("mastra");
1094
+ const runId = c2.req.param("runId");
1095
+ const transportId = c2.req.query("transportId");
1096
+ const logs$1 = await logs.getLogsByRunIdHandler({
1097
+ mastra,
1098
+ runId,
1099
+ transportId
1100
+ });
1101
+ return c2.json(logs$1);
1102
+ } catch (error) {
1103
+ return handleError(error, "Error getting logs by run ID");
1104
+ }
1105
+ }
1106
+ async function getLogTransports(c2) {
1107
+ try {
1108
+ const mastra = c2.get("mastra");
1109
+ const result = await logs.getLogTransports({
1110
+ mastra
1111
+ });
1112
+ return c2.json(result);
1113
+ } catch (error) {
1114
+ return handleError(error, "Error getting log Transports");
1115
+ }
1116
+ }
1117
+ var classRegExp = /^([A-Z][a-z0-9]*)+$/;
1118
+ var kTypes = [
1119
+ "string",
1120
+ "function",
1121
+ "number",
1122
+ "object",
1123
+ // Accept 'Function' and 'Object' as alternative to the lower cased version.
1124
+ "Function",
1125
+ "Object",
1126
+ "boolean",
1127
+ "bigint",
1128
+ "symbol"
1129
+ ];
1130
+ function determineSpecificType(value) {
1131
+ if (value == null) {
1132
+ return "" + value;
1133
+ }
1134
+ if (typeof value === "function" && value.name) {
1135
+ return `function ${value.name}`;
1136
+ }
1137
+ if (typeof value === "object") {
1138
+ if (value.constructor?.name) {
1139
+ return `an instance of ${value.constructor.name}`;
1140
+ }
1141
+ return `${util__default.default.inspect(value, { depth: -1 })}`;
1142
+ }
1143
+ let inspected = util__default.default.inspect(value, { colors: false });
1144
+ if (inspected.length > 28) {
1145
+ inspected = `${inspected.slice(0, 25)}...`;
1146
+ }
1147
+ return `type ${typeof value} (${inspected})`;
1148
+ }
1149
+ var ERR_HTTP_BODY_NOT_ALLOWED = class extends Error {
1150
+ constructor() {
1151
+ super("Adding content for this request method or response status is not allowed.");
1152
+ }
1153
+ };
1154
+ var ERR_HTTP_CONTENT_LENGTH_MISMATCH = class extends Error {
1155
+ constructor(actual, expected) {
1156
+ super(`Response body's content-length of ${actual} byte(s) does not match the content-length of ${expected} byte(s) set in header`);
1157
+ }
1158
+ };
1159
+ var ERR_HTTP_HEADERS_SENT = class extends Error {
1160
+ constructor(arg) {
1161
+ super(`Cannot ${arg} headers after they are sent to the client`);
1162
+ }
1163
+ };
1164
+ var ERR_INVALID_ARG_VALUE = class extends TypeError {
1165
+ constructor(name, value, reason = "is invalid") {
1166
+ let inspected = util__default.default.inspect(value);
1167
+ if (inspected.length > 128) {
1168
+ inspected = `${inspected.slice(0, 128)}...`;
1169
+ }
1170
+ const type = name.includes(".") ? "property" : "argument";
1171
+ super(`The ${type} '${name}' ${reason}. Received ${inspected}`);
1172
+ }
1173
+ };
1174
+ var ERR_INVALID_CHAR = class extends TypeError {
1175
+ constructor(name, field) {
1176
+ let msg = `Invalid character in ${name}`;
1177
+ if (field !== void 0) {
1178
+ msg += ` ["${field}"]`;
1179
+ }
1180
+ super(msg);
1181
+ }
1182
+ };
1183
+ var ERR_HTTP_INVALID_HEADER_VALUE = class extends TypeError {
1184
+ constructor(value, name) {
1185
+ super(`Invalid value "${value}" for header "${name}"`);
1186
+ }
1187
+ };
1188
+ var ERR_HTTP_INVALID_STATUS_CODE = class extends RangeError {
1189
+ originalStatusCode;
1190
+ constructor(originalStatusCode) {
1191
+ super(`Invalid status code: ${originalStatusCode}`);
1192
+ this.originalStatusCode = originalStatusCode;
1193
+ }
1194
+ };
1195
+ var ERR_HTTP_TRAILER_INVALID = class extends Error {
1196
+ constructor() {
1197
+ super(`Trailers are invalid with this transfer encoding`);
1198
+ }
1199
+ };
1200
+ var ERR_INVALID_ARG_TYPE = class extends TypeError {
1201
+ constructor(name, expected, actual) {
1202
+ if (!Array.isArray(expected)) {
1203
+ expected = [expected];
1204
+ }
1205
+ let msg = "The ";
1206
+ if (name.endsWith(" argument")) {
1207
+ msg += `${name} `;
1208
+ } else {
1209
+ const type = name.includes(".") ? "property" : "argument";
1210
+ msg += `"${name}" ${type} `;
1211
+ }
1212
+ msg += "must be ";
1213
+ const types = [];
1214
+ const instances = [];
1215
+ const other = [];
1216
+ for (const value of expected) {
1217
+ if (kTypes.includes(value)) {
1218
+ types.push(value.toLowerCase());
1219
+ } else if (classRegExp.exec(value) !== null) {
1220
+ instances.push(value);
1221
+ } else {
1222
+ other.push(value);
1223
+ }
1224
+ }
1225
+ if (instances.length > 0) {
1226
+ const pos = types.indexOf("object");
1227
+ if (pos !== -1) {
1228
+ types.splice(pos, 1);
1229
+ instances.push("Object");
1230
+ }
1231
+ }
1232
+ if (types.length > 0) {
1233
+ if (types.length > 2) {
1234
+ const last = types.pop();
1235
+ msg += `one of type ${types.join(", ")}, or ${last}`;
1236
+ } else if (types.length === 2) {
1237
+ msg += `one of type ${types[0]} or ${types[1]}`;
1238
+ } else {
1239
+ msg += `of type ${types[0]}`;
1240
+ }
1241
+ if (instances.length > 0 || other.length > 0)
1242
+ msg += " or ";
1243
+ }
1244
+ if (instances.length > 0) {
1245
+ if (instances.length > 2) {
1246
+ const last = instances.pop();
1247
+ msg += `an instance of ${instances.join(", ")}, or ${last}`;
1248
+ } else {
1249
+ msg += `an instance of ${instances[0]}`;
1250
+ if (instances.length === 2) {
1251
+ msg += ` or ${instances[1]}`;
1252
+ }
1253
+ }
1254
+ if (other.length > 0)
1255
+ msg += " or ";
1256
+ }
1257
+ if (other.length > 0) {
1258
+ if (other.length > 2) {
1259
+ const last = other.pop();
1260
+ msg += `one of ${other.join(", ")}, or ${last}`;
1261
+ } else if (other.length === 2) {
1262
+ msg += `one of ${other[0]} or ${other[1]}`;
1263
+ } else {
1264
+ if (other[0].toLowerCase() !== other[0])
1265
+ msg += "an ";
1266
+ msg += `${other[0]}`;
1267
+ }
1268
+ }
1269
+ msg += `. Received ${determineSpecificType(actual)}`;
1270
+ super(msg);
1271
+ }
1272
+ };
1273
+ var ERR_INVALID_HTTP_TOKEN = class extends TypeError {
1274
+ constructor(name, field) {
1275
+ super(`${name} must be a valid HTTP token ["${field}"]`);
1276
+ }
1277
+ };
1278
+ var ERR_METHOD_NOT_IMPLEMENTED = class extends Error {
1279
+ constructor(methodName) {
1280
+ super(`The ${methodName} method is not implemented`);
1281
+ }
1282
+ };
1283
+ var ERR_STREAM_ALREADY_FINISHED = class extends Error {
1284
+ constructor(methodName) {
1285
+ super(`Cannot call ${methodName} after a stream was finished`);
1286
+ }
1287
+ };
1288
+ var ERR_STREAM_CANNOT_PIPE = class extends Error {
1289
+ constructor() {
1290
+ super(`Cannot pipe, not readable`);
1291
+ }
1292
+ };
1293
+ var ERR_STREAM_DESTROYED = class extends Error {
1294
+ constructor(methodName) {
1295
+ super(`Cannot call ${methodName} after a stream was destroyed`);
1296
+ }
1297
+ };
1298
+ var ERR_STREAM_NULL_VALUES = class extends TypeError {
1299
+ constructor() {
1300
+ super(`May not write null values to stream`);
1301
+ }
1302
+ };
1303
+ var ERR_STREAM_WRITE_AFTER_END = class extends Error {
1304
+ constructor() {
1305
+ super(`write after end`);
1306
+ }
1307
+ };
1308
+
1309
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/http-incoming.js
1310
+ var kHeaders = Symbol("kHeaders");
1311
+ var kHeadersDistinct = Symbol("kHeadersDistinct");
1312
+ var kHeadersCount = Symbol("kHeadersCount");
1313
+ var kTrailers = Symbol("kTrailers");
1314
+ var kTrailersDistinct = Symbol("kTrailersDistinct");
1315
+ var kTrailersCount = Symbol("kTrailersCount");
1316
+ var FetchIncomingMessage = class extends stream.Readable {
1317
+ get socket() {
1318
+ return null;
1319
+ }
1320
+ set socket(_val) {
1321
+ throw new ERR_METHOD_NOT_IMPLEMENTED("socket");
1322
+ }
1323
+ httpVersionMajor;
1324
+ httpVersionMinor;
1325
+ httpVersion;
1326
+ complete = false;
1327
+ [kHeaders] = null;
1328
+ [kHeadersDistinct] = null;
1329
+ [kHeadersCount] = 0;
1330
+ rawHeaders = [];
1331
+ [kTrailers] = null;
1332
+ [kTrailersDistinct] = null;
1333
+ [kTrailersCount] = 0;
1334
+ rawTrailers = [];
1335
+ joinDuplicateHeaders = false;
1336
+ aborted = false;
1337
+ upgrade = false;
1338
+ // request (server) only
1339
+ url = "";
1340
+ method;
1341
+ // TODO: Support ClientRequest
1342
+ // statusCode = null;
1343
+ // statusMessage = null;
1344
+ // client = socket;
1345
+ _consuming;
1346
+ _dumped;
1347
+ // The underlying ReadableStream
1348
+ _stream = null;
1349
+ constructor() {
1350
+ const streamOptions = {};
1351
+ super(streamOptions);
1352
+ this._readableState.readingMore = true;
1353
+ this._consuming = false;
1354
+ this._dumped = false;
1355
+ }
1356
+ get connection() {
1357
+ return null;
1358
+ }
1359
+ set connection(_socket) {
1360
+ console.error("No support for IncomingMessage.connection");
1361
+ }
1362
+ get headers() {
1363
+ if (!this[kHeaders]) {
1364
+ this[kHeaders] = {};
1365
+ const src = this.rawHeaders;
1366
+ const dst = this[kHeaders];
1367
+ for (let n2 = 0; n2 < this[kHeadersCount]; n2 += 2) {
1368
+ this._addHeaderLine(src[n2], src[n2 + 1], dst);
1369
+ }
1370
+ }
1371
+ return this[kHeaders];
1372
+ }
1373
+ set headers(val) {
1374
+ this[kHeaders] = val;
1375
+ }
1376
+ get headersDistinct() {
1377
+ if (!this[kHeadersDistinct]) {
1378
+ this[kHeadersDistinct] = {};
1379
+ const src = this.rawHeaders;
1380
+ const dst = this[kHeadersDistinct];
1381
+ for (let n2 = 0; n2 < this[kHeadersCount]; n2 += 2) {
1382
+ this._addHeaderLineDistinct(src[n2], src[n2 + 1], dst);
1383
+ }
1384
+ }
1385
+ return this[kHeadersDistinct];
1386
+ }
1387
+ set headersDistinct(val) {
1388
+ this[kHeadersDistinct] = val;
1389
+ }
1390
+ get trailers() {
1391
+ if (!this[kTrailers]) {
1392
+ this[kTrailers] = {};
1393
+ const src = this.rawTrailers;
1394
+ const dst = this[kTrailers];
1395
+ for (let n2 = 0; n2 < this[kTrailersCount]; n2 += 2) {
1396
+ this._addHeaderLine(src[n2], src[n2 + 1], dst);
1397
+ }
1398
+ }
1399
+ return this[kTrailers];
1400
+ }
1401
+ set trailers(val) {
1402
+ this[kTrailers] = val;
1403
+ }
1404
+ get trailersDistinct() {
1405
+ if (!this[kTrailersDistinct]) {
1406
+ this[kTrailersDistinct] = {};
1407
+ const src = this.rawTrailers;
1408
+ const dst = this[kTrailersDistinct];
1409
+ for (let n2 = 0; n2 < this[kTrailersCount]; n2 += 2) {
1410
+ this._addHeaderLineDistinct(src[n2], src[n2 + 1], dst);
1411
+ }
1412
+ }
1413
+ return this[kTrailersDistinct];
1414
+ }
1415
+ set trailersDistinct(val) {
1416
+ this[kTrailersDistinct] = val;
1417
+ }
1418
+ setTimeout(msecs, callback) {
1419
+ return this;
1420
+ }
1421
+ async _read(n2) {
1422
+ if (!this._consuming) {
1423
+ this._readableState.readingMore = false;
1424
+ this._consuming = true;
1425
+ }
1426
+ if (this._stream == null) {
1427
+ this.complete = true;
1428
+ this.push(null);
1429
+ return;
1430
+ }
1431
+ const reader = this._stream.getReader();
1432
+ try {
1433
+ const data = await reader.read();
1434
+ if (data.done) {
1435
+ this.complete = true;
1436
+ this.push(null);
1437
+ } else {
1438
+ this.push(data.value);
1439
+ }
1440
+ } catch (e2) {
1441
+ this.destroy(e2);
1442
+ } finally {
1443
+ reader.releaseLock();
1444
+ }
1445
+ }
1446
+ _destroy(err, cb) {
1447
+ if (!this.readableEnded || !this.complete) {
1448
+ this.aborted = true;
1449
+ this.emit("aborted");
1450
+ }
1451
+ setTimeout(onError, 0, this, err, cb);
1452
+ }
1453
+ _addHeaderLines(headers, n2) {
1454
+ if (headers?.length) {
1455
+ let dest;
1456
+ if (this.complete) {
1457
+ this.rawTrailers = headers;
1458
+ this[kTrailersCount] = n2;
1459
+ dest = this[kTrailers];
1460
+ } else {
1461
+ this.rawHeaders = headers;
1462
+ this[kHeadersCount] = n2;
1463
+ dest = this[kHeaders];
1464
+ }
1465
+ if (dest) {
1466
+ for (let i2 = 0; i2 < n2; i2 += 2) {
1467
+ this._addHeaderLine(headers[i2], headers[i2 + 1], dest);
1468
+ }
1469
+ }
1470
+ }
1471
+ }
1472
+ // Add the given (field, value) pair to the message
1473
+ //
1474
+ // Per RFC2616, section 4.2 it is acceptable to join multiple instances of the
1475
+ // same header with a ', ' if the header in question supports specification of
1476
+ // multiple values this way. The one exception to this is the Cookie header,
1477
+ // which has multiple values joined with a '; ' instead. If a header's values
1478
+ // cannot be joined in either of these ways, we declare the first instance the
1479
+ // winner and drop the second. Extended header fields (those beginning with
1480
+ // 'x-') are always joined.
1481
+ _addHeaderLine(field, value, dest) {
1482
+ field = matchKnownFields(field);
1483
+ const flag = field.charCodeAt(0);
1484
+ if (flag === 0 || flag === 2) {
1485
+ field = field.slice(1);
1486
+ if (typeof dest[field] === "string") {
1487
+ dest[field] += (flag === 0 ? ", " : "; ") + value;
1488
+ } else {
1489
+ dest[field] = value;
1490
+ }
1491
+ } else if (flag === 1) {
1492
+ if (dest["set-cookie"] !== void 0) {
1493
+ dest["set-cookie"].push(value);
1494
+ } else {
1495
+ dest["set-cookie"] = [value];
1496
+ }
1497
+ } else if (this.joinDuplicateHeaders) {
1498
+ if (dest[field] === void 0) {
1499
+ dest[field] = value;
1500
+ } else {
1501
+ dest[field] += ", " + value;
1502
+ }
1503
+ } else if (dest[field] === void 0) {
1504
+ dest[field] = value;
1505
+ }
1506
+ }
1507
+ _addHeaderLineDistinct(field, value, dest) {
1508
+ field = field.toLowerCase();
1509
+ if (!dest[field]) {
1510
+ dest[field] = [value];
1511
+ } else {
1512
+ dest[field].push(value);
1513
+ }
1514
+ }
1515
+ // Call this instead of resume() if we want to just
1516
+ // dump all the data to /dev/null
1517
+ _dump() {
1518
+ if (!this._dumped) {
1519
+ this._dumped = true;
1520
+ this.removeAllListeners("data");
1521
+ this.resume();
1522
+ }
1523
+ }
1524
+ };
1525
+ function matchKnownFields(field, lowercased = false) {
1526
+ switch (field.length) {
1527
+ case 3:
1528
+ if (field === "Age" || field === "age")
1529
+ return "age";
1530
+ break;
1531
+ case 4:
1532
+ if (field === "Host" || field === "host")
1533
+ return "host";
1534
+ if (field === "From" || field === "from")
1535
+ return "from";
1536
+ if (field === "ETag" || field === "etag")
1537
+ return "etag";
1538
+ if (field === "Date" || field === "date")
1539
+ return "\0date";
1540
+ if (field === "Vary" || field === "vary")
1541
+ return "\0vary";
1542
+ break;
1543
+ case 6:
1544
+ if (field === "Server" || field === "server")
1545
+ return "server";
1546
+ if (field === "Cookie" || field === "cookie")
1547
+ return "cookie";
1548
+ if (field === "Origin" || field === "origin")
1549
+ return "\0origin";
1550
+ if (field === "Expect" || field === "expect")
1551
+ return "\0expect";
1552
+ if (field === "Accept" || field === "accept")
1553
+ return "\0accept";
1554
+ break;
1555
+ case 7:
1556
+ if (field === "Referer" || field === "referer")
1557
+ return "referer";
1558
+ if (field === "Expires" || field === "expires")
1559
+ return "expires";
1560
+ if (field === "Upgrade" || field === "upgrade")
1561
+ return "\0upgrade";
1562
+ break;
1563
+ case 8:
1564
+ if (field === "Location" || field === "location")
1565
+ return "location";
1566
+ if (field === "If-Match" || field === "if-match")
1567
+ return "\0if-match";
1568
+ break;
1569
+ case 10:
1570
+ if (field === "User-Agent" || field === "user-agent")
1571
+ return "user-agent";
1572
+ if (field === "Set-Cookie" || field === "set-cookie")
1573
+ return "";
1574
+ if (field === "Connection" || field === "connection")
1575
+ return "\0connection";
1576
+ break;
1577
+ case 11:
1578
+ if (field === "Retry-After" || field === "retry-after")
1579
+ return "retry-after";
1580
+ break;
1581
+ case 12:
1582
+ if (field === "Content-Type" || field === "content-type")
1583
+ return "content-type";
1584
+ if (field === "Max-Forwards" || field === "max-forwards")
1585
+ return "max-forwards";
1586
+ break;
1587
+ case 13:
1588
+ if (field === "Authorization" || field === "authorization")
1589
+ return "authorization";
1590
+ if (field === "Last-Modified" || field === "last-modified")
1591
+ return "last-modified";
1592
+ if (field === "Cache-Control" || field === "cache-control")
1593
+ return "\0cache-control";
1594
+ if (field === "If-None-Match" || field === "if-none-match")
1595
+ return "\0if-none-match";
1596
+ break;
1597
+ case 14:
1598
+ if (field === "Content-Length" || field === "content-length")
1599
+ return "content-length";
1600
+ break;
1601
+ case 15:
1602
+ if (field === "Accept-Encoding" || field === "accept-encoding")
1603
+ return "\0accept-encoding";
1604
+ if (field === "Accept-Language" || field === "accept-language")
1605
+ return "\0accept-language";
1606
+ if (field === "X-Forwarded-For" || field === "x-forwarded-for")
1607
+ return "\0x-forwarded-for";
1608
+ break;
1609
+ case 16:
1610
+ if (field === "Content-Encoding" || field === "content-encoding")
1611
+ return "\0content-encoding";
1612
+ if (field === "X-Forwarded-Host" || field === "x-forwarded-host")
1613
+ return "\0x-forwarded-host";
1614
+ break;
1615
+ case 17:
1616
+ if (field === "If-Modified-Since" || field === "if-modified-since")
1617
+ return "if-modified-since";
1618
+ if (field === "Transfer-Encoding" || field === "transfer-encoding")
1619
+ return "\0transfer-encoding";
1620
+ if (field === "X-Forwarded-Proto" || field === "x-forwarded-proto")
1621
+ return "\0x-forwarded-proto";
1622
+ break;
1623
+ case 19:
1624
+ if (field === "Proxy-Authorization" || field === "proxy-authorization")
1625
+ return "proxy-authorization";
1626
+ if (field === "If-Unmodified-Since" || field === "if-unmodified-since")
1627
+ return "if-unmodified-since";
1628
+ break;
1629
+ }
1630
+ if (lowercased) {
1631
+ return "\0" + field;
1632
+ }
1633
+ return matchKnownFields(field.toLowerCase(), true);
1634
+ }
1635
+ function onError(self, error, cb) {
1636
+ if (self.listenerCount("error") === 0) {
1637
+ cb();
1638
+ } else {
1639
+ cb(error);
1640
+ }
1641
+ }
1642
+
1643
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/utils/types.js
1644
+ function validateString(value, name) {
1645
+ if (typeof value !== "string")
1646
+ throw new ERR_INVALID_ARG_TYPE(name, "string", value);
1647
+ }
1648
+ var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
1649
+ function validateLinkHeaderFormat(value, name) {
1650
+ if (typeof value === "undefined" || !linkValueRegExp.exec(value)) {
1651
+ throw new ERR_INVALID_ARG_VALUE(name, value, 'must be an array or string of format "</styles.css>; rel=preload; as=style"');
1652
+ }
1653
+ }
1654
+ function validateLinkHeaderValue(hints) {
1655
+ if (typeof hints === "string") {
1656
+ validateLinkHeaderFormat(hints, "hints");
1657
+ return hints;
1658
+ } else if (Array.isArray(hints)) {
1659
+ const hintsLength = hints.length;
1660
+ let result = "";
1661
+ if (hintsLength === 0) {
1662
+ return result;
1663
+ }
1664
+ for (let i2 = 0; i2 < hintsLength; i2++) {
1665
+ const link = hints[i2];
1666
+ validateLinkHeaderFormat(link, "hints");
1667
+ result += link;
1668
+ if (i2 !== hintsLength - 1) {
1669
+ result += ", ";
1670
+ }
1671
+ }
1672
+ return result;
1673
+ }
1674
+ throw new ERR_INVALID_ARG_VALUE("hints", hints, 'must be an array or string of format "</styles.css>; rel=preload; as=style"');
1675
+ }
1676
+ function isUint8Array(value) {
1677
+ return value != null && value[Symbol.toStringTag] === "Uint8Array";
1678
+ }
1679
+
1680
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/internal-http.js
1681
+ var kNeedDrain = Symbol("kNeedDrain");
1682
+ var kOutHeaders = Symbol("kOutHeaders");
1683
+ function utcDate() {
1684
+ return (/* @__PURE__ */ new Date()).toUTCString();
1685
+ }
1686
+
1687
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/internal-streams-state.js
1688
+ function getDefaultHighWaterMark(objectMode) {
1689
+ return objectMode ? 16 : 64 * 1024;
1690
+ }
1691
+
1692
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/http-common.js
1693
+ var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
1694
+ function checkIsHttpToken(val) {
1695
+ return tokenRegExp.test(val);
1696
+ }
1697
+ var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
1698
+ function checkInvalidHeaderChar(val) {
1699
+ return headerCharRegex.test(val);
1700
+ }
1701
+ var chunkExpression = /(?:^|\W)chunked(?:$|\W)/i;
1702
+ var kCorked = Symbol("corked");
1703
+ var kChunkedBuffer = Symbol("kChunkedBuffer");
1704
+ var kChunkedLength = Symbol("kChunkedLength");
1705
+ var kUniqueHeaders = Symbol("kUniqueHeaders");
1706
+ var kBytesWritten = Symbol("kBytesWritten");
1707
+ var kErrored = Symbol("errored");
1708
+ var kHighWaterMark = Symbol("kHighWaterMark");
1709
+ var kRejectNonStandardBodyWrites = Symbol("kRejectNonStandardBodyWrites");
1710
+ var nop = () => {
1711
+ };
1712
+ var RE_CONN_CLOSE = /(?:^|\W)close(?:$|\W)/i;
1713
+ function isCookieField(s3) {
1714
+ return s3.length === 6 && s3.toLowerCase() === "cookie";
1715
+ }
1716
+ function isContentDispositionField(s3) {
1717
+ return s3.length === 19 && s3.toLowerCase() === "content-disposition";
1718
+ }
1719
+ var WrittenDataBuffer = class {
1720
+ [kCorked] = 0;
1721
+ [kHighWaterMark] = getDefaultHighWaterMark();
1722
+ entries = [];
1723
+ onWrite;
1724
+ constructor(params = {}) {
1725
+ this.onWrite = params.onWrite;
1726
+ }
1727
+ write(data, encoding, callback) {
1728
+ this.entries.push({
1729
+ data,
1730
+ length: data.length,
1731
+ encoding,
1732
+ callback,
1733
+ written: false
1734
+ });
1735
+ this._flush();
1736
+ return true;
1737
+ }
1738
+ cork() {
1739
+ this[kCorked]++;
1740
+ }
1741
+ uncork() {
1742
+ this[kCorked]--;
1743
+ this._flush();
1744
+ }
1745
+ _flush() {
1746
+ if (this[kCorked] <= 0) {
1747
+ for (const [index, entry] of this.entries.entries()) {
1748
+ if (!entry.written) {
1749
+ entry.written = true;
1750
+ if (this.onWrite != null) {
1751
+ this.onWrite(index, entry);
1752
+ }
1753
+ if (entry.callback != null) {
1754
+ entry.callback.call(void 0);
1755
+ }
1756
+ }
1757
+ }
1758
+ }
1759
+ }
1760
+ get writableLength() {
1761
+ return this.entries.reduce((acc, entry) => {
1762
+ return acc + (entry.written && entry.length ? entry.length : 0);
1763
+ }, 0);
1764
+ }
1765
+ get writableHighWaterMark() {
1766
+ return this[kHighWaterMark];
1767
+ }
1768
+ get writableCorked() {
1769
+ return this[kCorked];
1770
+ }
1771
+ };
1772
+ var FetchOutgoingMessage = class extends stream.Writable {
1773
+ req;
1774
+ outputData;
1775
+ outputSize;
1776
+ // Difference from Node.js -
1777
+ // `writtenHeaderBytes` is the number of bytes the header has taken.
1778
+ // Since Node.js writes both the headers and body into the same outgoing
1779
+ // stream, it helps to keep track of this so that we can skip that many bytes
1780
+ // from the beginning of the stream when providing the outgoing stream.
1781
+ writtenHeaderBytes = 0;
1782
+ _last;
1783
+ chunkedEncoding;
1784
+ shouldKeepAlive;
1785
+ maxRequestsOnConnectionReached;
1786
+ _defaultKeepAlive;
1787
+ useChunkedEncodingByDefault;
1788
+ sendDate;
1789
+ _removedConnection;
1790
+ _removedContLen;
1791
+ _removedTE;
1792
+ strictContentLength;
1793
+ [kBytesWritten];
1794
+ _contentLength;
1795
+ _hasBody;
1796
+ _trailer;
1797
+ [kNeedDrain];
1798
+ finished;
1799
+ _headerSent;
1800
+ [kCorked];
1801
+ [kChunkedBuffer];
1802
+ [kChunkedLength];
1803
+ _closed;
1804
+ // Difference from Node.js -
1805
+ // In Node.js, this is a socket object.
1806
+ // [kSocket]: null;
1807
+ _header;
1808
+ [kOutHeaders];
1809
+ _keepAliveTimeout;
1810
+ _maxRequestsPerSocket;
1811
+ _onPendingData;
1812
+ [kUniqueHeaders];
1813
+ [kErrored];
1814
+ [kHighWaterMark];
1815
+ [kRejectNonStandardBodyWrites];
1816
+ _writtenDataBuffer = new WrittenDataBuffer({
1817
+ onWrite: this._onDataWritten.bind(this)
1818
+ });
1819
+ constructor(req, options) {
1820
+ super();
1821
+ this.req = req;
1822
+ this.outputData = [];
1823
+ this.outputSize = 0;
1824
+ this.destroyed = false;
1825
+ this._last = false;
1826
+ this.chunkedEncoding = false;
1827
+ this.shouldKeepAlive = true;
1828
+ this.maxRequestsOnConnectionReached = false;
1829
+ this._defaultKeepAlive = true;
1830
+ this.useChunkedEncodingByDefault = true;
1831
+ this.sendDate = false;
1832
+ this._removedConnection = false;
1833
+ this._removedContLen = false;
1834
+ this._removedTE = false;
1835
+ this.strictContentLength = false;
1836
+ this[kBytesWritten] = 0;
1837
+ this._contentLength = null;
1838
+ this._hasBody = true;
1839
+ this._trailer = "";
1840
+ this[kNeedDrain] = false;
1841
+ this.finished = false;
1842
+ this._headerSent = false;
1843
+ this[kCorked] = 0;
1844
+ this[kChunkedBuffer] = [];
1845
+ this[kChunkedLength] = 0;
1846
+ this._closed = false;
1847
+ this._header = null;
1848
+ this[kOutHeaders] = null;
1849
+ this._keepAliveTimeout = 0;
1850
+ this._onPendingData = nop;
1851
+ this[kErrored] = null;
1852
+ this[kHighWaterMark] = options?.highWaterMark ?? getDefaultHighWaterMark();
1853
+ this[kRejectNonStandardBodyWrites] = options?.rejectNonStandardBodyWrites ?? false;
1854
+ this[kUniqueHeaders] = null;
1855
+ }
1856
+ _renderHeaders() {
1857
+ if (this._header) {
1858
+ throw new ERR_HTTP_HEADERS_SENT("render");
1859
+ }
1860
+ const headersMap = this[kOutHeaders];
1861
+ const headers = {};
1862
+ if (headersMap !== null) {
1863
+ const keys = Object.keys(headersMap);
1864
+ for (let i2 = 0, l2 = keys.length; i2 < l2; i2++) {
1865
+ const key = keys[i2];
1866
+ headers[headersMap[key][0]] = headersMap[key][1];
1867
+ }
1868
+ }
1869
+ return headers;
1870
+ }
1871
+ cork() {
1872
+ this[kCorked]++;
1873
+ if (this._writtenDataBuffer != null) {
1874
+ this._writtenDataBuffer.cork();
1875
+ }
1876
+ }
1877
+ uncork() {
1878
+ this[kCorked]--;
1879
+ if (this._writtenDataBuffer != null) {
1880
+ this._writtenDataBuffer.uncork();
1881
+ }
1882
+ if (this[kCorked] || this[kChunkedBuffer].length === 0) {
1883
+ return;
1884
+ }
1885
+ const buf = this[kChunkedBuffer];
1886
+ for (const { data, encoding, callback } of buf) {
1887
+ this._send(data ?? "", encoding, callback);
1888
+ }
1889
+ this[kChunkedBuffer].length = 0;
1890
+ this[kChunkedLength] = 0;
1891
+ }
1892
+ setTimeout(msecs, callback) {
1893
+ return this;
1894
+ }
1895
+ destroy(error) {
1896
+ if (this.destroyed) {
1897
+ return this;
1898
+ }
1899
+ this.destroyed = true;
1900
+ this[kErrored] = error;
1901
+ return this;
1902
+ }
1903
+ _send(data, encoding, callback, byteLength) {
1904
+ if (!this._headerSent) {
1905
+ const header = this._header;
1906
+ if (typeof data === "string" && (encoding === "utf8" || encoding === "latin1" || !encoding)) {
1907
+ data = header + data;
1908
+ } else {
1909
+ this.outputData.unshift({
1910
+ data: header,
1911
+ encoding: "latin1",
1912
+ callback: void 0
1913
+ });
1914
+ this.outputSize += header.length;
1915
+ this._onPendingData(header.length);
1916
+ }
1917
+ this._headerSent = true;
1918
+ this.writtenHeaderBytes = header.length;
1919
+ const [statusLine, ...headerLines] = this._header.split("\r\n");
1920
+ const STATUS_LINE_REGEXP = /^HTTP\/1\.1 (?<statusCode>\d+) (?<statusMessage>.*)$/;
1921
+ const statusLineResult = STATUS_LINE_REGEXP.exec(statusLine);
1922
+ if (statusLineResult == null) {
1923
+ throw new Error("Unexpected! Status line was " + statusLine);
1924
+ }
1925
+ const { statusCode: statusCodeText, statusMessage } = statusLineResult.groups ?? {};
1926
+ const statusCode = parseInt(statusCodeText, 10);
1927
+ const headers = [];
1928
+ for (const headerLine of headerLines) {
1929
+ if (headerLine !== "") {
1930
+ const pos = headerLine.indexOf(": ");
1931
+ const k = headerLine.slice(0, pos);
1932
+ const v = headerLine.slice(pos + 2);
1933
+ headers.push([k, v]);
1934
+ }
1935
+ }
1936
+ const event = {
1937
+ statusCode,
1938
+ statusMessage,
1939
+ headers
1940
+ };
1941
+ this.emit("_headersSent", event);
1942
+ }
1943
+ return this._writeRaw(data, encoding, callback, byteLength);
1944
+ }
1945
+ _writeRaw(data, encoding, callback, size) {
1946
+ if (typeof encoding === "function") {
1947
+ callback = encoding;
1948
+ encoding = null;
1949
+ }
1950
+ if (this._writtenDataBuffer != null) {
1951
+ if (this.outputData.length) {
1952
+ this._flushOutput(this._writtenDataBuffer);
1953
+ }
1954
+ return this._writtenDataBuffer.write(data, encoding, callback);
1955
+ }
1956
+ this.outputData.push({ data, encoding, callback });
1957
+ this.outputSize += data.length;
1958
+ this._onPendingData(data.length);
1959
+ return this.outputSize < this[kHighWaterMark];
1960
+ }
1961
+ _onDataWritten(index, entry) {
1962
+ const event = { index, entry };
1963
+ this.emit("_dataWritten", event);
1964
+ }
1965
+ _storeHeader(firstLine, headers) {
1966
+ const state = {
1967
+ connection: false,
1968
+ contLen: false,
1969
+ te: false,
1970
+ date: false,
1971
+ expect: false,
1972
+ trailer: false,
1973
+ header: firstLine
1974
+ };
1975
+ if (headers) {
1976
+ if (headers === this[kOutHeaders]) {
1977
+ for (const key in headers) {
1978
+ const entry = headers[key];
1979
+ processHeader(this, state, entry[0], entry[1], false);
1980
+ }
1981
+ } else if (Array.isArray(headers)) {
1982
+ if (headers.length && Array.isArray(headers[0])) {
1983
+ for (let i2 = 0; i2 < headers.length; i2++) {
1984
+ const entry = headers[i2];
1985
+ processHeader(this, state, entry[0], entry[1], true);
1986
+ }
1987
+ } else {
1988
+ if (headers.length % 2 !== 0) {
1989
+ throw new ERR_INVALID_ARG_VALUE("headers", headers);
1990
+ }
1991
+ for (let n2 = 0; n2 < headers.length; n2 += 2) {
1992
+ processHeader(this, state, headers[n2], headers[n2 + 1], true);
1993
+ }
1994
+ }
1995
+ } else {
1996
+ for (const key in headers) {
1997
+ if (headers.hasOwnProperty(key)) {
1998
+ const _headers = headers;
1999
+ processHeader(this, state, key, _headers[key], true);
2000
+ }
2001
+ }
2002
+ }
2003
+ }
2004
+ let { header } = state;
2005
+ if (this.sendDate && !state.date) {
2006
+ header += "Date: " + utcDate() + "\r\n";
2007
+ }
2008
+ if (this.chunkedEncoding && (this.statusCode === 204 || this.statusCode === 304)) {
2009
+ this.chunkedEncoding = false;
2010
+ this.shouldKeepAlive = false;
2011
+ }
2012
+ if (this._removedConnection) {
2013
+ this._last = !this.shouldKeepAlive;
2014
+ } else if (!state.connection) {
2015
+ const shouldSendKeepAlive = this.shouldKeepAlive && (state.contLen || this.useChunkedEncodingByDefault);
2016
+ if (shouldSendKeepAlive && this.maxRequestsOnConnectionReached) {
2017
+ header += "Connection: close\r\n";
2018
+ } else if (shouldSendKeepAlive) {
2019
+ header += "Connection: keep-alive\r\n";
2020
+ if (this._keepAliveTimeout && this._defaultKeepAlive) {
2021
+ const timeoutSeconds = Math.floor(this._keepAliveTimeout / 1e3);
2022
+ let max = "";
2023
+ if (this._maxRequestsPerSocket && ~~this._maxRequestsPerSocket > 0) {
2024
+ max = `, max=${this._maxRequestsPerSocket}`;
2025
+ }
2026
+ header += `Keep-Alive: timeout=${timeoutSeconds}${max}\r
2027
+ `;
2028
+ }
2029
+ } else {
2030
+ this._last = true;
2031
+ header += "Connection: close\r\n";
2032
+ }
2033
+ }
2034
+ if (!state.contLen && !state.te) {
2035
+ if (!this._hasBody) {
2036
+ this.chunkedEncoding = false;
2037
+ } else if (!this.useChunkedEncodingByDefault) {
2038
+ this._last = true;
2039
+ } else if (!state.trailer && !this._removedContLen && typeof this._contentLength === "number") {
2040
+ header += "Content-Length: " + this._contentLength + "\r\n";
2041
+ } else if (!this._removedTE) {
2042
+ header += "Transfer-Encoding: chunked\r\n";
2043
+ this.chunkedEncoding = true;
2044
+ } else {
2045
+ this._last = true;
2046
+ }
2047
+ }
2048
+ if (this.chunkedEncoding !== true && state.trailer) {
2049
+ throw new ERR_HTTP_TRAILER_INVALID();
2050
+ }
2051
+ this._header = header + "\r\n";
2052
+ this._headerSent = false;
2053
+ if (state.expect) {
2054
+ this._send("");
2055
+ }
2056
+ }
2057
+ get _headers() {
2058
+ console.warn("DEP0066: OutgoingMessage.prototype._headers is deprecated");
2059
+ return this.getHeaders();
2060
+ }
2061
+ set _headers(val) {
2062
+ console.warn("DEP0066: OutgoingMessage.prototype._headers is deprecated");
2063
+ if (val == null) {
2064
+ this[kOutHeaders] = null;
2065
+ } else if (typeof val === "object") {
2066
+ const headers = this[kOutHeaders] = /* @__PURE__ */ Object.create(null);
2067
+ const keys = Object.keys(val);
2068
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2069
+ const name = keys[i2];
2070
+ headers[name.toLowerCase()] = [name, val[name]];
2071
+ }
2072
+ }
2073
+ }
2074
+ get connection() {
2075
+ return null;
2076
+ }
2077
+ set connection(_socket) {
2078
+ console.error("No support for OutgoingMessage.connection");
2079
+ }
2080
+ get socket() {
2081
+ return null;
2082
+ }
2083
+ set socket(_socket) {
2084
+ console.error("No support for OutgoingMessage.socket");
2085
+ }
2086
+ get _headerNames() {
2087
+ console.warn("DEP0066: OutgoingMessage.prototype._headerNames is deprecated");
2088
+ const headers = this[kOutHeaders];
2089
+ if (headers !== null) {
2090
+ const out = /* @__PURE__ */ Object.create(null);
2091
+ const keys = Object.keys(headers);
2092
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2093
+ const key = keys[i2];
2094
+ const val = headers[key][0];
2095
+ out[key] = val;
2096
+ }
2097
+ return out;
2098
+ }
2099
+ return null;
2100
+ }
2101
+ set _headerNames(val) {
2102
+ console.warn("DEP0066: OutgoingMessage.prototype._headerNames is deprecated");
2103
+ if (typeof val === "object" && val !== null) {
2104
+ const headers = this[kOutHeaders];
2105
+ if (!headers)
2106
+ return;
2107
+ const keys = Object.keys(val);
2108
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2109
+ const header = headers[keys[i2]];
2110
+ if (header)
2111
+ header[0] = val[keys[i2]];
2112
+ }
2113
+ }
2114
+ }
2115
+ setHeader(name, value) {
2116
+ if (this._header) {
2117
+ throw new ERR_HTTP_HEADERS_SENT("set");
2118
+ }
2119
+ validateHeaderName(name);
2120
+ validateHeaderValue(name, value);
2121
+ let headers = this[kOutHeaders];
2122
+ if (headers === null) {
2123
+ this[kOutHeaders] = headers = { __proto__: null };
2124
+ }
2125
+ headers[name.toLowerCase()] = [name, value];
2126
+ return this;
2127
+ }
2128
+ setHeaders(headers) {
2129
+ if (this._header) {
2130
+ throw new ERR_HTTP_HEADERS_SENT("set");
2131
+ }
2132
+ if (!headers || Array.isArray(headers) || typeof headers.keys !== "function" || typeof headers.get !== "function") {
2133
+ throw new ERR_INVALID_ARG_TYPE("headers", ["Headers", "Map"], headers);
2134
+ }
2135
+ const cookies = [];
2136
+ for (const { 0: key, 1: value } of headers) {
2137
+ if (key === "set-cookie") {
2138
+ if (Array.isArray(value)) {
2139
+ cookies.push(...value);
2140
+ } else {
2141
+ cookies.push(value);
2142
+ }
2143
+ continue;
2144
+ }
2145
+ this.setHeader(key, value);
2146
+ }
2147
+ if (cookies.length) {
2148
+ this.setHeader("set-cookie", cookies);
2149
+ }
2150
+ return this;
2151
+ }
2152
+ appendHeader(name, value) {
2153
+ if (this._header) {
2154
+ throw new ERR_HTTP_HEADERS_SENT("append");
2155
+ }
2156
+ validateHeaderName(name);
2157
+ validateHeaderValue(name, value);
2158
+ const field = name.toLowerCase();
2159
+ const headers = this[kOutHeaders];
2160
+ if (headers === null || !headers[field]) {
2161
+ return this.setHeader(name, value);
2162
+ }
2163
+ if (!Array.isArray(headers[field][1])) {
2164
+ headers[field][1] = [headers[field][1]];
2165
+ }
2166
+ const existingValues = headers[field][1];
2167
+ if (Array.isArray(value)) {
2168
+ for (let i2 = 0, length = value.length; i2 < length; i2++) {
2169
+ existingValues.push(value[i2]);
2170
+ }
2171
+ } else {
2172
+ existingValues.push(value);
2173
+ }
2174
+ return this;
2175
+ }
2176
+ getHeader(name) {
2177
+ validateString(name, "name");
2178
+ const headers = this[kOutHeaders];
2179
+ if (headers === null) {
2180
+ return;
2181
+ }
2182
+ const entry = headers[name.toLowerCase()];
2183
+ return entry?.[1];
2184
+ }
2185
+ getHeaderNames() {
2186
+ return this[kOutHeaders] !== null ? Object.keys(this[kOutHeaders]) : [];
2187
+ }
2188
+ getRawHeaderNames() {
2189
+ const headersMap = this[kOutHeaders];
2190
+ if (headersMap === null)
2191
+ return [];
2192
+ const values = Object.values(headersMap);
2193
+ const headers = Array(values.length);
2194
+ for (let i2 = 0, l2 = values.length; i2 < l2; i2++) {
2195
+ headers[i2] = values[i2][0];
2196
+ }
2197
+ return headers;
2198
+ }
2199
+ getHeaders() {
2200
+ const headers = this[kOutHeaders];
2201
+ const ret = { __proto__: null };
2202
+ if (headers) {
2203
+ const keys = Object.keys(headers);
2204
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2205
+ const key = keys[i2];
2206
+ const val = headers[key][1];
2207
+ ret[key] = val;
2208
+ }
2209
+ }
2210
+ return ret;
2211
+ }
2212
+ hasHeader(name) {
2213
+ validateString(name, "name");
2214
+ return this[kOutHeaders] !== null && !!this[kOutHeaders][name.toLowerCase()];
2215
+ }
2216
+ removeHeader(name) {
2217
+ validateString(name, "name");
2218
+ if (this._header) {
2219
+ throw new ERR_HTTP_HEADERS_SENT("remove");
2220
+ }
2221
+ const key = name.toLowerCase();
2222
+ switch (key) {
2223
+ case "connection":
2224
+ this._removedConnection = true;
2225
+ break;
2226
+ case "content-length":
2227
+ this._removedContLen = true;
2228
+ break;
2229
+ case "transfer-encoding":
2230
+ this._removedTE = true;
2231
+ break;
2232
+ case "date":
2233
+ this.sendDate = false;
2234
+ break;
2235
+ }
2236
+ if (this[kOutHeaders] !== null) {
2237
+ delete this[kOutHeaders][key];
2238
+ }
2239
+ }
2240
+ _implicitHeader() {
2241
+ throw new ERR_METHOD_NOT_IMPLEMENTED("_implicitHeader()");
2242
+ }
2243
+ get headersSent() {
2244
+ return !!this._header;
2245
+ }
2246
+ write(chunk, encoding, callback) {
2247
+ if (typeof encoding === "function") {
2248
+ callback = encoding;
2249
+ encoding = null;
2250
+ }
2251
+ const ret = write_(this, chunk, encoding, callback, false);
2252
+ if (!ret) {
2253
+ this[kNeedDrain] = true;
2254
+ }
2255
+ return ret;
2256
+ }
2257
+ addTrailers(headers) {
2258
+ this._trailer = "";
2259
+ const isArray = Array.isArray(headers);
2260
+ const keys = isArray ? [...headers.keys()] : Object.keys(headers);
2261
+ for (let i2 = 0, l2 = keys.length; i2 < l2; i2++) {
2262
+ let field, value;
2263
+ if (isArray) {
2264
+ const _headers = headers;
2265
+ const key = keys[i2];
2266
+ field = _headers[key][0];
2267
+ value = _headers[key][1];
2268
+ } else {
2269
+ const _headers = headers;
2270
+ const key = keys[i2];
2271
+ field = key;
2272
+ value = _headers[key];
2273
+ }
2274
+ validateHeaderName(field, "Trailer name");
2275
+ if (Array.isArray(value) && value.length > 1 && (!this[kUniqueHeaders] || !this[kUniqueHeaders].has(field.toLowerCase()))) {
2276
+ for (let j = 0, l3 = value.length; j < l3; j++) {
2277
+ if (checkInvalidHeaderChar(value[j])) {
2278
+ throw new ERR_INVALID_CHAR("trailer content", field);
2279
+ }
2280
+ this._trailer += field + ": " + value[j] + "\r\n";
2281
+ }
2282
+ } else {
2283
+ if (Array.isArray(value)) {
2284
+ value = value.join("; ");
2285
+ }
2286
+ if (checkInvalidHeaderChar(String(value))) {
2287
+ throw new ERR_INVALID_CHAR("trailer content", field);
2288
+ }
2289
+ this._trailer += field + ": " + value + "\r\n";
2290
+ }
2291
+ }
2292
+ }
2293
+ end(chunk, encoding, callback) {
2294
+ if (typeof chunk === "function") {
2295
+ callback = chunk;
2296
+ chunk = null;
2297
+ encoding = null;
2298
+ } else if (typeof encoding === "function") {
2299
+ callback = encoding;
2300
+ encoding = null;
2301
+ }
2302
+ if (chunk) {
2303
+ if (this.finished) {
2304
+ onError2(this, new ERR_STREAM_WRITE_AFTER_END(), typeof callback !== "function" ? nop : callback);
2305
+ return this;
2306
+ }
2307
+ if (this._writtenDataBuffer != null) {
2308
+ this._writtenDataBuffer.cork();
2309
+ }
2310
+ write_(this, chunk, encoding, null, true);
2311
+ } else if (this.finished) {
2312
+ if (typeof callback === "function") {
2313
+ if (!this.writableFinished) {
2314
+ this.on("finish", callback);
2315
+ } else {
2316
+ callback(new ERR_STREAM_ALREADY_FINISHED("end"));
2317
+ }
2318
+ }
2319
+ return this;
2320
+ } else if (!this._header) {
2321
+ if (this._writtenDataBuffer != null) {
2322
+ this._writtenDataBuffer.cork();
2323
+ }
2324
+ this._contentLength = 0;
2325
+ this._implicitHeader();
2326
+ }
2327
+ if (typeof callback === "function")
2328
+ this.once("finish", callback);
2329
+ if (strictContentLength(this) && this[kBytesWritten] !== this._contentLength) {
2330
+ throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten], this._contentLength);
2331
+ }
2332
+ const finish = onFinish.bind(void 0, this);
2333
+ if (this._hasBody && this.chunkedEncoding) {
2334
+ this._send("", "latin1", finish);
2335
+ } else if (!this._headerSent || this.writableLength || chunk) {
2336
+ this._send("", "latin1", finish);
2337
+ } else {
2338
+ setTimeout(finish, 0);
2339
+ }
2340
+ if (this._writtenDataBuffer != null) {
2341
+ this._writtenDataBuffer.uncork();
2342
+ }
2343
+ this[kCorked] = 1;
2344
+ this.uncork();
2345
+ this.finished = true;
2346
+ if (this.outputData.length === 0 && this._writtenDataBuffer != null) {
2347
+ this._finish();
2348
+ }
2349
+ return this;
2350
+ }
2351
+ _finish() {
2352
+ this.emit("prefinish");
2353
+ }
2354
+ // No _flush() implementation?
2355
+ _flush() {
2356
+ if (this._writtenDataBuffer != null) {
2357
+ const ret = this._flushOutput(this._writtenDataBuffer);
2358
+ if (this.finished) {
2359
+ this._finish();
2360
+ } else if (ret && this[kNeedDrain]) {
2361
+ this[kNeedDrain] = false;
2362
+ this.emit("drain");
2363
+ }
2364
+ }
2365
+ }
2366
+ _flushOutput(dataBuffer) {
2367
+ while (this[kCorked]) {
2368
+ this[kCorked]--;
2369
+ dataBuffer.cork();
2370
+ }
2371
+ const outputLength = this.outputData.length;
2372
+ if (outputLength <= 0) {
2373
+ return void 0;
2374
+ }
2375
+ const outputData = this.outputData;
2376
+ dataBuffer.cork();
2377
+ let ret;
2378
+ for (let i2 = 0; i2 < outputLength; i2++) {
2379
+ const { data, encoding, callback } = outputData[i2];
2380
+ outputData[i2].data = null;
2381
+ ret = dataBuffer.write(data ?? "", encoding, callback);
2382
+ }
2383
+ dataBuffer.uncork();
2384
+ this.outputData = [];
2385
+ this._onPendingData(-this.outputSize);
2386
+ this.outputSize = 0;
2387
+ return ret;
2388
+ }
2389
+ flushHeaders() {
2390
+ if (!this._header) {
2391
+ this._implicitHeader();
2392
+ }
2393
+ this._send("");
2394
+ }
2395
+ pipe(destination) {
2396
+ this.emit("error", new ERR_STREAM_CANNOT_PIPE());
2397
+ return destination;
2398
+ }
2399
+ };
2400
+ function processHeader(self, state, key, value, validate) {
2401
+ if (validate) {
2402
+ validateHeaderName(key);
2403
+ }
2404
+ if (isContentDispositionField(key) && self._contentLength) {
2405
+ if (Array.isArray(value)) {
2406
+ for (let i2 = 0; i2 < value.length; i2++) {
2407
+ value[i2] = String(buffer.Buffer.from(String(value[i2]), "latin1"));
2408
+ }
2409
+ } else {
2410
+ value = String(buffer.Buffer.from(String(value), "latin1"));
2411
+ }
2412
+ }
2413
+ if (Array.isArray(value)) {
2414
+ if ((value.length < 2 || !isCookieField(key)) && (!self[kUniqueHeaders] || !self[kUniqueHeaders].has(key.toLowerCase()))) {
2415
+ for (let i2 = 0; i2 < value.length; i2++) {
2416
+ storeHeader(self, state, key, value[i2], validate);
2417
+ }
2418
+ return;
2419
+ }
2420
+ value = value.join("; ");
2421
+ }
2422
+ storeHeader(self, state, key, String(value), validate);
2423
+ }
2424
+ function storeHeader(self, state, key, value, validate) {
2425
+ if (validate) {
2426
+ validateHeaderValue(key, value);
2427
+ }
2428
+ state.header += key + ": " + value + "\r\n";
2429
+ matchHeader(self, state, key, value);
2430
+ }
2431
+ function validateHeaderName(name, label) {
2432
+ if (typeof name !== "string" || !name || !checkIsHttpToken(name)) {
2433
+ throw new ERR_INVALID_HTTP_TOKEN(label || "Header name", name);
2434
+ }
2435
+ }
2436
+ function validateHeaderValue(name, value) {
2437
+ if (value === void 0) {
2438
+ throw new ERR_HTTP_INVALID_HEADER_VALUE(String(value), name);
2439
+ }
2440
+ if (checkInvalidHeaderChar(String(value))) {
2441
+ throw new ERR_INVALID_CHAR("header content", name);
2442
+ }
2443
+ }
2444
+ function matchHeader(self, state, field, value) {
2445
+ if (field.length < 4 || field.length > 17)
2446
+ return;
2447
+ field = field.toLowerCase();
2448
+ switch (field) {
2449
+ case "connection":
2450
+ state.connection = true;
2451
+ self._removedConnection = false;
2452
+ if (RE_CONN_CLOSE.exec(value) !== null)
2453
+ self._last = true;
2454
+ else
2455
+ self.shouldKeepAlive = true;
2456
+ break;
2457
+ case "transfer-encoding":
2458
+ state.te = true;
2459
+ self._removedTE = false;
2460
+ if (chunkExpression.exec(value) !== null)
2461
+ self.chunkedEncoding = true;
2462
+ break;
2463
+ case "content-length":
2464
+ state.contLen = true;
2465
+ self._contentLength = +value;
2466
+ self._removedContLen = false;
2467
+ break;
2468
+ case "date":
2469
+ case "expect":
2470
+ case "trailer":
2471
+ state[field] = true;
2472
+ break;
2473
+ case "keep-alive":
2474
+ self._defaultKeepAlive = false;
2475
+ break;
2476
+ }
2477
+ }
2478
+ function onError2(msg, err, callback) {
2479
+ if (msg.destroyed) {
2480
+ return;
2481
+ }
2482
+ setTimeout(emitErrorNt, 0, msg, err, callback);
2483
+ }
2484
+ function emitErrorNt(msg, err, callback) {
2485
+ callback(err);
2486
+ if (typeof msg.emit === "function" && !msg.destroyed) {
2487
+ msg.emit("error", err);
2488
+ }
2489
+ }
2490
+ function strictContentLength(msg) {
2491
+ return msg.strictContentLength && msg._contentLength != null && msg._hasBody && !msg._removedContLen && !msg.chunkedEncoding && !msg.hasHeader("transfer-encoding");
2492
+ }
2493
+ function write_(msg, chunk, encoding, callback, fromEnd) {
2494
+ if (typeof callback !== "function") {
2495
+ callback = nop;
2496
+ }
2497
+ if (chunk === null) {
2498
+ throw new ERR_STREAM_NULL_VALUES();
2499
+ } else if (typeof chunk !== "string" && !isUint8Array(chunk)) {
2500
+ throw new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk);
2501
+ }
2502
+ let err = void 0;
2503
+ if (msg.finished) {
2504
+ err = new ERR_STREAM_WRITE_AFTER_END();
2505
+ } else if (msg.destroyed) {
2506
+ err = new ERR_STREAM_DESTROYED("write");
2507
+ }
2508
+ if (err) {
2509
+ if (!msg.destroyed) {
2510
+ onError2(msg, err, callback);
2511
+ } else {
2512
+ setTimeout(callback, 0, err);
2513
+ }
2514
+ return false;
2515
+ }
2516
+ let len = void 0;
2517
+ if (msg.strictContentLength) {
2518
+ len ??= typeof chunk === "string" ? buffer.Buffer.byteLength(chunk, encoding ?? void 0) : chunk.byteLength;
2519
+ if (strictContentLength(msg) && (fromEnd ? msg[kBytesWritten] + len !== msg._contentLength : msg[kBytesWritten] + len > (msg._contentLength ?? 0))) {
2520
+ throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(len + msg[kBytesWritten], msg._contentLength);
2521
+ }
2522
+ msg[kBytesWritten] += len;
2523
+ }
2524
+ if (!msg._header) {
2525
+ if (fromEnd) {
2526
+ len ??= typeof chunk === "string" ? buffer.Buffer.byteLength(chunk, encoding ?? void 0) : chunk.byteLength;
2527
+ msg._contentLength = len;
2528
+ }
2529
+ msg._implicitHeader();
2530
+ }
2531
+ if (!msg._hasBody) {
2532
+ if (msg[kRejectNonStandardBodyWrites]) {
2533
+ throw new ERR_HTTP_BODY_NOT_ALLOWED();
2534
+ } else {
2535
+ setTimeout(callback, 0);
2536
+ return true;
2537
+ }
2538
+ }
2539
+ if (!fromEnd && msg._writtenDataBuffer != null && !msg._writtenDataBuffer.writableCorked) {
2540
+ msg._writtenDataBuffer.cork();
2541
+ setTimeout(connectionCorkNT, 0, msg._writtenDataBuffer);
2542
+ }
2543
+ let ret;
2544
+ if (msg.chunkedEncoding && chunk.length !== 0) {
2545
+ len ??= typeof chunk === "string" ? buffer.Buffer.byteLength(chunk, encoding ?? void 0) : chunk.byteLength;
2546
+ if (msg[kCorked] && msg._headerSent) {
2547
+ msg[kChunkedBuffer].push({ data: chunk, encoding, callback });
2548
+ msg[kChunkedLength] += len;
2549
+ ret = msg[kChunkedLength] < msg[kHighWaterMark];
2550
+ } else {
2551
+ ret = msg._send(chunk, encoding, callback, len);
2552
+ }
2553
+ } else {
2554
+ ret = msg._send(chunk, encoding, callback, len);
2555
+ }
2556
+ return ret;
2557
+ }
2558
+ function connectionCorkNT(dataBuffer) {
2559
+ dataBuffer.uncork();
2560
+ }
2561
+ function onFinish(outmsg) {
2562
+ outmsg.emit("finish");
2563
+ }
2564
+ Object.defineProperties(FetchOutgoingMessage.prototype, {
2565
+ errored: {
2566
+ get() {
2567
+ return this[kErrored];
2568
+ }
2569
+ },
2570
+ closed: {
2571
+ get() {
2572
+ return this._closed;
2573
+ }
2574
+ },
2575
+ writableFinished: {
2576
+ get() {
2577
+ return this.finished && this.outputSize === 0 && (this._writtenDataBuffer == null || this._writtenDataBuffer.writableLength === 0);
2578
+ }
2579
+ },
2580
+ writableObjectMode: {
2581
+ get() {
2582
+ return false;
2583
+ }
2584
+ },
2585
+ writableLength: {
2586
+ get() {
2587
+ return this.outputSize + this[kChunkedLength] + (this._writtenDataBuffer != null ? this._writtenDataBuffer.writableLength : 0);
2588
+ }
2589
+ },
2590
+ writableHighWaterMark: {
2591
+ get() {
2592
+ return this._writtenDataBuffer != null ? this._writtenDataBuffer.writableHighWaterMark : this[kHighWaterMark];
2593
+ }
2594
+ },
2595
+ writableCorked: {
2596
+ get() {
2597
+ return this[kCorked];
2598
+ }
2599
+ },
2600
+ writableEnded: {
2601
+ get() {
2602
+ return this.finished;
2603
+ }
2604
+ },
2605
+ writableNeedDrain: {
2606
+ get() {
2607
+ return !this.destroyed && !this.finished && this[kNeedDrain];
2608
+ }
2609
+ }
2610
+ });
2611
+ var headerCharRegex2 = /[^\t\x20-\x7e\x80-\xff]/;
2612
+ function checkInvalidHeaderChar2(val) {
2613
+ return headerCharRegex2.test(val);
2614
+ }
2615
+ var STATUS_CODES = {
2616
+ 100: "Continue",
2617
+ // RFC 7231 6.2.1
2618
+ 101: "Switching Protocols",
2619
+ // RFC 7231 6.2.2
2620
+ 102: "Processing",
2621
+ // RFC 2518 10.1 (obsoleted by RFC 4918)
2622
+ 103: "Early Hints",
2623
+ // RFC 8297 2
2624
+ 200: "OK",
2625
+ // RFC 7231 6.3.1
2626
+ 201: "Created",
2627
+ // RFC 7231 6.3.2
2628
+ 202: "Accepted",
2629
+ // RFC 7231 6.3.3
2630
+ 203: "Non-Authoritative Information",
2631
+ // RFC 7231 6.3.4
2632
+ 204: "No Content",
2633
+ // RFC 7231 6.3.5
2634
+ 205: "Reset Content",
2635
+ // RFC 7231 6.3.6
2636
+ 206: "Partial Content",
2637
+ // RFC 7233 4.1
2638
+ 207: "Multi-Status",
2639
+ // RFC 4918 11.1
2640
+ 208: "Already Reported",
2641
+ // RFC 5842 7.1
2642
+ 226: "IM Used",
2643
+ // RFC 3229 10.4.1
2644
+ 300: "Multiple Choices",
2645
+ // RFC 7231 6.4.1
2646
+ 301: "Moved Permanently",
2647
+ // RFC 7231 6.4.2
2648
+ 302: "Found",
2649
+ // RFC 7231 6.4.3
2650
+ 303: "See Other",
2651
+ // RFC 7231 6.4.4
2652
+ 304: "Not Modified",
2653
+ // RFC 7232 4.1
2654
+ 305: "Use Proxy",
2655
+ // RFC 7231 6.4.5
2656
+ 307: "Temporary Redirect",
2657
+ // RFC 7231 6.4.7
2658
+ 308: "Permanent Redirect",
2659
+ // RFC 7238 3
2660
+ 400: "Bad Request",
2661
+ // RFC 7231 6.5.1
2662
+ 401: "Unauthorized",
2663
+ // RFC 7235 3.1
2664
+ 402: "Payment Required",
2665
+ // RFC 7231 6.5.2
2666
+ 403: "Forbidden",
2667
+ // RFC 7231 6.5.3
2668
+ 404: "Not Found",
2669
+ // RFC 7231 6.5.4
2670
+ 405: "Method Not Allowed",
2671
+ // RFC 7231 6.5.5
2672
+ 406: "Not Acceptable",
2673
+ // RFC 7231 6.5.6
2674
+ 407: "Proxy Authentication Required",
2675
+ // RFC 7235 3.2
2676
+ 408: "Request Timeout",
2677
+ // RFC 7231 6.5.7
2678
+ 409: "Conflict",
2679
+ // RFC 7231 6.5.8
2680
+ 410: "Gone",
2681
+ // RFC 7231 6.5.9
2682
+ 411: "Length Required",
2683
+ // RFC 7231 6.5.10
2684
+ 412: "Precondition Failed",
2685
+ // RFC 7232 4.2
2686
+ 413: "Payload Too Large",
2687
+ // RFC 7231 6.5.11
2688
+ 414: "URI Too Long",
2689
+ // RFC 7231 6.5.12
2690
+ 415: "Unsupported Media Type",
2691
+ // RFC 7231 6.5.13
2692
+ 416: "Range Not Satisfiable",
2693
+ // RFC 7233 4.4
2694
+ 417: "Expectation Failed",
2695
+ // RFC 7231 6.5.14
2696
+ 418: "I'm a Teapot",
2697
+ // RFC 7168 2.3.3
2698
+ 421: "Misdirected Request",
2699
+ // RFC 7540 9.1.2
2700
+ 422: "Unprocessable Entity",
2701
+ // RFC 4918 11.2
2702
+ 423: "Locked",
2703
+ // RFC 4918 11.3
2704
+ 424: "Failed Dependency",
2705
+ // RFC 4918 11.4
2706
+ 425: "Too Early",
2707
+ // RFC 8470 5.2
2708
+ 426: "Upgrade Required",
2709
+ // RFC 2817 and RFC 7231 6.5.15
2710
+ 428: "Precondition Required",
2711
+ // RFC 6585 3
2712
+ 429: "Too Many Requests",
2713
+ // RFC 6585 4
2714
+ 431: "Request Header Fields Too Large",
2715
+ // RFC 6585 5
2716
+ 451: "Unavailable For Legal Reasons",
2717
+ // RFC 7725 3
2718
+ 500: "Internal Server Error",
2719
+ // RFC 7231 6.6.1
2720
+ 501: "Not Implemented",
2721
+ // RFC 7231 6.6.2
2722
+ 502: "Bad Gateway",
2723
+ // RFC 7231 6.6.3
2724
+ 503: "Service Unavailable",
2725
+ // RFC 7231 6.6.4
2726
+ 504: "Gateway Timeout",
2727
+ // RFC 7231 6.6.5
2728
+ 505: "HTTP Version Not Supported",
2729
+ // RFC 7231 6.6.6
2730
+ 506: "Variant Also Negotiates",
2731
+ // RFC 2295 8.1
2732
+ 507: "Insufficient Storage",
2733
+ // RFC 4918 11.5
2734
+ 508: "Loop Detected",
2735
+ // RFC 5842 7.2
2736
+ 509: "Bandwidth Limit Exceeded",
2737
+ 510: "Not Extended",
2738
+ // RFC 2774 7
2739
+ 511: "Network Authentication Required"
2740
+ // RFC 6585 6
2741
+ };
2742
+ var FetchServerResponse = class _FetchServerResponse extends FetchOutgoingMessage {
2743
+ static encoder = new TextEncoder();
2744
+ statusCode = 200;
2745
+ statusMessage;
2746
+ _sent100;
2747
+ _expect_continue;
2748
+ [kOutHeaders] = null;
2749
+ constructor(req, options) {
2750
+ super(req, options);
2751
+ if (req.method === "HEAD") {
2752
+ this._hasBody = false;
2753
+ }
2754
+ this.sendDate = true;
2755
+ this._sent100 = false;
2756
+ this._expect_continue = false;
2757
+ if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
2758
+ this.useChunkedEncodingByDefault = chunkExpression.exec(String(req.headers.te)) !== null;
2759
+ this.shouldKeepAlive = false;
2760
+ }
2761
+ this.fetchResponse = new Promise((resolve) => {
2762
+ let finished = false;
2763
+ this.on("finish", () => {
2764
+ finished = true;
2765
+ });
2766
+ const initialDataChunks = [];
2767
+ const initialDataWrittenHandler = (e2) => {
2768
+ if (finished) {
2769
+ return;
2770
+ }
2771
+ initialDataChunks[e2.index] = this.dataFromDataWrittenEvent(e2);
2772
+ };
2773
+ this.on("_dataWritten", initialDataWrittenHandler);
2774
+ this.on("_headersSent", (e2) => {
2775
+ this.off("_dataWritten", initialDataWrittenHandler);
2776
+ const { statusCode, statusMessage, headers } = e2;
2777
+ resolve(this._toFetchResponse(statusCode, statusMessage, headers, initialDataChunks, finished));
2778
+ });
2779
+ });
2780
+ }
2781
+ dataFromDataWrittenEvent(e2) {
2782
+ const { index, entry } = e2;
2783
+ let { data, encoding } = entry;
2784
+ if (index === 0) {
2785
+ if (typeof data !== "string") {
2786
+ console.error("First chunk should be string, not sure what happened.");
2787
+ throw new ERR_INVALID_ARG_TYPE("packet.data", ["string", "Buffer", "Uint8Array"], data);
2788
+ }
2789
+ data = data.slice(this.writtenHeaderBytes);
2790
+ }
2791
+ if (typeof data === "string") {
2792
+ if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
2793
+ data = _FetchServerResponse.encoder.encode(data);
2794
+ } else {
2795
+ data = buffer.Buffer.from(data, encoding ?? void 0);
2796
+ }
2797
+ }
2798
+ return data ?? buffer.Buffer.from([]);
2799
+ }
2800
+ _finish() {
2801
+ super._finish();
2802
+ }
2803
+ assignSocket(socket) {
2804
+ throw new ERR_METHOD_NOT_IMPLEMENTED("assignSocket");
2805
+ }
2806
+ detachSocket(socket) {
2807
+ throw new ERR_METHOD_NOT_IMPLEMENTED("detachSocket");
2808
+ }
2809
+ writeContinue(callback) {
2810
+ this._writeRaw("HTTP/1.1 100 Continue\r\n\r\n", "ascii", callback);
2811
+ this._sent100 = true;
2812
+ }
2813
+ writeProcessing(callback) {
2814
+ this._writeRaw("HTTP/1.1 102 Processing\r\n\r\n", "ascii", callback);
2815
+ }
2816
+ writeEarlyHints(hints, callback) {
2817
+ let head = "HTTP/1.1 103 Early Hints\r\n";
2818
+ if (hints.link === null || hints.link === void 0) {
2819
+ return;
2820
+ }
2821
+ const link = validateLinkHeaderValue(hints.link);
2822
+ if (link.length === 0) {
2823
+ return;
956
2824
  }
957
- agent.__updateInstructions(instructions);
958
- return c2.json(
959
- {
960
- instructions
961
- },
962
- 200
963
- );
964
- } catch (error) {
965
- return handleError(error, "Error setting agent instructions");
2825
+ head += "Link: " + link + "\r\n";
2826
+ for (const key of Object.keys(hints)) {
2827
+ if (key !== "link") {
2828
+ head += key + ": " + hints[key] + "\r\n";
2829
+ }
2830
+ }
2831
+ head += "\r\n";
2832
+ this._writeRaw(head, "ascii", callback);
966
2833
  }
967
- }
968
-
969
- // src/server/handlers/client.ts
970
- var clients = /* @__PURE__ */ new Set();
971
- function handleClientsRefresh(c2) {
972
- const stream3 = new ReadableStream({
973
- start(controller) {
974
- clients.add(controller);
975
- controller.enqueue("data: connected\n\n");
976
- c2.req.raw.signal.addEventListener("abort", () => {
977
- clients.delete(controller);
978
- });
2834
+ _implicitHeader() {
2835
+ this.writeHead(this.statusCode);
2836
+ }
2837
+ writeHead(statusCode, reason, obj) {
2838
+ if (this._header) {
2839
+ throw new ERR_HTTP_HEADERS_SENT("write");
979
2840
  }
980
- });
981
- return new Response(stream3, {
982
- headers: {
983
- "Content-Type": "text/event-stream",
984
- "Cache-Control": "no-cache",
985
- Connection: "keep-alive",
986
- "Access-Control-Allow-Origin": "*"
2841
+ const originalStatusCode = statusCode;
2842
+ statusCode |= 0;
2843
+ if (statusCode < 100 || statusCode > 999) {
2844
+ throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
987
2845
  }
988
- });
989
- }
990
- function handleTriggerClientsRefresh(c2) {
991
- clients.forEach((controller) => {
992
- try {
993
- controller.enqueue("data: refresh\n\n");
994
- } catch {
995
- clients.delete(controller);
2846
+ if (typeof reason === "string") {
2847
+ this.statusMessage = reason;
2848
+ } else {
2849
+ this.statusMessage ||= STATUS_CODES[statusCode] || "unknown";
2850
+ obj ??= reason;
996
2851
  }
997
- });
998
- return c2.json({ success: true, clients: clients.size });
999
- }
1000
- async function getLogsHandler(c2) {
1001
- try {
1002
- const mastra = c2.get("mastra");
1003
- const transportId = c2.req.query("transportId");
1004
- const logs$1 = await logs.getLogsHandler({
1005
- mastra,
1006
- transportId
2852
+ this.statusCode = statusCode;
2853
+ let headers;
2854
+ if (this[kOutHeaders]) {
2855
+ let k;
2856
+ if (Array.isArray(obj)) {
2857
+ if (obj.length % 2 !== 0) {
2858
+ throw new ERR_INVALID_ARG_VALUE("headers", obj);
2859
+ }
2860
+ for (let n2 = 0; n2 < obj.length; n2 += 2) {
2861
+ k = obj[n2 + 0];
2862
+ this.removeHeader(String(k));
2863
+ }
2864
+ for (let n2 = 0; n2 < obj.length; n2 += 2) {
2865
+ k = obj[n2];
2866
+ if (k) {
2867
+ this.appendHeader(String(k), obj[n2 + 1]);
2868
+ }
2869
+ }
2870
+ } else if (obj) {
2871
+ const keys = Object.keys(obj);
2872
+ for (let i2 = 0; i2 < keys.length; i2++) {
2873
+ k = keys[i2];
2874
+ if (k) {
2875
+ this.setHeader(k, obj[k]);
2876
+ }
2877
+ }
2878
+ }
2879
+ headers = this[kOutHeaders];
2880
+ } else {
2881
+ headers = obj;
2882
+ }
2883
+ if (checkInvalidHeaderChar2(this.statusMessage)) {
2884
+ throw new ERR_INVALID_CHAR("statusMessage");
2885
+ }
2886
+ const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}\r
2887
+ `;
2888
+ if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199) {
2889
+ this._hasBody = false;
2890
+ }
2891
+ if (this._expect_continue && !this._sent100) {
2892
+ this.shouldKeepAlive = false;
2893
+ }
2894
+ const convertedHeaders = headers && !Array.isArray(headers) ? headers : headers;
2895
+ this._storeHeader(statusLine, convertedHeaders ?? null);
2896
+ return this;
2897
+ }
2898
+ // Docs-only deprecated: DEP0063
2899
+ writeHeader = this.writeHead;
2900
+ fetchResponse;
2901
+ _toFetchResponse(status, statusText, sentHeaders, initialDataChunks, finished) {
2902
+ const headers = new Headers();
2903
+ for (const [header, value] of sentHeaders) {
2904
+ headers.append(header, value);
2905
+ }
2906
+ const _this = this;
2907
+ let body = this._hasBody ? new ReadableStream({
2908
+ start(controller) {
2909
+ for (const dataChunk of initialDataChunks) {
2910
+ controller.enqueue(dataChunk);
2911
+ }
2912
+ if (finished) {
2913
+ controller.close();
2914
+ } else {
2915
+ _this.on("finish", () => {
2916
+ finished = true;
2917
+ controller.close();
2918
+ });
2919
+ _this.on("_dataWritten", (e2) => {
2920
+ if (finished) {
2921
+ return;
2922
+ }
2923
+ const data = _this.dataFromDataWrittenEvent(e2);
2924
+ controller.enqueue(data);
2925
+ });
2926
+ }
2927
+ }
2928
+ }) : null;
2929
+ if (body != null && typeof FixedLengthStream !== "undefined") {
2930
+ const contentLength = parseInt(headers.get("content-length") ?? "", 10);
2931
+ if (contentLength >= 0) {
2932
+ body = body.pipeThrough(new FixedLengthStream(contentLength));
2933
+ }
2934
+ }
2935
+ return new Response(body, {
2936
+ status,
2937
+ statusText,
2938
+ headers
1007
2939
  });
1008
- return c2.json(logs$1);
1009
- } catch (error) {
1010
- return handleError(error, "Error getting logs");
1011
2940
  }
2941
+ };
2942
+ function toReqRes(req, options) {
2943
+ const { createIncomingMessage = () => new FetchIncomingMessage(), createServerResponse = (incoming2) => new FetchServerResponse(incoming2), ctx } = {};
2944
+ const incoming = createIncomingMessage(ctx);
2945
+ const serverResponse = createServerResponse(incoming, ctx);
2946
+ const reqUrl = new URL(req.url);
2947
+ const versionMajor = 1;
2948
+ const versionMinor = 1;
2949
+ incoming.httpVersionMajor = versionMajor;
2950
+ incoming.httpVersionMinor = versionMinor;
2951
+ incoming.httpVersion = `${versionMajor}.${versionMinor}`;
2952
+ incoming.url = reqUrl.pathname + reqUrl.search;
2953
+ incoming.upgrade = false;
2954
+ const headers = [];
2955
+ for (const [headerName, headerValue] of req.headers) {
2956
+ headers.push(headerName);
2957
+ headers.push(headerValue);
2958
+ }
2959
+ incoming._addHeaderLines(headers, headers.length);
2960
+ incoming.method = req.method;
2961
+ incoming._stream = req.body;
2962
+ return {
2963
+ req: incoming,
2964
+ res: serverResponse
2965
+ };
2966
+ }
2967
+ function toFetchResponse(res) {
2968
+ if (!(res instanceof FetchServerResponse)) {
2969
+ throw new Error("toFetchResponse must be called on a ServerResponse generated by toReqRes");
2970
+ }
2971
+ return res.fetchResponse;
1012
2972
  }
1013
- async function getLogsByRunIdHandler(c2) {
2973
+
2974
+ // src/server/handlers/mcp.ts
2975
+ var getMastra = (c2) => c2.get("mastra");
2976
+ var getMcpServerMessageHandler = async (c2) => {
2977
+ const mastra = getMastra(c2);
2978
+ const serverId = c2.req.param("serverId");
2979
+ const { req, res } = toReqRes(c2.req.raw);
2980
+ const server = mastra.getMCPServer(serverId);
2981
+ if (!server) {
2982
+ return c2.json({ error: `MCP server '${serverId}' not found` }, 404);
2983
+ }
1014
2984
  try {
1015
- const mastra = c2.get("mastra");
1016
- const runId = c2.req.param("runId");
1017
- const transportId = c2.req.query("transportId");
1018
- const logs$1 = await logs.getLogsByRunIdHandler({
1019
- mastra,
1020
- runId,
1021
- transportId
2985
+ await server.startHTTP({
2986
+ url: new URL(c2.req.url),
2987
+ httpPath: `/api/servers/${serverId}/mcp`,
2988
+ req,
2989
+ res,
2990
+ options: {
2991
+ sessionIdGenerator: void 0
2992
+ }
1022
2993
  });
1023
- return c2.json(logs$1);
2994
+ const toFetchRes = await toFetchResponse(res);
2995
+ return toFetchRes;
1024
2996
  } catch (error) {
1025
- return handleError(error, "Error getting logs by run ID");
2997
+ return handleError(error, "Error sending MCP message");
1026
2998
  }
1027
- }
1028
- async function getLogTransports(c2) {
2999
+ };
3000
+ var handleMcpServerSseRoutes = async (c2) => {
3001
+ const mastra = getMastra(c2);
3002
+ const serverId = c2.req.param("serverId");
3003
+ const server = mastra.getMCPServer(serverId);
3004
+ if (!server) {
3005
+ return c2.json({ error: `MCP server '${serverId}' not found` }, 404);
3006
+ }
3007
+ const { req, res } = toReqRes(c2.req.raw);
3008
+ const requestUrl = new URL(c2.req.url);
3009
+ const sseConnectionPath = `/api/servers/${serverId}/sse`;
3010
+ const sseMessagePath = `/api/servers/${serverId}/messages`;
1029
3011
  try {
1030
- const mastra = c2.get("mastra");
1031
- const result = await logs.getLogTransports({
1032
- mastra
3012
+ await server.startSSE({
3013
+ url: requestUrl,
3014
+ ssePath: sseConnectionPath,
3015
+ messagePath: sseMessagePath,
3016
+ req,
3017
+ res
1033
3018
  });
1034
- return c2.json(result);
3019
+ if (res.writableEnded || res.headersSent) {
3020
+ return toFetchResponse(res);
3021
+ }
3022
+ c2.get("logger")?.warn(
3023
+ { serverId, path: requestUrl.pathname },
3024
+ "MCP SSE handler: MCPServer.startSSE did not seem to handle the response."
3025
+ );
3026
+ return c2.text("Internal Server Error: MCP SSE request not fully processed by server component", 500);
1035
3027
  } catch (error) {
1036
- return handleError(error, "Error getting log Transports");
3028
+ c2.get("logger")?.error({ err: error, serverId, path: requestUrl.pathname }, "Error in MCP SSE route handler");
3029
+ if (!res.headersSent && !res.writableEnded) {
3030
+ return handleError(error, "Error handling MCP SSE request");
3031
+ }
1037
3032
  }
1038
- }
3033
+ };
1039
3034
  async function getMemoryStatusHandler(c2) {
1040
3035
  try {
1041
3036
  const mastra = c2.get("mastra");
@@ -1398,13 +3393,14 @@ function executeToolHandler(tools$1) {
1398
3393
  const runtimeContext = c2.get("runtimeContext");
1399
3394
  const toolId = decodeURIComponent(c2.req.param("toolId"));
1400
3395
  const runId = c2.req.query("runId");
1401
- const { data } = await c2.req.json();
3396
+ const { data, runtimeContext: runtimeContextFromRequest } = await c2.req.json();
1402
3397
  const result = await tools.executeToolHandler(tools$1)({
1403
3398
  mastra,
1404
3399
  toolId,
1405
3400
  data,
1406
3401
  runtimeContext,
1407
- runId
3402
+ runId,
3403
+ runtimeContextFromRequest
1408
3404
  });
1409
3405
  return c2.json(result);
1410
3406
  } catch (error) {
@@ -1418,13 +3414,14 @@ async function executeAgentToolHandler(c2) {
1418
3414
  const runtimeContext = c2.get("runtimeContext");
1419
3415
  const agentId = c2.req.param("agentId");
1420
3416
  const toolId = c2.req.param("toolId");
1421
- const { data } = await c2.req.json();
3417
+ const { data, runtimeContext: runtimeContextFromRequest } = await c2.req.json();
1422
3418
  const result = await tools.executeAgentToolHandler({
1423
3419
  mastra,
1424
3420
  agentId,
1425
3421
  toolId,
1426
3422
  data,
1427
- runtimeContext
3423
+ runtimeContext,
3424
+ runtimeContextFromRequest
1428
3425
  });
1429
3426
  return c2.json(result);
1430
3427
  } catch (error) {
@@ -1572,11 +3569,13 @@ async function startAsyncVNextWorkflowHandler(c2) {
1572
3569
  try {
1573
3570
  const mastra = c2.get("mastra");
1574
3571
  const workflowId = c2.req.param("workflowId");
1575
- const { inputData, runtimeContext } = await c2.req.json();
3572
+ const runtimeContext = c2.get("runtimeContext");
3573
+ const { inputData, runtimeContext: runtimeContextFromRequest } = await c2.req.json();
1576
3574
  const runId = c2.req.query("runId");
1577
3575
  const result = await vNextWorkflows.startAsyncVNextWorkflowHandler({
1578
3576
  mastra,
1579
3577
  runtimeContext,
3578
+ runtimeContextFromRequest,
1580
3579
  workflowId,
1581
3580
  runId,
1582
3581
  inputData
@@ -1590,11 +3589,13 @@ async function startVNextWorkflowRunHandler(c2) {
1590
3589
  try {
1591
3590
  const mastra = c2.get("mastra");
1592
3591
  const workflowId = c2.req.param("workflowId");
1593
- const { inputData, runtimeContext } = await c2.req.json();
3592
+ const runtimeContext = c2.get("runtimeContext");
3593
+ const { inputData, runtimeContext: runtimeContextFromRequest } = await c2.req.json();
1594
3594
  const runId = c2.req.query("runId");
1595
3595
  await vNextWorkflows.startVNextWorkflowRunHandler({
1596
3596
  mastra,
1597
3597
  runtimeContext,
3598
+ runtimeContextFromRequest,
1598
3599
  workflowId,
1599
3600
  runId,
1600
3601
  inputData
@@ -1615,20 +3616,20 @@ function watchVNextWorkflowHandler(c2) {
1615
3616
  }
1616
3617
  return streaming.stream(
1617
3618
  c2,
1618
- async (stream3) => {
3619
+ async (stream4) => {
1619
3620
  try {
1620
3621
  const result = await vNextWorkflows.watchVNextWorkflowHandler({
1621
3622
  mastra,
1622
3623
  workflowId,
1623
3624
  runId
1624
3625
  });
1625
- stream3.onAbort(() => {
3626
+ stream4.onAbort(() => {
1626
3627
  if (!result.locked) {
1627
3628
  return result.cancel();
1628
3629
  }
1629
3630
  });
1630
3631
  for await (const chunk of result) {
1631
- await stream3.write(chunk.toString() + "");
3632
+ await stream4.write(chunk.toString() + "");
1632
3633
  }
1633
3634
  } catch (err) {
1634
3635
  console.log(err);
@@ -1647,13 +3648,15 @@ async function resumeAsyncVNextWorkflowHandler(c2) {
1647
3648
  const mastra = c2.get("mastra");
1648
3649
  const workflowId = c2.req.param("workflowId");
1649
3650
  const runId = c2.req.query("runId");
1650
- const { step, resumeData, runtimeContext } = await c2.req.json();
3651
+ const runtimeContext = c2.get("runtimeContext");
3652
+ const { step, resumeData, runtimeContext: runtimeContextFromRequest } = await c2.req.json();
1651
3653
  if (!runId) {
1652
3654
  throw new httpException.HTTPException(400, { message: "runId required to resume workflow" });
1653
3655
  }
1654
3656
  const result = await vNextWorkflows.resumeAsyncVNextWorkflowHandler({
1655
3657
  mastra,
1656
3658
  runtimeContext,
3659
+ runtimeContextFromRequest,
1657
3660
  workflowId,
1658
3661
  runId,
1659
3662
  body: { step, resumeData }
@@ -1850,20 +3853,20 @@ function watchWorkflowHandler(c2) {
1850
3853
  }
1851
3854
  return streaming.stream(
1852
3855
  c2,
1853
- async (stream3) => {
3856
+ async (stream4) => {
1854
3857
  try {
1855
3858
  const result = await workflows.watchWorkflowHandler({
1856
3859
  mastra,
1857
3860
  workflowId,
1858
3861
  runId
1859
3862
  });
1860
- stream3.onAbort(() => {
3863
+ stream4.onAbort(() => {
1861
3864
  if (!result.locked) {
1862
3865
  return result.cancel();
1863
3866
  }
1864
3867
  });
1865
3868
  for await (const chunk of result) {
1866
- await stream3.write(chunk.toString() + "");
3869
+ await stream4.write(chunk.toString() + "");
1867
3870
  }
1868
3871
  } catch (err) {
1869
3872
  console.log(err);
@@ -2093,7 +4096,18 @@ async function createHonoServer(mastra, options = {}) {
2093
4096
  app.onError(errorHandler);
2094
4097
  app.use("*", function setContext(c2, next) {
2095
4098
  const runtimeContext$1 = new runtimeContext.RuntimeContext();
2096
- c2.set("runtimeContext", runtimeContext$1);
4099
+ const proxyRuntimeContext = new Proxy(runtimeContext$1, {
4100
+ get(target, prop) {
4101
+ if (prop === "get") {
4102
+ return function(key) {
4103
+ const value = target.get(key);
4104
+ return value ?? `<${key}>`;
4105
+ };
4106
+ }
4107
+ return Reflect.get(target, prop);
4108
+ }
4109
+ });
4110
+ c2.set("runtimeContext", proxyRuntimeContext);
2097
4111
  c2.set("mastra", mastra);
2098
4112
  c2.set("tools", tools);
2099
4113
  c2.set("playground", options.playground === true);
@@ -2167,6 +4181,142 @@ async function createHonoServer(mastra, options = {}) {
2167
4181
  if (server?.build?.apiReqLogs) {
2168
4182
  app.use(logger.logger());
2169
4183
  }
4184
+ app.get(
4185
+ "/.well-known/:agentId/agent.json",
4186
+ h({
4187
+ description: "Get agent configuration",
4188
+ tags: ["agents"],
4189
+ parameters: [
4190
+ {
4191
+ name: "agentId",
4192
+ in: "path",
4193
+ required: true,
4194
+ schema: { type: "string" }
4195
+ }
4196
+ ],
4197
+ responses: {
4198
+ 200: {
4199
+ description: "Agent configuration"
4200
+ }
4201
+ }
4202
+ }),
4203
+ getAgentCardByIdHandler
4204
+ );
4205
+ app.post(
4206
+ "/a2a/:agentId",
4207
+ h({
4208
+ description: "Execute agent via A2A protocol",
4209
+ tags: ["agents"],
4210
+ parameters: [
4211
+ {
4212
+ name: "agentId",
4213
+ in: "path",
4214
+ required: true,
4215
+ schema: { type: "string" }
4216
+ }
4217
+ ],
4218
+ requestBody: {
4219
+ required: true,
4220
+ content: {
4221
+ "application/json": {
4222
+ schema: {
4223
+ type: "object",
4224
+ properties: {
4225
+ method: {
4226
+ type: "string",
4227
+ enum: ["tasks/send", "tasks/sendSubscribe", "tasks/get", "tasks/cancel"],
4228
+ description: "The A2A protocol method to execute"
4229
+ },
4230
+ params: {
4231
+ type: "object",
4232
+ oneOf: [
4233
+ {
4234
+ // TaskSendParams
4235
+ type: "object",
4236
+ properties: {
4237
+ id: {
4238
+ type: "string",
4239
+ description: "Unique identifier for the task being initiated or continued"
4240
+ },
4241
+ sessionId: {
4242
+ type: "string",
4243
+ description: "Optional identifier for the session this task belongs to"
4244
+ },
4245
+ message: {
4246
+ type: "object",
4247
+ description: "The message content to send to the agent for processing"
4248
+ },
4249
+ pushNotification: {
4250
+ type: "object",
4251
+ nullable: true,
4252
+ description: "Optional pushNotification information for receiving notifications about this task"
4253
+ },
4254
+ historyLength: {
4255
+ type: "integer",
4256
+ nullable: true,
4257
+ description: "Optional parameter to specify how much message history to include in the response"
4258
+ },
4259
+ metadata: {
4260
+ type: "object",
4261
+ nullable: true,
4262
+ description: "Optional metadata associated with sending this message"
4263
+ }
4264
+ },
4265
+ required: ["id", "message"]
4266
+ },
4267
+ {
4268
+ // TaskQueryParams
4269
+ type: "object",
4270
+ properties: {
4271
+ id: { type: "string", description: "The unique identifier of the task" },
4272
+ historyLength: {
4273
+ type: "integer",
4274
+ nullable: true,
4275
+ description: "Optional history length to retrieve for the task"
4276
+ },
4277
+ metadata: {
4278
+ type: "object",
4279
+ nullable: true,
4280
+ description: "Optional metadata to include with the operation"
4281
+ }
4282
+ },
4283
+ required: ["id"]
4284
+ },
4285
+ {
4286
+ // TaskIdParams
4287
+ type: "object",
4288
+ properties: {
4289
+ id: { type: "string", description: "The unique identifier of the task" },
4290
+ metadata: {
4291
+ type: "object",
4292
+ nullable: true,
4293
+ description: "Optional metadata to include with the operation"
4294
+ }
4295
+ },
4296
+ required: ["id"]
4297
+ }
4298
+ ]
4299
+ }
4300
+ },
4301
+ required: ["method", "params"]
4302
+ }
4303
+ }
4304
+ }
4305
+ },
4306
+ responses: {
4307
+ 200: {
4308
+ description: "A2A response"
4309
+ },
4310
+ 400: {
4311
+ description: "Missing or invalid request parameters"
4312
+ },
4313
+ 404: {
4314
+ description: "Agent not found"
4315
+ }
4316
+ }
4317
+ }),
4318
+ getAgentExecutionHandler
4319
+ );
2170
4320
  app.get(
2171
4321
  "/api",
2172
4322
  h({
@@ -3007,7 +5157,8 @@ async function createHonoServer(mastra, options = {}) {
3007
5157
  schema: {
3008
5158
  type: "object",
3009
5159
  properties: {
3010
- data: { type: "object" }
5160
+ data: { type: "object" },
5161
+ runtimeContext: { type: "object" }
3011
5162
  },
3012
5163
  required: ["data"]
3013
5164
  }
@@ -3025,6 +5176,93 @@ async function createHonoServer(mastra, options = {}) {
3025
5176
  }),
3026
5177
  executeAgentToolHandler
3027
5178
  );
5179
+ app.post(
5180
+ "/api/servers/:serverId/mcp",
5181
+ bodyLimit.bodyLimit(bodyLimitOptions),
5182
+ h({
5183
+ description: "Send a message to an MCP server using Streamable HTTP",
5184
+ tags: ["mcp"],
5185
+ parameters: [
5186
+ {
5187
+ name: "serverId",
5188
+ in: "path",
5189
+ required: true,
5190
+ schema: { type: "string" }
5191
+ }
5192
+ ],
5193
+ requestBody: {
5194
+ content: { "application/json": { schema: { type: "object" } } }
5195
+ },
5196
+ responses: {
5197
+ 200: {
5198
+ description: "Streamable HTTP connection processed"
5199
+ },
5200
+ 404: {
5201
+ description: "MCP server not found"
5202
+ }
5203
+ }
5204
+ }),
5205
+ getMcpServerMessageHandler
5206
+ );
5207
+ const mcpSseBasePath = "/api/servers/:serverId/sse";
5208
+ const mcpSseMessagePath = "/api/servers/:serverId/messages";
5209
+ app.get(
5210
+ mcpSseBasePath,
5211
+ h({
5212
+ description: "Establish an MCP Server-Sent Events (SSE) connection with a server instance.",
5213
+ tags: ["mcp"],
5214
+ parameters: [
5215
+ {
5216
+ name: "serverId",
5217
+ in: "path",
5218
+ required: true,
5219
+ schema: { type: "string" },
5220
+ description: "The ID of the MCP server instance."
5221
+ }
5222
+ ],
5223
+ responses: {
5224
+ 200: {
5225
+ description: "SSE connection established. The client will receive events over this connection. (Content-Type: text/event-stream)"
5226
+ },
5227
+ 404: { description: "MCP server instance not found." },
5228
+ 500: { description: "Internal server error establishing SSE connection." }
5229
+ }
5230
+ }),
5231
+ handleMcpServerSseRoutes
5232
+ );
5233
+ app.post(
5234
+ mcpSseMessagePath,
5235
+ bodyLimit.bodyLimit(bodyLimitOptions),
5236
+ // Apply body limit for messages
5237
+ h({
5238
+ description: "Send a message to an MCP server over an established SSE connection.",
5239
+ tags: ["mcp"],
5240
+ parameters: [
5241
+ {
5242
+ name: "serverId",
5243
+ in: "path",
5244
+ required: true,
5245
+ schema: { type: "string" },
5246
+ description: "The ID of the MCP server instance."
5247
+ }
5248
+ ],
5249
+ requestBody: {
5250
+ description: "JSON-RPC message to send to the MCP server.",
5251
+ required: true,
5252
+ content: { "application/json": { schema: { type: "object" } } }
5253
+ // MCP messages are typically JSON
5254
+ },
5255
+ responses: {
5256
+ 200: {
5257
+ description: "Message received and is being processed by the MCP server. The actual result or error will be sent as an SSE event over the established connection."
5258
+ },
5259
+ 400: { description: "Bad request (e.g., invalid JSON payload or missing body)." },
5260
+ 404: { description: "MCP server instance not found or SSE connection path incorrect." },
5261
+ 503: { description: "SSE connection not established with this server, or server unable to process message." }
5262
+ }
5263
+ }),
5264
+ handleMcpServerSseRoutes
5265
+ );
3028
5266
  app.get(
3029
5267
  "/api/memory/status",
3030
5268
  h({
@@ -3394,7 +5632,10 @@ async function createHonoServer(mastra, options = {}) {
3394
5632
  oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }]
3395
5633
  },
3396
5634
  resumeData: { type: "object" },
3397
- runtimeContext: { type: "object" }
5635
+ runtimeContext: {
5636
+ type: "object",
5637
+ description: "Runtime context for the workflow execution"
5638
+ }
3398
5639
  },
3399
5640
  required: ["step"]
3400
5641
  }
@@ -3435,7 +5676,10 @@ async function createHonoServer(mastra, options = {}) {
3435
5676
  oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }]
3436
5677
  },
3437
5678
  resumeData: { type: "object" },
3438
- runtimeContext: { type: "object" }
5679
+ runtimeContext: {
5680
+ type: "object",
5681
+ description: "Runtime context for the workflow execution"
5682
+ }
3439
5683
  },
3440
5684
  required: ["step"]
3441
5685
  }
@@ -3501,7 +5745,10 @@ async function createHonoServer(mastra, options = {}) {
3501
5745
  type: "object",
3502
5746
  properties: {
3503
5747
  inputData: { type: "object" },
3504
- runtimeContext: { type: "object" }
5748
+ runtimeContext: {
5749
+ type: "object",
5750
+ description: "Runtime context for the workflow execution"
5751
+ }
3505
5752
  }
3506
5753
  }
3507
5754
  }
@@ -3545,7 +5792,10 @@ async function createHonoServer(mastra, options = {}) {
3545
5792
  type: "object",
3546
5793
  properties: {
3547
5794
  inputData: { type: "object" },
3548
- runtimeContext: { type: "object" }
5795
+ runtimeContext: {
5796
+ type: "object",
5797
+ description: "Runtime context for the workflow execution"
5798
+ }
3549
5799
  }
3550
5800
  }
3551
5801
  }
@@ -4072,7 +6322,8 @@ async function createHonoServer(mastra, options = {}) {
4072
6322
  schema: {
4073
6323
  type: "object",
4074
6324
  properties: {
4075
- data: { type: "object" }
6325
+ data: { type: "object" },
6326
+ runtimeContext: { type: "object" }
4076
6327
  },
4077
6328
  required: ["data"]
4078
6329
  }
@@ -4365,7 +6616,7 @@ async function createNodeServer(mastra, options = {}) {
4365
6616
  const host = serverOptions?.host ?? "localhost";
4366
6617
  logger2.info(` Mastra API running on port http://${host}:${port}/api`);
4367
6618
  if (options?.isDev) {
4368
- logger2.info(`\uFFFD Open API documentation available at http://${host}:${port}/openapi.json`);
6619
+ logger2.info(`\u{1F517} Open API documentation available at http://${host}:${port}/openapi.json`);
4369
6620
  }
4370
6621
  if (options?.isDev) {
4371
6622
  logger2.info(`\u{1F9EA} Swagger UI available at http://${host}:${port}/swagger-ui`);