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