@mastra/deployer 0.3.4-alpha.0 → 0.3.4-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,8 @@ var a2a = require('@mastra/server/handlers/a2a');
22
22
  var streaming = require('hono/streaming');
23
23
  var agents = require('@mastra/server/handlers/agents');
24
24
  var logs = require('@mastra/server/handlers/logs');
25
+ var util = require('util');
26
+ var buffer = require('buffer');
25
27
  var memory = require('@mastra/server/handlers/memory');
26
28
  var network = require('@mastra/server/handlers/network');
27
29
  var agent = require('@mastra/core/agent');
@@ -36,6 +38,7 @@ var workflows = require('@mastra/server/handlers/workflows');
36
38
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
37
39
 
38
40
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
41
+ var util__default = /*#__PURE__*/_interopDefault(util);
39
42
 
40
43
  // src/server/index.ts
41
44
  var RequestError = class extends Error {
@@ -1111,6 +1114,1923 @@ async function getLogTransports(c2) {
1111
1114
  return handleError(error, "Error getting log Transports");
1112
1115
  }
1113
1116
  }
1117
+ var classRegExp = /^([A-Z][a-z0-9]*)+$/;
1118
+ var kTypes = [
1119
+ "string",
1120
+ "function",
1121
+ "number",
1122
+ "object",
1123
+ // Accept 'Function' and 'Object' as alternative to the lower cased version.
1124
+ "Function",
1125
+ "Object",
1126
+ "boolean",
1127
+ "bigint",
1128
+ "symbol"
1129
+ ];
1130
+ function determineSpecificType(value) {
1131
+ if (value == null) {
1132
+ return "" + value;
1133
+ }
1134
+ if (typeof value === "function" && value.name) {
1135
+ return `function ${value.name}`;
1136
+ }
1137
+ if (typeof value === "object") {
1138
+ if (value.constructor?.name) {
1139
+ return `an instance of ${value.constructor.name}`;
1140
+ }
1141
+ return `${util__default.default.inspect(value, { depth: -1 })}`;
1142
+ }
1143
+ let inspected = util__default.default.inspect(value, { colors: false });
1144
+ if (inspected.length > 28) {
1145
+ inspected = `${inspected.slice(0, 25)}...`;
1146
+ }
1147
+ return `type ${typeof value} (${inspected})`;
1148
+ }
1149
+ var ERR_HTTP_BODY_NOT_ALLOWED = class extends Error {
1150
+ constructor() {
1151
+ super("Adding content for this request method or response status is not allowed.");
1152
+ }
1153
+ };
1154
+ var ERR_HTTP_CONTENT_LENGTH_MISMATCH = class extends Error {
1155
+ constructor(actual, expected) {
1156
+ super(`Response body's content-length of ${actual} byte(s) does not match the content-length of ${expected} byte(s) set in header`);
1157
+ }
1158
+ };
1159
+ var ERR_HTTP_HEADERS_SENT = class extends Error {
1160
+ constructor(arg) {
1161
+ super(`Cannot ${arg} headers after they are sent to the client`);
1162
+ }
1163
+ };
1164
+ var ERR_INVALID_ARG_VALUE = class extends TypeError {
1165
+ constructor(name, value, reason = "is invalid") {
1166
+ let inspected = util__default.default.inspect(value);
1167
+ if (inspected.length > 128) {
1168
+ inspected = `${inspected.slice(0, 128)}...`;
1169
+ }
1170
+ const type = name.includes(".") ? "property" : "argument";
1171
+ super(`The ${type} '${name}' ${reason}. Received ${inspected}`);
1172
+ }
1173
+ };
1174
+ var ERR_INVALID_CHAR = class extends TypeError {
1175
+ constructor(name, field) {
1176
+ let msg = `Invalid character in ${name}`;
1177
+ if (field !== void 0) {
1178
+ msg += ` ["${field}"]`;
1179
+ }
1180
+ super(msg);
1181
+ }
1182
+ };
1183
+ var ERR_HTTP_INVALID_HEADER_VALUE = class extends TypeError {
1184
+ constructor(value, name) {
1185
+ super(`Invalid value "${value}" for header "${name}"`);
1186
+ }
1187
+ };
1188
+ var ERR_HTTP_INVALID_STATUS_CODE = class extends RangeError {
1189
+ originalStatusCode;
1190
+ constructor(originalStatusCode) {
1191
+ super(`Invalid status code: ${originalStatusCode}`);
1192
+ this.originalStatusCode = originalStatusCode;
1193
+ }
1194
+ };
1195
+ var ERR_HTTP_TRAILER_INVALID = class extends Error {
1196
+ constructor() {
1197
+ super(`Trailers are invalid with this transfer encoding`);
1198
+ }
1199
+ };
1200
+ var ERR_INVALID_ARG_TYPE = class extends TypeError {
1201
+ constructor(name, expected, actual) {
1202
+ if (!Array.isArray(expected)) {
1203
+ expected = [expected];
1204
+ }
1205
+ let msg = "The ";
1206
+ if (name.endsWith(" argument")) {
1207
+ msg += `${name} `;
1208
+ } else {
1209
+ const type = name.includes(".") ? "property" : "argument";
1210
+ msg += `"${name}" ${type} `;
1211
+ }
1212
+ msg += "must be ";
1213
+ const types = [];
1214
+ const instances = [];
1215
+ const other = [];
1216
+ for (const value of expected) {
1217
+ if (kTypes.includes(value)) {
1218
+ types.push(value.toLowerCase());
1219
+ } else if (classRegExp.exec(value) !== null) {
1220
+ instances.push(value);
1221
+ } else {
1222
+ other.push(value);
1223
+ }
1224
+ }
1225
+ if (instances.length > 0) {
1226
+ const pos = types.indexOf("object");
1227
+ if (pos !== -1) {
1228
+ types.splice(pos, 1);
1229
+ instances.push("Object");
1230
+ }
1231
+ }
1232
+ if (types.length > 0) {
1233
+ if (types.length > 2) {
1234
+ const last = types.pop();
1235
+ msg += `one of type ${types.join(", ")}, or ${last}`;
1236
+ } else if (types.length === 2) {
1237
+ msg += `one of type ${types[0]} or ${types[1]}`;
1238
+ } else {
1239
+ msg += `of type ${types[0]}`;
1240
+ }
1241
+ if (instances.length > 0 || other.length > 0)
1242
+ msg += " or ";
1243
+ }
1244
+ if (instances.length > 0) {
1245
+ if (instances.length > 2) {
1246
+ const last = instances.pop();
1247
+ msg += `an instance of ${instances.join(", ")}, or ${last}`;
1248
+ } else {
1249
+ msg += `an instance of ${instances[0]}`;
1250
+ if (instances.length === 2) {
1251
+ msg += ` or ${instances[1]}`;
1252
+ }
1253
+ }
1254
+ if (other.length > 0)
1255
+ msg += " or ";
1256
+ }
1257
+ if (other.length > 0) {
1258
+ if (other.length > 2) {
1259
+ const last = other.pop();
1260
+ msg += `one of ${other.join(", ")}, or ${last}`;
1261
+ } else if (other.length === 2) {
1262
+ msg += `one of ${other[0]} or ${other[1]}`;
1263
+ } else {
1264
+ if (other[0].toLowerCase() !== other[0])
1265
+ msg += "an ";
1266
+ msg += `${other[0]}`;
1267
+ }
1268
+ }
1269
+ msg += `. Received ${determineSpecificType(actual)}`;
1270
+ super(msg);
1271
+ }
1272
+ };
1273
+ var ERR_INVALID_HTTP_TOKEN = class extends TypeError {
1274
+ constructor(name, field) {
1275
+ super(`${name} must be a valid HTTP token ["${field}"]`);
1276
+ }
1277
+ };
1278
+ var ERR_METHOD_NOT_IMPLEMENTED = class extends Error {
1279
+ constructor(methodName) {
1280
+ super(`The ${methodName} method is not implemented`);
1281
+ }
1282
+ };
1283
+ var ERR_STREAM_ALREADY_FINISHED = class extends Error {
1284
+ constructor(methodName) {
1285
+ super(`Cannot call ${methodName} after a stream was finished`);
1286
+ }
1287
+ };
1288
+ var ERR_STREAM_CANNOT_PIPE = class extends Error {
1289
+ constructor() {
1290
+ super(`Cannot pipe, not readable`);
1291
+ }
1292
+ };
1293
+ var ERR_STREAM_DESTROYED = class extends Error {
1294
+ constructor(methodName) {
1295
+ super(`Cannot call ${methodName} after a stream was destroyed`);
1296
+ }
1297
+ };
1298
+ var ERR_STREAM_NULL_VALUES = class extends TypeError {
1299
+ constructor() {
1300
+ super(`May not write null values to stream`);
1301
+ }
1302
+ };
1303
+ var ERR_STREAM_WRITE_AFTER_END = class extends Error {
1304
+ constructor() {
1305
+ super(`write after end`);
1306
+ }
1307
+ };
1308
+
1309
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/http-incoming.js
1310
+ var kHeaders = Symbol("kHeaders");
1311
+ var kHeadersDistinct = Symbol("kHeadersDistinct");
1312
+ var kHeadersCount = Symbol("kHeadersCount");
1313
+ var kTrailers = Symbol("kTrailers");
1314
+ var kTrailersDistinct = Symbol("kTrailersDistinct");
1315
+ var kTrailersCount = Symbol("kTrailersCount");
1316
+ var FetchIncomingMessage = class extends stream.Readable {
1317
+ get socket() {
1318
+ return null;
1319
+ }
1320
+ set socket(_val) {
1321
+ throw new ERR_METHOD_NOT_IMPLEMENTED("socket");
1322
+ }
1323
+ httpVersionMajor;
1324
+ httpVersionMinor;
1325
+ httpVersion;
1326
+ complete = false;
1327
+ [kHeaders] = null;
1328
+ [kHeadersDistinct] = null;
1329
+ [kHeadersCount] = 0;
1330
+ rawHeaders = [];
1331
+ [kTrailers] = null;
1332
+ [kTrailersDistinct] = null;
1333
+ [kTrailersCount] = 0;
1334
+ rawTrailers = [];
1335
+ joinDuplicateHeaders = false;
1336
+ aborted = false;
1337
+ upgrade = false;
1338
+ // request (server) only
1339
+ url = "";
1340
+ method;
1341
+ // TODO: Support ClientRequest
1342
+ // statusCode = null;
1343
+ // statusMessage = null;
1344
+ // client = socket;
1345
+ _consuming;
1346
+ _dumped;
1347
+ // The underlying ReadableStream
1348
+ _stream = null;
1349
+ constructor() {
1350
+ const streamOptions = {};
1351
+ super(streamOptions);
1352
+ this._readableState.readingMore = true;
1353
+ this._consuming = false;
1354
+ this._dumped = false;
1355
+ }
1356
+ get connection() {
1357
+ return null;
1358
+ }
1359
+ set connection(_socket) {
1360
+ console.error("No support for IncomingMessage.connection");
1361
+ }
1362
+ get headers() {
1363
+ if (!this[kHeaders]) {
1364
+ this[kHeaders] = {};
1365
+ const src = this.rawHeaders;
1366
+ const dst = this[kHeaders];
1367
+ for (let n2 = 0; n2 < this[kHeadersCount]; n2 += 2) {
1368
+ this._addHeaderLine(src[n2], src[n2 + 1], dst);
1369
+ }
1370
+ }
1371
+ return this[kHeaders];
1372
+ }
1373
+ set headers(val) {
1374
+ this[kHeaders] = val;
1375
+ }
1376
+ get headersDistinct() {
1377
+ if (!this[kHeadersDistinct]) {
1378
+ this[kHeadersDistinct] = {};
1379
+ const src = this.rawHeaders;
1380
+ const dst = this[kHeadersDistinct];
1381
+ for (let n2 = 0; n2 < this[kHeadersCount]; n2 += 2) {
1382
+ this._addHeaderLineDistinct(src[n2], src[n2 + 1], dst);
1383
+ }
1384
+ }
1385
+ return this[kHeadersDistinct];
1386
+ }
1387
+ set headersDistinct(val) {
1388
+ this[kHeadersDistinct] = val;
1389
+ }
1390
+ get trailers() {
1391
+ if (!this[kTrailers]) {
1392
+ this[kTrailers] = {};
1393
+ const src = this.rawTrailers;
1394
+ const dst = this[kTrailers];
1395
+ for (let n2 = 0; n2 < this[kTrailersCount]; n2 += 2) {
1396
+ this._addHeaderLine(src[n2], src[n2 + 1], dst);
1397
+ }
1398
+ }
1399
+ return this[kTrailers];
1400
+ }
1401
+ set trailers(val) {
1402
+ this[kTrailers] = val;
1403
+ }
1404
+ get trailersDistinct() {
1405
+ if (!this[kTrailersDistinct]) {
1406
+ this[kTrailersDistinct] = {};
1407
+ const src = this.rawTrailers;
1408
+ const dst = this[kTrailersDistinct];
1409
+ for (let n2 = 0; n2 < this[kTrailersCount]; n2 += 2) {
1410
+ this._addHeaderLineDistinct(src[n2], src[n2 + 1], dst);
1411
+ }
1412
+ }
1413
+ return this[kTrailersDistinct];
1414
+ }
1415
+ set trailersDistinct(val) {
1416
+ this[kTrailersDistinct] = val;
1417
+ }
1418
+ setTimeout(msecs, callback) {
1419
+ return this;
1420
+ }
1421
+ async _read(n2) {
1422
+ if (!this._consuming) {
1423
+ this._readableState.readingMore = false;
1424
+ this._consuming = true;
1425
+ }
1426
+ if (this._stream == null) {
1427
+ this.complete = true;
1428
+ this.push(null);
1429
+ return;
1430
+ }
1431
+ const reader = this._stream.getReader();
1432
+ try {
1433
+ const data = await reader.read();
1434
+ if (data.done) {
1435
+ this.complete = true;
1436
+ this.push(null);
1437
+ } else {
1438
+ this.push(data.value);
1439
+ }
1440
+ } catch (e2) {
1441
+ this.destroy(e2);
1442
+ } finally {
1443
+ reader.releaseLock();
1444
+ }
1445
+ }
1446
+ _destroy(err, cb) {
1447
+ if (!this.readableEnded || !this.complete) {
1448
+ this.aborted = true;
1449
+ this.emit("aborted");
1450
+ }
1451
+ setTimeout(onError, 0, this, err, cb);
1452
+ }
1453
+ _addHeaderLines(headers, n2) {
1454
+ if (headers?.length) {
1455
+ let dest;
1456
+ if (this.complete) {
1457
+ this.rawTrailers = headers;
1458
+ this[kTrailersCount] = n2;
1459
+ dest = this[kTrailers];
1460
+ } else {
1461
+ this.rawHeaders = headers;
1462
+ this[kHeadersCount] = n2;
1463
+ dest = this[kHeaders];
1464
+ }
1465
+ if (dest) {
1466
+ for (let i2 = 0; i2 < n2; i2 += 2) {
1467
+ this._addHeaderLine(headers[i2], headers[i2 + 1], dest);
1468
+ }
1469
+ }
1470
+ }
1471
+ }
1472
+ // Add the given (field, value) pair to the message
1473
+ //
1474
+ // Per RFC2616, section 4.2 it is acceptable to join multiple instances of the
1475
+ // same header with a ', ' if the header in question supports specification of
1476
+ // multiple values this way. The one exception to this is the Cookie header,
1477
+ // which has multiple values joined with a '; ' instead. If a header's values
1478
+ // cannot be joined in either of these ways, we declare the first instance the
1479
+ // winner and drop the second. Extended header fields (those beginning with
1480
+ // 'x-') are always joined.
1481
+ _addHeaderLine(field, value, dest) {
1482
+ field = matchKnownFields(field);
1483
+ const flag = field.charCodeAt(0);
1484
+ if (flag === 0 || flag === 2) {
1485
+ field = field.slice(1);
1486
+ if (typeof dest[field] === "string") {
1487
+ dest[field] += (flag === 0 ? ", " : "; ") + value;
1488
+ } else {
1489
+ dest[field] = value;
1490
+ }
1491
+ } else if (flag === 1) {
1492
+ if (dest["set-cookie"] !== void 0) {
1493
+ dest["set-cookie"].push(value);
1494
+ } else {
1495
+ dest["set-cookie"] = [value];
1496
+ }
1497
+ } else if (this.joinDuplicateHeaders) {
1498
+ if (dest[field] === void 0) {
1499
+ dest[field] = value;
1500
+ } else {
1501
+ dest[field] += ", " + value;
1502
+ }
1503
+ } else if (dest[field] === void 0) {
1504
+ dest[field] = value;
1505
+ }
1506
+ }
1507
+ _addHeaderLineDistinct(field, value, dest) {
1508
+ field = field.toLowerCase();
1509
+ if (!dest[field]) {
1510
+ dest[field] = [value];
1511
+ } else {
1512
+ dest[field].push(value);
1513
+ }
1514
+ }
1515
+ // Call this instead of resume() if we want to just
1516
+ // dump all the data to /dev/null
1517
+ _dump() {
1518
+ if (!this._dumped) {
1519
+ this._dumped = true;
1520
+ this.removeAllListeners("data");
1521
+ this.resume();
1522
+ }
1523
+ }
1524
+ };
1525
+ function matchKnownFields(field, lowercased = false) {
1526
+ switch (field.length) {
1527
+ case 3:
1528
+ if (field === "Age" || field === "age")
1529
+ return "age";
1530
+ break;
1531
+ case 4:
1532
+ if (field === "Host" || field === "host")
1533
+ return "host";
1534
+ if (field === "From" || field === "from")
1535
+ return "from";
1536
+ if (field === "ETag" || field === "etag")
1537
+ return "etag";
1538
+ if (field === "Date" || field === "date")
1539
+ return "\0date";
1540
+ if (field === "Vary" || field === "vary")
1541
+ return "\0vary";
1542
+ break;
1543
+ case 6:
1544
+ if (field === "Server" || field === "server")
1545
+ return "server";
1546
+ if (field === "Cookie" || field === "cookie")
1547
+ return "cookie";
1548
+ if (field === "Origin" || field === "origin")
1549
+ return "\0origin";
1550
+ if (field === "Expect" || field === "expect")
1551
+ return "\0expect";
1552
+ if (field === "Accept" || field === "accept")
1553
+ return "\0accept";
1554
+ break;
1555
+ case 7:
1556
+ if (field === "Referer" || field === "referer")
1557
+ return "referer";
1558
+ if (field === "Expires" || field === "expires")
1559
+ return "expires";
1560
+ if (field === "Upgrade" || field === "upgrade")
1561
+ return "\0upgrade";
1562
+ break;
1563
+ case 8:
1564
+ if (field === "Location" || field === "location")
1565
+ return "location";
1566
+ if (field === "If-Match" || field === "if-match")
1567
+ return "\0if-match";
1568
+ break;
1569
+ case 10:
1570
+ if (field === "User-Agent" || field === "user-agent")
1571
+ return "user-agent";
1572
+ if (field === "Set-Cookie" || field === "set-cookie")
1573
+ return "";
1574
+ if (field === "Connection" || field === "connection")
1575
+ return "\0connection";
1576
+ break;
1577
+ case 11:
1578
+ if (field === "Retry-After" || field === "retry-after")
1579
+ return "retry-after";
1580
+ break;
1581
+ case 12:
1582
+ if (field === "Content-Type" || field === "content-type")
1583
+ return "content-type";
1584
+ if (field === "Max-Forwards" || field === "max-forwards")
1585
+ return "max-forwards";
1586
+ break;
1587
+ case 13:
1588
+ if (field === "Authorization" || field === "authorization")
1589
+ return "authorization";
1590
+ if (field === "Last-Modified" || field === "last-modified")
1591
+ return "last-modified";
1592
+ if (field === "Cache-Control" || field === "cache-control")
1593
+ return "\0cache-control";
1594
+ if (field === "If-None-Match" || field === "if-none-match")
1595
+ return "\0if-none-match";
1596
+ break;
1597
+ case 14:
1598
+ if (field === "Content-Length" || field === "content-length")
1599
+ return "content-length";
1600
+ break;
1601
+ case 15:
1602
+ if (field === "Accept-Encoding" || field === "accept-encoding")
1603
+ return "\0accept-encoding";
1604
+ if (field === "Accept-Language" || field === "accept-language")
1605
+ return "\0accept-language";
1606
+ if (field === "X-Forwarded-For" || field === "x-forwarded-for")
1607
+ return "\0x-forwarded-for";
1608
+ break;
1609
+ case 16:
1610
+ if (field === "Content-Encoding" || field === "content-encoding")
1611
+ return "\0content-encoding";
1612
+ if (field === "X-Forwarded-Host" || field === "x-forwarded-host")
1613
+ return "\0x-forwarded-host";
1614
+ break;
1615
+ case 17:
1616
+ if (field === "If-Modified-Since" || field === "if-modified-since")
1617
+ return "if-modified-since";
1618
+ if (field === "Transfer-Encoding" || field === "transfer-encoding")
1619
+ return "\0transfer-encoding";
1620
+ if (field === "X-Forwarded-Proto" || field === "x-forwarded-proto")
1621
+ return "\0x-forwarded-proto";
1622
+ break;
1623
+ case 19:
1624
+ if (field === "Proxy-Authorization" || field === "proxy-authorization")
1625
+ return "proxy-authorization";
1626
+ if (field === "If-Unmodified-Since" || field === "if-unmodified-since")
1627
+ return "if-unmodified-since";
1628
+ break;
1629
+ }
1630
+ if (lowercased) {
1631
+ return "\0" + field;
1632
+ }
1633
+ return matchKnownFields(field.toLowerCase(), true);
1634
+ }
1635
+ function onError(self, error, cb) {
1636
+ if (self.listenerCount("error") === 0) {
1637
+ cb();
1638
+ } else {
1639
+ cb(error);
1640
+ }
1641
+ }
1642
+
1643
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/utils/types.js
1644
+ function validateString(value, name) {
1645
+ if (typeof value !== "string")
1646
+ throw new ERR_INVALID_ARG_TYPE(name, "string", value);
1647
+ }
1648
+ var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
1649
+ function validateLinkHeaderFormat(value, name) {
1650
+ if (typeof value === "undefined" || !linkValueRegExp.exec(value)) {
1651
+ throw new ERR_INVALID_ARG_VALUE(name, value, 'must be an array or string of format "</styles.css>; rel=preload; as=style"');
1652
+ }
1653
+ }
1654
+ function validateLinkHeaderValue(hints) {
1655
+ if (typeof hints === "string") {
1656
+ validateLinkHeaderFormat(hints, "hints");
1657
+ return hints;
1658
+ } else if (Array.isArray(hints)) {
1659
+ const hintsLength = hints.length;
1660
+ let result = "";
1661
+ if (hintsLength === 0) {
1662
+ return result;
1663
+ }
1664
+ for (let i2 = 0; i2 < hintsLength; i2++) {
1665
+ const link = hints[i2];
1666
+ validateLinkHeaderFormat(link, "hints");
1667
+ result += link;
1668
+ if (i2 !== hintsLength - 1) {
1669
+ result += ", ";
1670
+ }
1671
+ }
1672
+ return result;
1673
+ }
1674
+ throw new ERR_INVALID_ARG_VALUE("hints", hints, 'must be an array or string of format "</styles.css>; rel=preload; as=style"');
1675
+ }
1676
+ function isUint8Array(value) {
1677
+ return value != null && value[Symbol.toStringTag] === "Uint8Array";
1678
+ }
1679
+
1680
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/internal-http.js
1681
+ var kNeedDrain = Symbol("kNeedDrain");
1682
+ var kOutHeaders = Symbol("kOutHeaders");
1683
+ function utcDate() {
1684
+ return (/* @__PURE__ */ new Date()).toUTCString();
1685
+ }
1686
+
1687
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/internal-streams-state.js
1688
+ function getDefaultHighWaterMark(objectMode) {
1689
+ return objectMode ? 16 : 64 * 1024;
1690
+ }
1691
+
1692
+ // ../../node_modules/.pnpm/fetch-to-node@2.1.0/node_modules/fetch-to-node/dist/fetch-to-node/http-common.js
1693
+ var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
1694
+ function checkIsHttpToken(val) {
1695
+ return tokenRegExp.test(val);
1696
+ }
1697
+ var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
1698
+ function checkInvalidHeaderChar(val) {
1699
+ return headerCharRegex.test(val);
1700
+ }
1701
+ var chunkExpression = /(?:^|\W)chunked(?:$|\W)/i;
1702
+ var kCorked = Symbol("corked");
1703
+ var kChunkedBuffer = Symbol("kChunkedBuffer");
1704
+ var kChunkedLength = Symbol("kChunkedLength");
1705
+ var kUniqueHeaders = Symbol("kUniqueHeaders");
1706
+ var kBytesWritten = Symbol("kBytesWritten");
1707
+ var kErrored = Symbol("errored");
1708
+ var kHighWaterMark = Symbol("kHighWaterMark");
1709
+ var kRejectNonStandardBodyWrites = Symbol("kRejectNonStandardBodyWrites");
1710
+ var nop = () => {
1711
+ };
1712
+ var RE_CONN_CLOSE = /(?:^|\W)close(?:$|\W)/i;
1713
+ function isCookieField(s3) {
1714
+ return s3.length === 6 && s3.toLowerCase() === "cookie";
1715
+ }
1716
+ function isContentDispositionField(s3) {
1717
+ return s3.length === 19 && s3.toLowerCase() === "content-disposition";
1718
+ }
1719
+ var WrittenDataBuffer = class {
1720
+ [kCorked] = 0;
1721
+ [kHighWaterMark] = getDefaultHighWaterMark();
1722
+ entries = [];
1723
+ onWrite;
1724
+ constructor(params = {}) {
1725
+ this.onWrite = params.onWrite;
1726
+ }
1727
+ write(data, encoding, callback) {
1728
+ this.entries.push({
1729
+ data,
1730
+ length: data.length,
1731
+ encoding,
1732
+ callback,
1733
+ written: false
1734
+ });
1735
+ this._flush();
1736
+ return true;
1737
+ }
1738
+ cork() {
1739
+ this[kCorked]++;
1740
+ }
1741
+ uncork() {
1742
+ this[kCorked]--;
1743
+ this._flush();
1744
+ }
1745
+ _flush() {
1746
+ if (this[kCorked] <= 0) {
1747
+ for (const [index, entry] of this.entries.entries()) {
1748
+ if (!entry.written) {
1749
+ entry.written = true;
1750
+ if (this.onWrite != null) {
1751
+ this.onWrite(index, entry);
1752
+ }
1753
+ if (entry.callback != null) {
1754
+ entry.callback.call(void 0);
1755
+ }
1756
+ }
1757
+ }
1758
+ }
1759
+ }
1760
+ get writableLength() {
1761
+ return this.entries.reduce((acc, entry) => {
1762
+ return acc + (entry.written && entry.length ? entry.length : 0);
1763
+ }, 0);
1764
+ }
1765
+ get writableHighWaterMark() {
1766
+ return this[kHighWaterMark];
1767
+ }
1768
+ get writableCorked() {
1769
+ return this[kCorked];
1770
+ }
1771
+ };
1772
+ var FetchOutgoingMessage = class extends stream.Writable {
1773
+ req;
1774
+ outputData;
1775
+ outputSize;
1776
+ // Difference from Node.js -
1777
+ // `writtenHeaderBytes` is the number of bytes the header has taken.
1778
+ // Since Node.js writes both the headers and body into the same outgoing
1779
+ // stream, it helps to keep track of this so that we can skip that many bytes
1780
+ // from the beginning of the stream when providing the outgoing stream.
1781
+ writtenHeaderBytes = 0;
1782
+ _last;
1783
+ chunkedEncoding;
1784
+ shouldKeepAlive;
1785
+ maxRequestsOnConnectionReached;
1786
+ _defaultKeepAlive;
1787
+ useChunkedEncodingByDefault;
1788
+ sendDate;
1789
+ _removedConnection;
1790
+ _removedContLen;
1791
+ _removedTE;
1792
+ strictContentLength;
1793
+ [kBytesWritten];
1794
+ _contentLength;
1795
+ _hasBody;
1796
+ _trailer;
1797
+ [kNeedDrain];
1798
+ finished;
1799
+ _headerSent;
1800
+ [kCorked];
1801
+ [kChunkedBuffer];
1802
+ [kChunkedLength];
1803
+ _closed;
1804
+ // Difference from Node.js -
1805
+ // In Node.js, this is a socket object.
1806
+ // [kSocket]: null;
1807
+ _header;
1808
+ [kOutHeaders];
1809
+ _keepAliveTimeout;
1810
+ _maxRequestsPerSocket;
1811
+ _onPendingData;
1812
+ [kUniqueHeaders];
1813
+ [kErrored];
1814
+ [kHighWaterMark];
1815
+ [kRejectNonStandardBodyWrites];
1816
+ _writtenDataBuffer = new WrittenDataBuffer({
1817
+ onWrite: this._onDataWritten.bind(this)
1818
+ });
1819
+ constructor(req, options) {
1820
+ super();
1821
+ this.req = req;
1822
+ this.outputData = [];
1823
+ this.outputSize = 0;
1824
+ this.destroyed = false;
1825
+ this._last = false;
1826
+ this.chunkedEncoding = false;
1827
+ this.shouldKeepAlive = true;
1828
+ this.maxRequestsOnConnectionReached = false;
1829
+ this._defaultKeepAlive = true;
1830
+ this.useChunkedEncodingByDefault = true;
1831
+ this.sendDate = false;
1832
+ this._removedConnection = false;
1833
+ this._removedContLen = false;
1834
+ this._removedTE = false;
1835
+ this.strictContentLength = false;
1836
+ this[kBytesWritten] = 0;
1837
+ this._contentLength = null;
1838
+ this._hasBody = true;
1839
+ this._trailer = "";
1840
+ this[kNeedDrain] = false;
1841
+ this.finished = false;
1842
+ this._headerSent = false;
1843
+ this[kCorked] = 0;
1844
+ this[kChunkedBuffer] = [];
1845
+ this[kChunkedLength] = 0;
1846
+ this._closed = false;
1847
+ this._header = null;
1848
+ this[kOutHeaders] = null;
1849
+ this._keepAliveTimeout = 0;
1850
+ this._onPendingData = nop;
1851
+ this[kErrored] = null;
1852
+ this[kHighWaterMark] = options?.highWaterMark ?? getDefaultHighWaterMark();
1853
+ this[kRejectNonStandardBodyWrites] = options?.rejectNonStandardBodyWrites ?? false;
1854
+ this[kUniqueHeaders] = null;
1855
+ }
1856
+ _renderHeaders() {
1857
+ if (this._header) {
1858
+ throw new ERR_HTTP_HEADERS_SENT("render");
1859
+ }
1860
+ const headersMap = this[kOutHeaders];
1861
+ const headers = {};
1862
+ if (headersMap !== null) {
1863
+ const keys = Object.keys(headersMap);
1864
+ for (let i2 = 0, l2 = keys.length; i2 < l2; i2++) {
1865
+ const key = keys[i2];
1866
+ headers[headersMap[key][0]] = headersMap[key][1];
1867
+ }
1868
+ }
1869
+ return headers;
1870
+ }
1871
+ cork() {
1872
+ this[kCorked]++;
1873
+ if (this._writtenDataBuffer != null) {
1874
+ this._writtenDataBuffer.cork();
1875
+ }
1876
+ }
1877
+ uncork() {
1878
+ this[kCorked]--;
1879
+ if (this._writtenDataBuffer != null) {
1880
+ this._writtenDataBuffer.uncork();
1881
+ }
1882
+ if (this[kCorked] || this[kChunkedBuffer].length === 0) {
1883
+ return;
1884
+ }
1885
+ const buf = this[kChunkedBuffer];
1886
+ for (const { data, encoding, callback } of buf) {
1887
+ this._send(data ?? "", encoding, callback);
1888
+ }
1889
+ this[kChunkedBuffer].length = 0;
1890
+ this[kChunkedLength] = 0;
1891
+ }
1892
+ setTimeout(msecs, callback) {
1893
+ return this;
1894
+ }
1895
+ destroy(error) {
1896
+ if (this.destroyed) {
1897
+ return this;
1898
+ }
1899
+ this.destroyed = true;
1900
+ this[kErrored] = error;
1901
+ return this;
1902
+ }
1903
+ _send(data, encoding, callback, byteLength) {
1904
+ if (!this._headerSent) {
1905
+ const header = this._header;
1906
+ if (typeof data === "string" && (encoding === "utf8" || encoding === "latin1" || !encoding)) {
1907
+ data = header + data;
1908
+ } else {
1909
+ this.outputData.unshift({
1910
+ data: header,
1911
+ encoding: "latin1",
1912
+ callback: void 0
1913
+ });
1914
+ this.outputSize += header.length;
1915
+ this._onPendingData(header.length);
1916
+ }
1917
+ this._headerSent = true;
1918
+ this.writtenHeaderBytes = header.length;
1919
+ const [statusLine, ...headerLines] = this._header.split("\r\n");
1920
+ const STATUS_LINE_REGEXP = /^HTTP\/1\.1 (?<statusCode>\d+) (?<statusMessage>.*)$/;
1921
+ const statusLineResult = STATUS_LINE_REGEXP.exec(statusLine);
1922
+ if (statusLineResult == null) {
1923
+ throw new Error("Unexpected! Status line was " + statusLine);
1924
+ }
1925
+ const { statusCode: statusCodeText, statusMessage } = statusLineResult.groups ?? {};
1926
+ const statusCode = parseInt(statusCodeText, 10);
1927
+ const headers = [];
1928
+ for (const headerLine of headerLines) {
1929
+ if (headerLine !== "") {
1930
+ const pos = headerLine.indexOf(": ");
1931
+ const k = headerLine.slice(0, pos);
1932
+ const v = headerLine.slice(pos + 2);
1933
+ headers.push([k, v]);
1934
+ }
1935
+ }
1936
+ const event = {
1937
+ statusCode,
1938
+ statusMessage,
1939
+ headers
1940
+ };
1941
+ this.emit("_headersSent", event);
1942
+ }
1943
+ return this._writeRaw(data, encoding, callback, byteLength);
1944
+ }
1945
+ _writeRaw(data, encoding, callback, size) {
1946
+ if (typeof encoding === "function") {
1947
+ callback = encoding;
1948
+ encoding = null;
1949
+ }
1950
+ if (this._writtenDataBuffer != null) {
1951
+ if (this.outputData.length) {
1952
+ this._flushOutput(this._writtenDataBuffer);
1953
+ }
1954
+ return this._writtenDataBuffer.write(data, encoding, callback);
1955
+ }
1956
+ this.outputData.push({ data, encoding, callback });
1957
+ this.outputSize += data.length;
1958
+ this._onPendingData(data.length);
1959
+ return this.outputSize < this[kHighWaterMark];
1960
+ }
1961
+ _onDataWritten(index, entry) {
1962
+ const event = { index, entry };
1963
+ this.emit("_dataWritten", event);
1964
+ }
1965
+ _storeHeader(firstLine, headers) {
1966
+ const state = {
1967
+ connection: false,
1968
+ contLen: false,
1969
+ te: false,
1970
+ date: false,
1971
+ expect: false,
1972
+ trailer: false,
1973
+ header: firstLine
1974
+ };
1975
+ if (headers) {
1976
+ if (headers === this[kOutHeaders]) {
1977
+ for (const key in headers) {
1978
+ const entry = headers[key];
1979
+ processHeader(this, state, entry[0], entry[1], false);
1980
+ }
1981
+ } else if (Array.isArray(headers)) {
1982
+ if (headers.length && Array.isArray(headers[0])) {
1983
+ for (let i2 = 0; i2 < headers.length; i2++) {
1984
+ const entry = headers[i2];
1985
+ processHeader(this, state, entry[0], entry[1], true);
1986
+ }
1987
+ } else {
1988
+ if (headers.length % 2 !== 0) {
1989
+ throw new ERR_INVALID_ARG_VALUE("headers", headers);
1990
+ }
1991
+ for (let n2 = 0; n2 < headers.length; n2 += 2) {
1992
+ processHeader(this, state, headers[n2], headers[n2 + 1], true);
1993
+ }
1994
+ }
1995
+ } else {
1996
+ for (const key in headers) {
1997
+ if (headers.hasOwnProperty(key)) {
1998
+ const _headers = headers;
1999
+ processHeader(this, state, key, _headers[key], true);
2000
+ }
2001
+ }
2002
+ }
2003
+ }
2004
+ let { header } = state;
2005
+ if (this.sendDate && !state.date) {
2006
+ header += "Date: " + utcDate() + "\r\n";
2007
+ }
2008
+ if (this.chunkedEncoding && (this.statusCode === 204 || this.statusCode === 304)) {
2009
+ this.chunkedEncoding = false;
2010
+ this.shouldKeepAlive = false;
2011
+ }
2012
+ if (this._removedConnection) {
2013
+ this._last = !this.shouldKeepAlive;
2014
+ } else if (!state.connection) {
2015
+ const shouldSendKeepAlive = this.shouldKeepAlive && (state.contLen || this.useChunkedEncodingByDefault);
2016
+ if (shouldSendKeepAlive && this.maxRequestsOnConnectionReached) {
2017
+ header += "Connection: close\r\n";
2018
+ } else if (shouldSendKeepAlive) {
2019
+ header += "Connection: keep-alive\r\n";
2020
+ if (this._keepAliveTimeout && this._defaultKeepAlive) {
2021
+ const timeoutSeconds = Math.floor(this._keepAliveTimeout / 1e3);
2022
+ let max = "";
2023
+ if (this._maxRequestsPerSocket && ~~this._maxRequestsPerSocket > 0) {
2024
+ max = `, max=${this._maxRequestsPerSocket}`;
2025
+ }
2026
+ header += `Keep-Alive: timeout=${timeoutSeconds}${max}\r
2027
+ `;
2028
+ }
2029
+ } else {
2030
+ this._last = true;
2031
+ header += "Connection: close\r\n";
2032
+ }
2033
+ }
2034
+ if (!state.contLen && !state.te) {
2035
+ if (!this._hasBody) {
2036
+ this.chunkedEncoding = false;
2037
+ } else if (!this.useChunkedEncodingByDefault) {
2038
+ this._last = true;
2039
+ } else if (!state.trailer && !this._removedContLen && typeof this._contentLength === "number") {
2040
+ header += "Content-Length: " + this._contentLength + "\r\n";
2041
+ } else if (!this._removedTE) {
2042
+ header += "Transfer-Encoding: chunked\r\n";
2043
+ this.chunkedEncoding = true;
2044
+ } else {
2045
+ this._last = true;
2046
+ }
2047
+ }
2048
+ if (this.chunkedEncoding !== true && state.trailer) {
2049
+ throw new ERR_HTTP_TRAILER_INVALID();
2050
+ }
2051
+ this._header = header + "\r\n";
2052
+ this._headerSent = false;
2053
+ if (state.expect) {
2054
+ this._send("");
2055
+ }
2056
+ }
2057
+ get _headers() {
2058
+ console.warn("DEP0066: OutgoingMessage.prototype._headers is deprecated");
2059
+ return this.getHeaders();
2060
+ }
2061
+ set _headers(val) {
2062
+ console.warn("DEP0066: OutgoingMessage.prototype._headers is deprecated");
2063
+ if (val == null) {
2064
+ this[kOutHeaders] = null;
2065
+ } else if (typeof val === "object") {
2066
+ const headers = this[kOutHeaders] = /* @__PURE__ */ Object.create(null);
2067
+ const keys = Object.keys(val);
2068
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2069
+ const name = keys[i2];
2070
+ headers[name.toLowerCase()] = [name, val[name]];
2071
+ }
2072
+ }
2073
+ }
2074
+ get connection() {
2075
+ return null;
2076
+ }
2077
+ set connection(_socket) {
2078
+ console.error("No support for OutgoingMessage.connection");
2079
+ }
2080
+ get socket() {
2081
+ return null;
2082
+ }
2083
+ set socket(_socket) {
2084
+ console.error("No support for OutgoingMessage.socket");
2085
+ }
2086
+ get _headerNames() {
2087
+ console.warn("DEP0066: OutgoingMessage.prototype._headerNames is deprecated");
2088
+ const headers = this[kOutHeaders];
2089
+ if (headers !== null) {
2090
+ const out = /* @__PURE__ */ Object.create(null);
2091
+ const keys = Object.keys(headers);
2092
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2093
+ const key = keys[i2];
2094
+ const val = headers[key][0];
2095
+ out[key] = val;
2096
+ }
2097
+ return out;
2098
+ }
2099
+ return null;
2100
+ }
2101
+ set _headerNames(val) {
2102
+ console.warn("DEP0066: OutgoingMessage.prototype._headerNames is deprecated");
2103
+ if (typeof val === "object" && val !== null) {
2104
+ const headers = this[kOutHeaders];
2105
+ if (!headers)
2106
+ return;
2107
+ const keys = Object.keys(val);
2108
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2109
+ const header = headers[keys[i2]];
2110
+ if (header)
2111
+ header[0] = val[keys[i2]];
2112
+ }
2113
+ }
2114
+ }
2115
+ setHeader(name, value) {
2116
+ if (this._header) {
2117
+ throw new ERR_HTTP_HEADERS_SENT("set");
2118
+ }
2119
+ validateHeaderName(name);
2120
+ validateHeaderValue(name, value);
2121
+ let headers = this[kOutHeaders];
2122
+ if (headers === null) {
2123
+ this[kOutHeaders] = headers = { __proto__: null };
2124
+ }
2125
+ headers[name.toLowerCase()] = [name, value];
2126
+ return this;
2127
+ }
2128
+ setHeaders(headers) {
2129
+ if (this._header) {
2130
+ throw new ERR_HTTP_HEADERS_SENT("set");
2131
+ }
2132
+ if (!headers || Array.isArray(headers) || typeof headers.keys !== "function" || typeof headers.get !== "function") {
2133
+ throw new ERR_INVALID_ARG_TYPE("headers", ["Headers", "Map"], headers);
2134
+ }
2135
+ const cookies = [];
2136
+ for (const { 0: key, 1: value } of headers) {
2137
+ if (key === "set-cookie") {
2138
+ if (Array.isArray(value)) {
2139
+ cookies.push(...value);
2140
+ } else {
2141
+ cookies.push(value);
2142
+ }
2143
+ continue;
2144
+ }
2145
+ this.setHeader(key, value);
2146
+ }
2147
+ if (cookies.length) {
2148
+ this.setHeader("set-cookie", cookies);
2149
+ }
2150
+ return this;
2151
+ }
2152
+ appendHeader(name, value) {
2153
+ if (this._header) {
2154
+ throw new ERR_HTTP_HEADERS_SENT("append");
2155
+ }
2156
+ validateHeaderName(name);
2157
+ validateHeaderValue(name, value);
2158
+ const field = name.toLowerCase();
2159
+ const headers = this[kOutHeaders];
2160
+ if (headers === null || !headers[field]) {
2161
+ return this.setHeader(name, value);
2162
+ }
2163
+ if (!Array.isArray(headers[field][1])) {
2164
+ headers[field][1] = [headers[field][1]];
2165
+ }
2166
+ const existingValues = headers[field][1];
2167
+ if (Array.isArray(value)) {
2168
+ for (let i2 = 0, length = value.length; i2 < length; i2++) {
2169
+ existingValues.push(value[i2]);
2170
+ }
2171
+ } else {
2172
+ existingValues.push(value);
2173
+ }
2174
+ return this;
2175
+ }
2176
+ getHeader(name) {
2177
+ validateString(name, "name");
2178
+ const headers = this[kOutHeaders];
2179
+ if (headers === null) {
2180
+ return;
2181
+ }
2182
+ const entry = headers[name.toLowerCase()];
2183
+ return entry?.[1];
2184
+ }
2185
+ getHeaderNames() {
2186
+ return this[kOutHeaders] !== null ? Object.keys(this[kOutHeaders]) : [];
2187
+ }
2188
+ getRawHeaderNames() {
2189
+ const headersMap = this[kOutHeaders];
2190
+ if (headersMap === null)
2191
+ return [];
2192
+ const values = Object.values(headersMap);
2193
+ const headers = Array(values.length);
2194
+ for (let i2 = 0, l2 = values.length; i2 < l2; i2++) {
2195
+ headers[i2] = values[i2][0];
2196
+ }
2197
+ return headers;
2198
+ }
2199
+ getHeaders() {
2200
+ const headers = this[kOutHeaders];
2201
+ const ret = { __proto__: null };
2202
+ if (headers) {
2203
+ const keys = Object.keys(headers);
2204
+ for (let i2 = 0; i2 < keys.length; ++i2) {
2205
+ const key = keys[i2];
2206
+ const val = headers[key][1];
2207
+ ret[key] = val;
2208
+ }
2209
+ }
2210
+ return ret;
2211
+ }
2212
+ hasHeader(name) {
2213
+ validateString(name, "name");
2214
+ return this[kOutHeaders] !== null && !!this[kOutHeaders][name.toLowerCase()];
2215
+ }
2216
+ removeHeader(name) {
2217
+ validateString(name, "name");
2218
+ if (this._header) {
2219
+ throw new ERR_HTTP_HEADERS_SENT("remove");
2220
+ }
2221
+ const key = name.toLowerCase();
2222
+ switch (key) {
2223
+ case "connection":
2224
+ this._removedConnection = true;
2225
+ break;
2226
+ case "content-length":
2227
+ this._removedContLen = true;
2228
+ break;
2229
+ case "transfer-encoding":
2230
+ this._removedTE = true;
2231
+ break;
2232
+ case "date":
2233
+ this.sendDate = false;
2234
+ break;
2235
+ }
2236
+ if (this[kOutHeaders] !== null) {
2237
+ delete this[kOutHeaders][key];
2238
+ }
2239
+ }
2240
+ _implicitHeader() {
2241
+ throw new ERR_METHOD_NOT_IMPLEMENTED("_implicitHeader()");
2242
+ }
2243
+ get headersSent() {
2244
+ return !!this._header;
2245
+ }
2246
+ write(chunk, encoding, callback) {
2247
+ if (typeof encoding === "function") {
2248
+ callback = encoding;
2249
+ encoding = null;
2250
+ }
2251
+ const ret = write_(this, chunk, encoding, callback, false);
2252
+ if (!ret) {
2253
+ this[kNeedDrain] = true;
2254
+ }
2255
+ return ret;
2256
+ }
2257
+ addTrailers(headers) {
2258
+ this._trailer = "";
2259
+ const isArray = Array.isArray(headers);
2260
+ const keys = isArray ? [...headers.keys()] : Object.keys(headers);
2261
+ for (let i2 = 0, l2 = keys.length; i2 < l2; i2++) {
2262
+ let field, value;
2263
+ if (isArray) {
2264
+ const _headers = headers;
2265
+ const key = keys[i2];
2266
+ field = _headers[key][0];
2267
+ value = _headers[key][1];
2268
+ } else {
2269
+ const _headers = headers;
2270
+ const key = keys[i2];
2271
+ field = key;
2272
+ value = _headers[key];
2273
+ }
2274
+ validateHeaderName(field, "Trailer name");
2275
+ if (Array.isArray(value) && value.length > 1 && (!this[kUniqueHeaders] || !this[kUniqueHeaders].has(field.toLowerCase()))) {
2276
+ for (let j = 0, l3 = value.length; j < l3; j++) {
2277
+ if (checkInvalidHeaderChar(value[j])) {
2278
+ throw new ERR_INVALID_CHAR("trailer content", field);
2279
+ }
2280
+ this._trailer += field + ": " + value[j] + "\r\n";
2281
+ }
2282
+ } else {
2283
+ if (Array.isArray(value)) {
2284
+ value = value.join("; ");
2285
+ }
2286
+ if (checkInvalidHeaderChar(String(value))) {
2287
+ throw new ERR_INVALID_CHAR("trailer content", field);
2288
+ }
2289
+ this._trailer += field + ": " + value + "\r\n";
2290
+ }
2291
+ }
2292
+ }
2293
+ end(chunk, encoding, callback) {
2294
+ if (typeof chunk === "function") {
2295
+ callback = chunk;
2296
+ chunk = null;
2297
+ encoding = null;
2298
+ } else if (typeof encoding === "function") {
2299
+ callback = encoding;
2300
+ encoding = null;
2301
+ }
2302
+ if (chunk) {
2303
+ if (this.finished) {
2304
+ onError2(this, new ERR_STREAM_WRITE_AFTER_END(), typeof callback !== "function" ? nop : callback);
2305
+ return this;
2306
+ }
2307
+ if (this._writtenDataBuffer != null) {
2308
+ this._writtenDataBuffer.cork();
2309
+ }
2310
+ write_(this, chunk, encoding, null, true);
2311
+ } else if (this.finished) {
2312
+ if (typeof callback === "function") {
2313
+ if (!this.writableFinished) {
2314
+ this.on("finish", callback);
2315
+ } else {
2316
+ callback(new ERR_STREAM_ALREADY_FINISHED("end"));
2317
+ }
2318
+ }
2319
+ return this;
2320
+ } else if (!this._header) {
2321
+ if (this._writtenDataBuffer != null) {
2322
+ this._writtenDataBuffer.cork();
2323
+ }
2324
+ this._contentLength = 0;
2325
+ this._implicitHeader();
2326
+ }
2327
+ if (typeof callback === "function")
2328
+ this.once("finish", callback);
2329
+ if (strictContentLength(this) && this[kBytesWritten] !== this._contentLength) {
2330
+ throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(this[kBytesWritten], this._contentLength);
2331
+ }
2332
+ const finish = onFinish.bind(void 0, this);
2333
+ if (this._hasBody && this.chunkedEncoding) {
2334
+ this._send("", "latin1", finish);
2335
+ } else if (!this._headerSent || this.writableLength || chunk) {
2336
+ this._send("", "latin1", finish);
2337
+ } else {
2338
+ setTimeout(finish, 0);
2339
+ }
2340
+ if (this._writtenDataBuffer != null) {
2341
+ this._writtenDataBuffer.uncork();
2342
+ }
2343
+ this[kCorked] = 1;
2344
+ this.uncork();
2345
+ this.finished = true;
2346
+ if (this.outputData.length === 0 && this._writtenDataBuffer != null) {
2347
+ this._finish();
2348
+ }
2349
+ return this;
2350
+ }
2351
+ _finish() {
2352
+ this.emit("prefinish");
2353
+ }
2354
+ // No _flush() implementation?
2355
+ _flush() {
2356
+ if (this._writtenDataBuffer != null) {
2357
+ const ret = this._flushOutput(this._writtenDataBuffer);
2358
+ if (this.finished) {
2359
+ this._finish();
2360
+ } else if (ret && this[kNeedDrain]) {
2361
+ this[kNeedDrain] = false;
2362
+ this.emit("drain");
2363
+ }
2364
+ }
2365
+ }
2366
+ _flushOutput(dataBuffer) {
2367
+ while (this[kCorked]) {
2368
+ this[kCorked]--;
2369
+ dataBuffer.cork();
2370
+ }
2371
+ const outputLength = this.outputData.length;
2372
+ if (outputLength <= 0) {
2373
+ return void 0;
2374
+ }
2375
+ const outputData = this.outputData;
2376
+ dataBuffer.cork();
2377
+ let ret;
2378
+ for (let i2 = 0; i2 < outputLength; i2++) {
2379
+ const { data, encoding, callback } = outputData[i2];
2380
+ outputData[i2].data = null;
2381
+ ret = dataBuffer.write(data ?? "", encoding, callback);
2382
+ }
2383
+ dataBuffer.uncork();
2384
+ this.outputData = [];
2385
+ this._onPendingData(-this.outputSize);
2386
+ this.outputSize = 0;
2387
+ return ret;
2388
+ }
2389
+ flushHeaders() {
2390
+ if (!this._header) {
2391
+ this._implicitHeader();
2392
+ }
2393
+ this._send("");
2394
+ }
2395
+ pipe(destination) {
2396
+ this.emit("error", new ERR_STREAM_CANNOT_PIPE());
2397
+ return destination;
2398
+ }
2399
+ };
2400
+ function processHeader(self, state, key, value, validate) {
2401
+ if (validate) {
2402
+ validateHeaderName(key);
2403
+ }
2404
+ if (isContentDispositionField(key) && self._contentLength) {
2405
+ if (Array.isArray(value)) {
2406
+ for (let i2 = 0; i2 < value.length; i2++) {
2407
+ value[i2] = String(buffer.Buffer.from(String(value[i2]), "latin1"));
2408
+ }
2409
+ } else {
2410
+ value = String(buffer.Buffer.from(String(value), "latin1"));
2411
+ }
2412
+ }
2413
+ if (Array.isArray(value)) {
2414
+ if ((value.length < 2 || !isCookieField(key)) && (!self[kUniqueHeaders] || !self[kUniqueHeaders].has(key.toLowerCase()))) {
2415
+ for (let i2 = 0; i2 < value.length; i2++) {
2416
+ storeHeader(self, state, key, value[i2], validate);
2417
+ }
2418
+ return;
2419
+ }
2420
+ value = value.join("; ");
2421
+ }
2422
+ storeHeader(self, state, key, String(value), validate);
2423
+ }
2424
+ function storeHeader(self, state, key, value, validate) {
2425
+ if (validate) {
2426
+ validateHeaderValue(key, value);
2427
+ }
2428
+ state.header += key + ": " + value + "\r\n";
2429
+ matchHeader(self, state, key, value);
2430
+ }
2431
+ function validateHeaderName(name, label) {
2432
+ if (typeof name !== "string" || !name || !checkIsHttpToken(name)) {
2433
+ throw new ERR_INVALID_HTTP_TOKEN(label || "Header name", name);
2434
+ }
2435
+ }
2436
+ function validateHeaderValue(name, value) {
2437
+ if (value === void 0) {
2438
+ throw new ERR_HTTP_INVALID_HEADER_VALUE(String(value), name);
2439
+ }
2440
+ if (checkInvalidHeaderChar(String(value))) {
2441
+ throw new ERR_INVALID_CHAR("header content", name);
2442
+ }
2443
+ }
2444
+ function matchHeader(self, state, field, value) {
2445
+ if (field.length < 4 || field.length > 17)
2446
+ return;
2447
+ field = field.toLowerCase();
2448
+ switch (field) {
2449
+ case "connection":
2450
+ state.connection = true;
2451
+ self._removedConnection = false;
2452
+ if (RE_CONN_CLOSE.exec(value) !== null)
2453
+ self._last = true;
2454
+ else
2455
+ self.shouldKeepAlive = true;
2456
+ break;
2457
+ case "transfer-encoding":
2458
+ state.te = true;
2459
+ self._removedTE = false;
2460
+ if (chunkExpression.exec(value) !== null)
2461
+ self.chunkedEncoding = true;
2462
+ break;
2463
+ case "content-length":
2464
+ state.contLen = true;
2465
+ self._contentLength = +value;
2466
+ self._removedContLen = false;
2467
+ break;
2468
+ case "date":
2469
+ case "expect":
2470
+ case "trailer":
2471
+ state[field] = true;
2472
+ break;
2473
+ case "keep-alive":
2474
+ self._defaultKeepAlive = false;
2475
+ break;
2476
+ }
2477
+ }
2478
+ function onError2(msg, err, callback) {
2479
+ if (msg.destroyed) {
2480
+ return;
2481
+ }
2482
+ setTimeout(emitErrorNt, 0, msg, err, callback);
2483
+ }
2484
+ function emitErrorNt(msg, err, callback) {
2485
+ callback(err);
2486
+ if (typeof msg.emit === "function" && !msg.destroyed) {
2487
+ msg.emit("error", err);
2488
+ }
2489
+ }
2490
+ function strictContentLength(msg) {
2491
+ return msg.strictContentLength && msg._contentLength != null && msg._hasBody && !msg._removedContLen && !msg.chunkedEncoding && !msg.hasHeader("transfer-encoding");
2492
+ }
2493
+ function write_(msg, chunk, encoding, callback, fromEnd) {
2494
+ if (typeof callback !== "function") {
2495
+ callback = nop;
2496
+ }
2497
+ if (chunk === null) {
2498
+ throw new ERR_STREAM_NULL_VALUES();
2499
+ } else if (typeof chunk !== "string" && !isUint8Array(chunk)) {
2500
+ throw new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk);
2501
+ }
2502
+ let err = void 0;
2503
+ if (msg.finished) {
2504
+ err = new ERR_STREAM_WRITE_AFTER_END();
2505
+ } else if (msg.destroyed) {
2506
+ err = new ERR_STREAM_DESTROYED("write");
2507
+ }
2508
+ if (err) {
2509
+ if (!msg.destroyed) {
2510
+ onError2(msg, err, callback);
2511
+ } else {
2512
+ setTimeout(callback, 0, err);
2513
+ }
2514
+ return false;
2515
+ }
2516
+ let len = void 0;
2517
+ if (msg.strictContentLength) {
2518
+ len ??= typeof chunk === "string" ? buffer.Buffer.byteLength(chunk, encoding ?? void 0) : chunk.byteLength;
2519
+ if (strictContentLength(msg) && (fromEnd ? msg[kBytesWritten] + len !== msg._contentLength : msg[kBytesWritten] + len > (msg._contentLength ?? 0))) {
2520
+ throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(len + msg[kBytesWritten], msg._contentLength);
2521
+ }
2522
+ msg[kBytesWritten] += len;
2523
+ }
2524
+ if (!msg._header) {
2525
+ if (fromEnd) {
2526
+ len ??= typeof chunk === "string" ? buffer.Buffer.byteLength(chunk, encoding ?? void 0) : chunk.byteLength;
2527
+ msg._contentLength = len;
2528
+ }
2529
+ msg._implicitHeader();
2530
+ }
2531
+ if (!msg._hasBody) {
2532
+ if (msg[kRejectNonStandardBodyWrites]) {
2533
+ throw new ERR_HTTP_BODY_NOT_ALLOWED();
2534
+ } else {
2535
+ setTimeout(callback, 0);
2536
+ return true;
2537
+ }
2538
+ }
2539
+ if (!fromEnd && msg._writtenDataBuffer != null && !msg._writtenDataBuffer.writableCorked) {
2540
+ msg._writtenDataBuffer.cork();
2541
+ setTimeout(connectionCorkNT, 0, msg._writtenDataBuffer);
2542
+ }
2543
+ let ret;
2544
+ if (msg.chunkedEncoding && chunk.length !== 0) {
2545
+ len ??= typeof chunk === "string" ? buffer.Buffer.byteLength(chunk, encoding ?? void 0) : chunk.byteLength;
2546
+ if (msg[kCorked] && msg._headerSent) {
2547
+ msg[kChunkedBuffer].push({ data: chunk, encoding, callback });
2548
+ msg[kChunkedLength] += len;
2549
+ ret = msg[kChunkedLength] < msg[kHighWaterMark];
2550
+ } else {
2551
+ ret = msg._send(chunk, encoding, callback, len);
2552
+ }
2553
+ } else {
2554
+ ret = msg._send(chunk, encoding, callback, len);
2555
+ }
2556
+ return ret;
2557
+ }
2558
+ function connectionCorkNT(dataBuffer) {
2559
+ dataBuffer.uncork();
2560
+ }
2561
+ function onFinish(outmsg) {
2562
+ outmsg.emit("finish");
2563
+ }
2564
+ Object.defineProperties(FetchOutgoingMessage.prototype, {
2565
+ errored: {
2566
+ get() {
2567
+ return this[kErrored];
2568
+ }
2569
+ },
2570
+ closed: {
2571
+ get() {
2572
+ return this._closed;
2573
+ }
2574
+ },
2575
+ writableFinished: {
2576
+ get() {
2577
+ return this.finished && this.outputSize === 0 && (this._writtenDataBuffer == null || this._writtenDataBuffer.writableLength === 0);
2578
+ }
2579
+ },
2580
+ writableObjectMode: {
2581
+ get() {
2582
+ return false;
2583
+ }
2584
+ },
2585
+ writableLength: {
2586
+ get() {
2587
+ return this.outputSize + this[kChunkedLength] + (this._writtenDataBuffer != null ? this._writtenDataBuffer.writableLength : 0);
2588
+ }
2589
+ },
2590
+ writableHighWaterMark: {
2591
+ get() {
2592
+ return this._writtenDataBuffer != null ? this._writtenDataBuffer.writableHighWaterMark : this[kHighWaterMark];
2593
+ }
2594
+ },
2595
+ writableCorked: {
2596
+ get() {
2597
+ return this[kCorked];
2598
+ }
2599
+ },
2600
+ writableEnded: {
2601
+ get() {
2602
+ return this.finished;
2603
+ }
2604
+ },
2605
+ writableNeedDrain: {
2606
+ get() {
2607
+ return !this.destroyed && !this.finished && this[kNeedDrain];
2608
+ }
2609
+ }
2610
+ });
2611
+ var headerCharRegex2 = /[^\t\x20-\x7e\x80-\xff]/;
2612
+ function checkInvalidHeaderChar2(val) {
2613
+ return headerCharRegex2.test(val);
2614
+ }
2615
+ var STATUS_CODES = {
2616
+ 100: "Continue",
2617
+ // RFC 7231 6.2.1
2618
+ 101: "Switching Protocols",
2619
+ // RFC 7231 6.2.2
2620
+ 102: "Processing",
2621
+ // RFC 2518 10.1 (obsoleted by RFC 4918)
2622
+ 103: "Early Hints",
2623
+ // RFC 8297 2
2624
+ 200: "OK",
2625
+ // RFC 7231 6.3.1
2626
+ 201: "Created",
2627
+ // RFC 7231 6.3.2
2628
+ 202: "Accepted",
2629
+ // RFC 7231 6.3.3
2630
+ 203: "Non-Authoritative Information",
2631
+ // RFC 7231 6.3.4
2632
+ 204: "No Content",
2633
+ // RFC 7231 6.3.5
2634
+ 205: "Reset Content",
2635
+ // RFC 7231 6.3.6
2636
+ 206: "Partial Content",
2637
+ // RFC 7233 4.1
2638
+ 207: "Multi-Status",
2639
+ // RFC 4918 11.1
2640
+ 208: "Already Reported",
2641
+ // RFC 5842 7.1
2642
+ 226: "IM Used",
2643
+ // RFC 3229 10.4.1
2644
+ 300: "Multiple Choices",
2645
+ // RFC 7231 6.4.1
2646
+ 301: "Moved Permanently",
2647
+ // RFC 7231 6.4.2
2648
+ 302: "Found",
2649
+ // RFC 7231 6.4.3
2650
+ 303: "See Other",
2651
+ // RFC 7231 6.4.4
2652
+ 304: "Not Modified",
2653
+ // RFC 7232 4.1
2654
+ 305: "Use Proxy",
2655
+ // RFC 7231 6.4.5
2656
+ 307: "Temporary Redirect",
2657
+ // RFC 7231 6.4.7
2658
+ 308: "Permanent Redirect",
2659
+ // RFC 7238 3
2660
+ 400: "Bad Request",
2661
+ // RFC 7231 6.5.1
2662
+ 401: "Unauthorized",
2663
+ // RFC 7235 3.1
2664
+ 402: "Payment Required",
2665
+ // RFC 7231 6.5.2
2666
+ 403: "Forbidden",
2667
+ // RFC 7231 6.5.3
2668
+ 404: "Not Found",
2669
+ // RFC 7231 6.5.4
2670
+ 405: "Method Not Allowed",
2671
+ // RFC 7231 6.5.5
2672
+ 406: "Not Acceptable",
2673
+ // RFC 7231 6.5.6
2674
+ 407: "Proxy Authentication Required",
2675
+ // RFC 7235 3.2
2676
+ 408: "Request Timeout",
2677
+ // RFC 7231 6.5.7
2678
+ 409: "Conflict",
2679
+ // RFC 7231 6.5.8
2680
+ 410: "Gone",
2681
+ // RFC 7231 6.5.9
2682
+ 411: "Length Required",
2683
+ // RFC 7231 6.5.10
2684
+ 412: "Precondition Failed",
2685
+ // RFC 7232 4.2
2686
+ 413: "Payload Too Large",
2687
+ // RFC 7231 6.5.11
2688
+ 414: "URI Too Long",
2689
+ // RFC 7231 6.5.12
2690
+ 415: "Unsupported Media Type",
2691
+ // RFC 7231 6.5.13
2692
+ 416: "Range Not Satisfiable",
2693
+ // RFC 7233 4.4
2694
+ 417: "Expectation Failed",
2695
+ // RFC 7231 6.5.14
2696
+ 418: "I'm a Teapot",
2697
+ // RFC 7168 2.3.3
2698
+ 421: "Misdirected Request",
2699
+ // RFC 7540 9.1.2
2700
+ 422: "Unprocessable Entity",
2701
+ // RFC 4918 11.2
2702
+ 423: "Locked",
2703
+ // RFC 4918 11.3
2704
+ 424: "Failed Dependency",
2705
+ // RFC 4918 11.4
2706
+ 425: "Too Early",
2707
+ // RFC 8470 5.2
2708
+ 426: "Upgrade Required",
2709
+ // RFC 2817 and RFC 7231 6.5.15
2710
+ 428: "Precondition Required",
2711
+ // RFC 6585 3
2712
+ 429: "Too Many Requests",
2713
+ // RFC 6585 4
2714
+ 431: "Request Header Fields Too Large",
2715
+ // RFC 6585 5
2716
+ 451: "Unavailable For Legal Reasons",
2717
+ // RFC 7725 3
2718
+ 500: "Internal Server Error",
2719
+ // RFC 7231 6.6.1
2720
+ 501: "Not Implemented",
2721
+ // RFC 7231 6.6.2
2722
+ 502: "Bad Gateway",
2723
+ // RFC 7231 6.6.3
2724
+ 503: "Service Unavailable",
2725
+ // RFC 7231 6.6.4
2726
+ 504: "Gateway Timeout",
2727
+ // RFC 7231 6.6.5
2728
+ 505: "HTTP Version Not Supported",
2729
+ // RFC 7231 6.6.6
2730
+ 506: "Variant Also Negotiates",
2731
+ // RFC 2295 8.1
2732
+ 507: "Insufficient Storage",
2733
+ // RFC 4918 11.5
2734
+ 508: "Loop Detected",
2735
+ // RFC 5842 7.2
2736
+ 509: "Bandwidth Limit Exceeded",
2737
+ 510: "Not Extended",
2738
+ // RFC 2774 7
2739
+ 511: "Network Authentication Required"
2740
+ // RFC 6585 6
2741
+ };
2742
+ var FetchServerResponse = class _FetchServerResponse extends FetchOutgoingMessage {
2743
+ static encoder = new TextEncoder();
2744
+ statusCode = 200;
2745
+ statusMessage;
2746
+ _sent100;
2747
+ _expect_continue;
2748
+ [kOutHeaders] = null;
2749
+ constructor(req, options) {
2750
+ super(req, options);
2751
+ if (req.method === "HEAD") {
2752
+ this._hasBody = false;
2753
+ }
2754
+ this.sendDate = true;
2755
+ this._sent100 = false;
2756
+ this._expect_continue = false;
2757
+ if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
2758
+ this.useChunkedEncodingByDefault = chunkExpression.exec(String(req.headers.te)) !== null;
2759
+ this.shouldKeepAlive = false;
2760
+ }
2761
+ this.fetchResponse = new Promise((resolve) => {
2762
+ let finished = false;
2763
+ this.on("finish", () => {
2764
+ finished = true;
2765
+ });
2766
+ const initialDataChunks = [];
2767
+ const initialDataWrittenHandler = (e2) => {
2768
+ if (finished) {
2769
+ return;
2770
+ }
2771
+ initialDataChunks[e2.index] = this.dataFromDataWrittenEvent(e2);
2772
+ };
2773
+ this.on("_dataWritten", initialDataWrittenHandler);
2774
+ this.on("_headersSent", (e2) => {
2775
+ this.off("_dataWritten", initialDataWrittenHandler);
2776
+ const { statusCode, statusMessage, headers } = e2;
2777
+ resolve(this._toFetchResponse(statusCode, statusMessage, headers, initialDataChunks, finished));
2778
+ });
2779
+ });
2780
+ }
2781
+ dataFromDataWrittenEvent(e2) {
2782
+ const { index, entry } = e2;
2783
+ let { data, encoding } = entry;
2784
+ if (index === 0) {
2785
+ if (typeof data !== "string") {
2786
+ console.error("First chunk should be string, not sure what happened.");
2787
+ throw new ERR_INVALID_ARG_TYPE("packet.data", ["string", "Buffer", "Uint8Array"], data);
2788
+ }
2789
+ data = data.slice(this.writtenHeaderBytes);
2790
+ }
2791
+ if (typeof data === "string") {
2792
+ if (encoding === void 0 || encoding === "utf8" || encoding === "utf-8") {
2793
+ data = _FetchServerResponse.encoder.encode(data);
2794
+ } else {
2795
+ data = buffer.Buffer.from(data, encoding ?? void 0);
2796
+ }
2797
+ }
2798
+ return data ?? buffer.Buffer.from([]);
2799
+ }
2800
+ _finish() {
2801
+ super._finish();
2802
+ }
2803
+ assignSocket(socket) {
2804
+ throw new ERR_METHOD_NOT_IMPLEMENTED("assignSocket");
2805
+ }
2806
+ detachSocket(socket) {
2807
+ throw new ERR_METHOD_NOT_IMPLEMENTED("detachSocket");
2808
+ }
2809
+ writeContinue(callback) {
2810
+ this._writeRaw("HTTP/1.1 100 Continue\r\n\r\n", "ascii", callback);
2811
+ this._sent100 = true;
2812
+ }
2813
+ writeProcessing(callback) {
2814
+ this._writeRaw("HTTP/1.1 102 Processing\r\n\r\n", "ascii", callback);
2815
+ }
2816
+ writeEarlyHints(hints, callback) {
2817
+ let head = "HTTP/1.1 103 Early Hints\r\n";
2818
+ if (hints.link === null || hints.link === void 0) {
2819
+ return;
2820
+ }
2821
+ const link = validateLinkHeaderValue(hints.link);
2822
+ if (link.length === 0) {
2823
+ return;
2824
+ }
2825
+ head += "Link: " + link + "\r\n";
2826
+ for (const key of Object.keys(hints)) {
2827
+ if (key !== "link") {
2828
+ head += key + ": " + hints[key] + "\r\n";
2829
+ }
2830
+ }
2831
+ head += "\r\n";
2832
+ this._writeRaw(head, "ascii", callback);
2833
+ }
2834
+ _implicitHeader() {
2835
+ this.writeHead(this.statusCode);
2836
+ }
2837
+ writeHead(statusCode, reason, obj) {
2838
+ if (this._header) {
2839
+ throw new ERR_HTTP_HEADERS_SENT("write");
2840
+ }
2841
+ const originalStatusCode = statusCode;
2842
+ statusCode |= 0;
2843
+ if (statusCode < 100 || statusCode > 999) {
2844
+ throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
2845
+ }
2846
+ if (typeof reason === "string") {
2847
+ this.statusMessage = reason;
2848
+ } else {
2849
+ this.statusMessage ||= STATUS_CODES[statusCode] || "unknown";
2850
+ obj ??= reason;
2851
+ }
2852
+ this.statusCode = statusCode;
2853
+ let headers;
2854
+ if (this[kOutHeaders]) {
2855
+ let k;
2856
+ if (Array.isArray(obj)) {
2857
+ if (obj.length % 2 !== 0) {
2858
+ throw new ERR_INVALID_ARG_VALUE("headers", obj);
2859
+ }
2860
+ for (let n2 = 0; n2 < obj.length; n2 += 2) {
2861
+ k = obj[n2 + 0];
2862
+ this.removeHeader(String(k));
2863
+ }
2864
+ for (let n2 = 0; n2 < obj.length; n2 += 2) {
2865
+ k = obj[n2];
2866
+ if (k) {
2867
+ this.appendHeader(String(k), obj[n2 + 1]);
2868
+ }
2869
+ }
2870
+ } else if (obj) {
2871
+ const keys = Object.keys(obj);
2872
+ for (let i2 = 0; i2 < keys.length; i2++) {
2873
+ k = keys[i2];
2874
+ if (k) {
2875
+ this.setHeader(k, obj[k]);
2876
+ }
2877
+ }
2878
+ }
2879
+ headers = this[kOutHeaders];
2880
+ } else {
2881
+ headers = obj;
2882
+ }
2883
+ if (checkInvalidHeaderChar2(this.statusMessage)) {
2884
+ throw new ERR_INVALID_CHAR("statusMessage");
2885
+ }
2886
+ const statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}\r
2887
+ `;
2888
+ if (statusCode === 204 || statusCode === 304 || statusCode >= 100 && statusCode <= 199) {
2889
+ this._hasBody = false;
2890
+ }
2891
+ if (this._expect_continue && !this._sent100) {
2892
+ this.shouldKeepAlive = false;
2893
+ }
2894
+ const convertedHeaders = headers && !Array.isArray(headers) ? headers : headers;
2895
+ this._storeHeader(statusLine, convertedHeaders ?? null);
2896
+ return this;
2897
+ }
2898
+ // Docs-only deprecated: DEP0063
2899
+ writeHeader = this.writeHead;
2900
+ fetchResponse;
2901
+ _toFetchResponse(status, statusText, sentHeaders, initialDataChunks, finished) {
2902
+ const headers = new Headers();
2903
+ for (const [header, value] of sentHeaders) {
2904
+ headers.append(header, value);
2905
+ }
2906
+ const _this = this;
2907
+ let body = this._hasBody ? new ReadableStream({
2908
+ start(controller) {
2909
+ for (const dataChunk of initialDataChunks) {
2910
+ controller.enqueue(dataChunk);
2911
+ }
2912
+ if (finished) {
2913
+ controller.close();
2914
+ } else {
2915
+ _this.on("finish", () => {
2916
+ finished = true;
2917
+ controller.close();
2918
+ });
2919
+ _this.on("_dataWritten", (e2) => {
2920
+ if (finished) {
2921
+ return;
2922
+ }
2923
+ const data = _this.dataFromDataWrittenEvent(e2);
2924
+ controller.enqueue(data);
2925
+ });
2926
+ }
2927
+ }
2928
+ }) : null;
2929
+ if (body != null && typeof FixedLengthStream !== "undefined") {
2930
+ const contentLength = parseInt(headers.get("content-length") ?? "", 10);
2931
+ if (contentLength >= 0) {
2932
+ body = body.pipeThrough(new FixedLengthStream(contentLength));
2933
+ }
2934
+ }
2935
+ return new Response(body, {
2936
+ status,
2937
+ statusText,
2938
+ headers
2939
+ });
2940
+ }
2941
+ };
2942
+ function toReqRes(req, options) {
2943
+ const { createIncomingMessage = () => new FetchIncomingMessage(), createServerResponse = (incoming2) => new FetchServerResponse(incoming2), ctx } = {};
2944
+ const incoming = createIncomingMessage(ctx);
2945
+ const serverResponse = createServerResponse(incoming, ctx);
2946
+ const reqUrl = new URL(req.url);
2947
+ const versionMajor = 1;
2948
+ const versionMinor = 1;
2949
+ incoming.httpVersionMajor = versionMajor;
2950
+ incoming.httpVersionMinor = versionMinor;
2951
+ incoming.httpVersion = `${versionMajor}.${versionMinor}`;
2952
+ incoming.url = reqUrl.pathname + reqUrl.search;
2953
+ incoming.upgrade = false;
2954
+ const headers = [];
2955
+ for (const [headerName, headerValue] of req.headers) {
2956
+ headers.push(headerName);
2957
+ headers.push(headerValue);
2958
+ }
2959
+ incoming._addHeaderLines(headers, headers.length);
2960
+ incoming.method = req.method;
2961
+ incoming._stream = req.body;
2962
+ return {
2963
+ req: incoming,
2964
+ res: serverResponse
2965
+ };
2966
+ }
2967
+ function toFetchResponse(res) {
2968
+ if (!(res instanceof FetchServerResponse)) {
2969
+ throw new Error("toFetchResponse must be called on a ServerResponse generated by toReqRes");
2970
+ }
2971
+ return res.fetchResponse;
2972
+ }
2973
+
2974
+ // src/server/handlers/mcp.ts
2975
+ var getMastra = (c2) => c2.get("mastra");
2976
+ var getMcpServerMessageHandler = async (c2) => {
2977
+ const mastra = getMastra(c2);
2978
+ const serverId = c2.req.param("serverId");
2979
+ const { req, res } = toReqRes(c2.req.raw);
2980
+ const server = mastra.getMCPServer(serverId);
2981
+ if (!server) {
2982
+ return c2.json({ error: `MCP server '${serverId}' not found` }, 404);
2983
+ }
2984
+ try {
2985
+ await server.startHTTP({
2986
+ url: new URL(c2.req.url),
2987
+ httpPath: `/api/servers/${serverId}/mcp`,
2988
+ req,
2989
+ res,
2990
+ options: {
2991
+ sessionIdGenerator: void 0
2992
+ }
2993
+ });
2994
+ const toFetchRes = await toFetchResponse(res);
2995
+ return toFetchRes;
2996
+ } catch (error) {
2997
+ return handleError(error, "Error sending MCP message");
2998
+ }
2999
+ };
3000
+ var handleMcpServerSseRoutes = async (c2) => {
3001
+ const mastra = getMastra(c2);
3002
+ const serverId = c2.req.param("serverId");
3003
+ const server = mastra.getMCPServer(serverId);
3004
+ if (!server) {
3005
+ return c2.json({ error: `MCP server '${serverId}' not found` }, 404);
3006
+ }
3007
+ const { req, res } = toReqRes(c2.req.raw);
3008
+ const requestUrl = new URL(c2.req.url);
3009
+ const sseConnectionPath = `/api/servers/${serverId}/sse`;
3010
+ const sseMessagePath = `/api/servers/${serverId}/messages`;
3011
+ try {
3012
+ await server.startSSE({
3013
+ url: requestUrl,
3014
+ ssePath: sseConnectionPath,
3015
+ messagePath: sseMessagePath,
3016
+ req,
3017
+ res
3018
+ });
3019
+ if (res.writableEnded || res.headersSent) {
3020
+ return toFetchResponse(res);
3021
+ }
3022
+ c2.get("logger")?.warn(
3023
+ { serverId, path: requestUrl.pathname },
3024
+ "MCP SSE handler: MCPServer.startSSE did not seem to handle the response."
3025
+ );
3026
+ return c2.text("Internal Server Error: MCP SSE request not fully processed by server component", 500);
3027
+ } catch (error) {
3028
+ c2.get("logger")?.error({ err: error, serverId, path: requestUrl.pathname }, "Error in MCP SSE route handler");
3029
+ if (!res.headersSent && !res.writableEnded) {
3030
+ return handleError(error, "Error handling MCP SSE request");
3031
+ }
3032
+ }
3033
+ };
1114
3034
  async function getMemoryStatusHandler(c2) {
1115
3035
  try {
1116
3036
  const mastra = c2.get("mastra");
@@ -2724,121 +4644,123 @@ async function createHonoServer(mastra, options = {}) {
2724
4644
  }),
2725
4645
  streamGenerateHandler
2726
4646
  );
2727
- app.post(
2728
- "/api/agents/:agentId/instructions",
2729
- bodyLimit.bodyLimit(bodyLimitOptions),
2730
- h({
2731
- description: "Update an agent's instructions",
2732
- tags: ["agents"],
2733
- parameters: [
2734
- {
2735
- name: "agentId",
2736
- in: "path",
2737
- required: true,
2738
- schema: { type: "string" }
2739
- }
2740
- ],
2741
- requestBody: {
2742
- required: true,
2743
- content: {
2744
- "application/json": {
2745
- schema: {
2746
- type: "object",
2747
- properties: {
2748
- instructions: {
2749
- type: "string",
2750
- description: "New instructions for the agent"
2751
- }
2752
- },
2753
- required: ["instructions"]
2754
- }
4647
+ if (options.isDev) {
4648
+ app.post(
4649
+ "/api/agents/:agentId/instructions",
4650
+ bodyLimit.bodyLimit(bodyLimitOptions),
4651
+ h({
4652
+ description: "Update an agent's instructions",
4653
+ tags: ["agents"],
4654
+ parameters: [
4655
+ {
4656
+ name: "agentId",
4657
+ in: "path",
4658
+ required: true,
4659
+ schema: { type: "string" }
2755
4660
  }
2756
- }
2757
- },
2758
- responses: {
2759
- 200: {
2760
- description: "Instructions updated successfully"
2761
- },
2762
- 403: {
2763
- description: "Not allowed in non-playground environment"
2764
- },
2765
- 404: {
2766
- description: "Agent not found"
2767
- }
2768
- }
2769
- }),
2770
- setAgentInstructionsHandler
2771
- );
2772
- app.post(
2773
- "/api/agents/:agentId/instructions/enhance",
2774
- bodyLimit.bodyLimit(bodyLimitOptions),
2775
- h({
2776
- description: "Generate an improved system prompt from instructions",
2777
- tags: ["agents"],
2778
- parameters: [
2779
- {
2780
- name: "agentId",
2781
- in: "path",
4661
+ ],
4662
+ requestBody: {
2782
4663
  required: true,
2783
- schema: { type: "string" },
2784
- description: "ID of the agent whose model will be used for prompt generation"
2785
- }
2786
- ],
2787
- requestBody: {
2788
- required: true,
2789
- content: {
2790
- "application/json": {
2791
- schema: {
2792
- type: "object",
2793
- properties: {
2794
- instructions: {
2795
- type: "string",
2796
- description: "Instructions to generate a system prompt from"
4664
+ content: {
4665
+ "application/json": {
4666
+ schema: {
4667
+ type: "object",
4668
+ properties: {
4669
+ instructions: {
4670
+ type: "string",
4671
+ description: "New instructions for the agent"
4672
+ }
2797
4673
  },
2798
- comment: {
2799
- type: "string",
2800
- description: "Optional comment for the enhanced prompt"
2801
- }
2802
- },
2803
- required: ["instructions"]
4674
+ required: ["instructions"]
4675
+ }
2804
4676
  }
2805
4677
  }
4678
+ },
4679
+ responses: {
4680
+ 200: {
4681
+ description: "Instructions updated successfully"
4682
+ },
4683
+ 403: {
4684
+ description: "Not allowed in non-playground environment"
4685
+ },
4686
+ 404: {
4687
+ description: "Agent not found"
4688
+ }
2806
4689
  }
2807
- },
2808
- responses: {
2809
- 200: {
2810
- description: "Generated system prompt and analysis",
4690
+ }),
4691
+ setAgentInstructionsHandler
4692
+ );
4693
+ app.post(
4694
+ "/api/agents/:agentId/instructions/enhance",
4695
+ bodyLimit.bodyLimit(bodyLimitOptions),
4696
+ h({
4697
+ description: "Generate an improved system prompt from instructions",
4698
+ tags: ["agents"],
4699
+ parameters: [
4700
+ {
4701
+ name: "agentId",
4702
+ in: "path",
4703
+ required: true,
4704
+ schema: { type: "string" },
4705
+ description: "ID of the agent whose model will be used for prompt generation"
4706
+ }
4707
+ ],
4708
+ requestBody: {
4709
+ required: true,
2811
4710
  content: {
2812
4711
  "application/json": {
2813
4712
  schema: {
2814
4713
  type: "object",
2815
4714
  properties: {
2816
- explanation: {
4715
+ instructions: {
2817
4716
  type: "string",
2818
- description: "Detailed analysis of the instructions"
4717
+ description: "Instructions to generate a system prompt from"
2819
4718
  },
2820
- new_prompt: {
4719
+ comment: {
2821
4720
  type: "string",
2822
- description: "The enhanced system prompt"
4721
+ description: "Optional comment for the enhanced prompt"
2823
4722
  }
2824
- }
4723
+ },
4724
+ required: ["instructions"]
2825
4725
  }
2826
4726
  }
2827
4727
  }
2828
4728
  },
2829
- 400: {
2830
- description: "Missing or invalid request parameters"
2831
- },
2832
- 404: {
2833
- description: "Agent not found"
2834
- },
2835
- 500: {
2836
- description: "Internal server error or model response parsing error"
4729
+ responses: {
4730
+ 200: {
4731
+ description: "Generated system prompt and analysis",
4732
+ content: {
4733
+ "application/json": {
4734
+ schema: {
4735
+ type: "object",
4736
+ properties: {
4737
+ explanation: {
4738
+ type: "string",
4739
+ description: "Detailed analysis of the instructions"
4740
+ },
4741
+ new_prompt: {
4742
+ type: "string",
4743
+ description: "The enhanced system prompt"
4744
+ }
4745
+ }
4746
+ }
4747
+ }
4748
+ }
4749
+ },
4750
+ 400: {
4751
+ description: "Missing or invalid request parameters"
4752
+ },
4753
+ 404: {
4754
+ description: "Agent not found"
4755
+ },
4756
+ 500: {
4757
+ description: "Internal server error or model response parsing error"
4758
+ }
2837
4759
  }
2838
- }
2839
- }),
2840
- generateSystemPromptHandler
2841
- );
4760
+ }),
4761
+ generateSystemPromptHandler
4762
+ );
4763
+ }
2842
4764
  app.get(
2843
4765
  "/api/agents/:agentId/speakers",
2844
4766
  async (c2, next) => {
@@ -3256,6 +5178,93 @@ async function createHonoServer(mastra, options = {}) {
3256
5178
  }),
3257
5179
  executeAgentToolHandler
3258
5180
  );
5181
+ app.post(
5182
+ "/api/servers/:serverId/mcp",
5183
+ bodyLimit.bodyLimit(bodyLimitOptions),
5184
+ h({
5185
+ description: "Send a message to an MCP server using Streamable HTTP",
5186
+ tags: ["mcp"],
5187
+ parameters: [
5188
+ {
5189
+ name: "serverId",
5190
+ in: "path",
5191
+ required: true,
5192
+ schema: { type: "string" }
5193
+ }
5194
+ ],
5195
+ requestBody: {
5196
+ content: { "application/json": { schema: { type: "object" } } }
5197
+ },
5198
+ responses: {
5199
+ 200: {
5200
+ description: "Streamable HTTP connection processed"
5201
+ },
5202
+ 404: {
5203
+ description: "MCP server not found"
5204
+ }
5205
+ }
5206
+ }),
5207
+ getMcpServerMessageHandler
5208
+ );
5209
+ const mcpSseBasePath = "/api/servers/:serverId/sse";
5210
+ const mcpSseMessagePath = "/api/servers/:serverId/messages";
5211
+ app.get(
5212
+ mcpSseBasePath,
5213
+ h({
5214
+ description: "Establish an MCP Server-Sent Events (SSE) connection with a server instance.",
5215
+ tags: ["mcp"],
5216
+ parameters: [
5217
+ {
5218
+ name: "serverId",
5219
+ in: "path",
5220
+ required: true,
5221
+ schema: { type: "string" },
5222
+ description: "The ID of the MCP server instance."
5223
+ }
5224
+ ],
5225
+ responses: {
5226
+ 200: {
5227
+ description: "SSE connection established. The client will receive events over this connection. (Content-Type: text/event-stream)"
5228
+ },
5229
+ 404: { description: "MCP server instance not found." },
5230
+ 500: { description: "Internal server error establishing SSE connection." }
5231
+ }
5232
+ }),
5233
+ handleMcpServerSseRoutes
5234
+ );
5235
+ app.post(
5236
+ mcpSseMessagePath,
5237
+ bodyLimit.bodyLimit(bodyLimitOptions),
5238
+ // Apply body limit for messages
5239
+ h({
5240
+ description: "Send a message to an MCP server over an established SSE connection.",
5241
+ tags: ["mcp"],
5242
+ parameters: [
5243
+ {
5244
+ name: "serverId",
5245
+ in: "path",
5246
+ required: true,
5247
+ schema: { type: "string" },
5248
+ description: "The ID of the MCP server instance."
5249
+ }
5250
+ ],
5251
+ requestBody: {
5252
+ description: "JSON-RPC message to send to the MCP server.",
5253
+ required: true,
5254
+ content: { "application/json": { schema: { type: "object" } } }
5255
+ // MCP messages are typically JSON
5256
+ },
5257
+ responses: {
5258
+ 200: {
5259
+ 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."
5260
+ },
5261
+ 400: { description: "Bad request (e.g., invalid JSON payload or missing body)." },
5262
+ 404: { description: "MCP server instance not found or SSE connection path incorrect." },
5263
+ 503: { description: "SSE connection not established with this server, or server unable to process message." }
5264
+ }
5265
+ }),
5266
+ handleMcpServerSseRoutes
5267
+ );
3259
5268
  app.get(
3260
5269
  "/api/memory/status",
3261
5270
  h({