sunpeak 0.20.64 → 0.20.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/bin/commands/dev.mjs +88 -46
  2. package/bin/lib/inspect/inspect-config.mjs +6 -6
  3. package/bin/lib/live/live-config.mjs +8 -6
  4. package/bin/lib/test/test-config.mjs +7 -10
  5. package/dist/chatgpt/index.cjs +1 -1
  6. package/dist/chatgpt/index.js +1 -1
  7. package/dist/claude/index.cjs +1 -1
  8. package/dist/claude/index.js +1 -1
  9. package/dist/embed.css +2 -2
  10. package/dist/host/chatgpt/index.cjs +1 -1
  11. package/dist/host/chatgpt/index.js +1 -1
  12. package/dist/index.cjs +22 -12
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.js +17 -12
  16. package/dist/index.js.map +1 -1
  17. package/dist/inspector/index.cjs +1 -1
  18. package/dist/inspector/index.js +1 -1
  19. package/dist/{inspector-Cl5w_7yQ.cjs → inspector-BSYXIDUe.cjs} +34 -17
  20. package/dist/{inspector-Cl5w_7yQ.cjs.map → inspector-BSYXIDUe.cjs.map} +1 -1
  21. package/dist/{inspector-DPJeSQAd.js → inspector-C5YJHT_c.js} +32 -16
  22. package/dist/{inspector-DPJeSQAd.js.map → inspector-C5YJHT_c.js.map} +1 -1
  23. package/dist/mcp/index.cjs +517 -104
  24. package/dist/mcp/index.cjs.map +1 -1
  25. package/dist/mcp/index.d.ts +1 -1
  26. package/dist/mcp/index.js +505 -92
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/style.css +7 -6
  29. package/dist/{use-app-D7-OtXBl.js → use-app-D27K0Cjf.js} +82 -32
  30. package/dist/{use-app-D7-OtXBl.js.map → use-app-D27K0Cjf.js.map} +1 -1
  31. package/dist/{use-app-BcSuulay.cjs → use-app-LPg2jlv8.cjs} +107 -32
  32. package/dist/{use-app-BcSuulay.cjs.map → use-app-LPg2jlv8.cjs.map} +1 -1
  33. package/package.json +21 -21
  34. package/template/dist/albums/albums.html +3 -3
  35. package/template/dist/albums/albums.json +1 -1
  36. package/template/dist/carousel/carousel.html +3 -3
  37. package/template/dist/carousel/carousel.json +1 -1
  38. package/template/dist/map/map.html +887 -811
  39. package/template/dist/map/map.json +1 -1
  40. package/template/dist/review/review.html +2 -2
  41. package/template/dist/review/review.json +1 -1
  42. package/template/node_modules/.bin/vite +2 -2
  43. package/template/node_modules/.bin/vitest +2 -2
  44. package/template/node_modules/.vite/deps/_metadata.json +4 -4
  45. package/template/node_modules/.vite-mcp/deps/@modelcontextprotocol_ext-apps.js +83 -31
  46. package/template/node_modules/.vite-mcp/deps/@modelcontextprotocol_ext-apps.js.map +1 -1
  47. package/template/node_modules/.vite-mcp/deps/@modelcontextprotocol_ext-apps_app-bridge.js +83 -31
  48. package/template/node_modules/.vite-mcp/deps/@modelcontextprotocol_ext-apps_app-bridge.js.map +1 -1
  49. package/template/node_modules/.vite-mcp/deps/@modelcontextprotocol_ext-apps_react.js +83 -31
  50. package/template/node_modules/.vite-mcp/deps/@modelcontextprotocol_ext-apps_react.js.map +1 -1
  51. package/template/node_modules/.vite-mcp/deps/@testing-library_react.js +4 -4
  52. package/template/node_modules/.vite-mcp/deps/@testing-library_react.js.map +1 -1
  53. package/template/node_modules/.vite-mcp/deps/_metadata.json +36 -36
  54. package/template/node_modules/.vite-mcp/deps/{client-ClsaORxz.js → client-96teDLij.js} +6 -6
  55. package/template/node_modules/.vite-mcp/deps/{client-ClsaORxz.js.map → client-96teDLij.js.map} +1 -1
  56. package/template/node_modules/.vite-mcp/deps/{dist-CO4R4Zw4.js → dist-Bd8a6mlN.js} +17 -5
  57. package/template/node_modules/.vite-mcp/deps/{dist-CO4R4Zw4.js.map → dist-Bd8a6mlN.js.map} +1 -1
  58. package/template/node_modules/.vite-mcp/deps/embla-carousel-react.js +1 -1
  59. package/template/node_modules/.vite-mcp/deps/embla-carousel-react.js.map +1 -1
  60. package/template/node_modules/.vite-mcp/deps/mapbox-gl.js +15062 -13925
  61. package/template/node_modules/.vite-mcp/deps/mapbox-gl.js.map +1 -1
  62. package/template/node_modules/.vite-mcp/deps/react-dom.js +3 -3
  63. package/template/node_modules/.vite-mcp/deps/react-dom.js.map +1 -1
  64. package/template/node_modules/.vite-mcp/deps/react-dom_client.js +1 -1
  65. package/template/node_modules/.vite-mcp/deps/react.js +3 -3
  66. package/template/node_modules/.vite-mcp/deps/react.js.map +1 -1
  67. package/template/node_modules/.vite-mcp/deps/react_jsx-dev-runtime.js +2 -2
  68. package/template/node_modules/.vite-mcp/deps/react_jsx-dev-runtime.js.map +1 -1
  69. package/template/node_modules/.vite-mcp/deps/react_jsx-runtime.js +2 -2
  70. package/template/node_modules/.vite-mcp/deps/react_jsx-runtime.js.map +1 -1
  71. package/template/node_modules/.vite-mcp/deps/vitest.js +57 -36
  72. package/template/node_modules/.vite-mcp/deps/vitest.js.map +1 -1
  73. package/template/package.json +11 -11
  74. package/template/tests/e2e/visual.spec.ts-snapshots/albums-fullscreen-chatgpt-linux.png +0 -0
  75. package/template/tests/e2e/visual.spec.ts-snapshots/albums-fullscreen-claude-darwin.png +0 -0
package/dist/mcp/index.js CHANGED
@@ -5,10 +5,8 @@ import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { gzipSync } from "node:zlib";
7
7
  import { ZodOptional, z } from "zod";
8
- import "http";
9
- import { Http2ServerRequest, constants } from "http2";
10
- import { Readable } from "stream";
11
- import crypto$1 from "crypto";
8
+ import { Http2ServerRequest, constants } from "node:http2";
9
+ import { Readable } from "node:stream";
12
10
  import { createHash, randomUUID } from "node:crypto";
13
11
  //#region src/mcp/favicon.ts
14
12
  var FAVICON_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAOdEVYdFNvZnR3YXJlAEZpZ21hnrGWYwAAA6BJREFUeAHtm09ME0EUxr+lqIDVlMQEI8aAaPRUmwgmeLEcTLxR7ibASY+QqNfSqxfiDU+UhDvlZuKBcpEELpUTBwWCciDRsMGC8Q/W9y0U+29bu922dHZ/yXRndynp++btzLzZeRryCPqA5AigDQKpgBx9aGhSutiQkMoMsBLNvatln94LAX+mG99oUzalRDKF8Py71xuWjykxvgU1oKvjB3zew5Oi7zejBrBhpZGvymF7kReOPaBvRD6mUQVoaNCfxAP/HgLXDwxjea0QFCHxsVVKG96vtyHBIvXqoA0By7G0ABv8rbCJoP+bYfDIw6+mxv4vmzvnEHvnw6vYZamfhY1I3/CrW7Oz9Wl4+PG2cawG8dULmHl7CVEp9tA0TgEWpBZEBVTb8FzoFeOvrxmeUSFxCrCLo86hbHznDzH9bAOh/l3UA3pCZLazkkdDpwApWICtPRf+ICL8Rj0xvGFKvGHJmjdYEoA9eahfx2mCj4O+7yn7e5Y9QBWa4HBcAeBwHC9A0QiE47zPW99hrlI4TBajqACTT7dkPv8FjQznB0ORm6b3TR+B0H294Y0nnK8Um6KbCjD5ZAuqwDjFjIICsOUrDWNPE/QAMy8oKMCwxPGqYeYFeQJ0dfwUtfagGmZekBcL0PUpgopwuS137dENhuBwXAHgcNxgKPOkVqu69YbL62myRoHUmxU4Ae1R30n95BFQaepbikxb3U4QDscVIF0ptXSkEpm2Zg2DAy9uw2m4wRAcjisAHI4bDOVe4NugQM8BVITDX+5ukjwBaPzCyzWoSPewP+9a3iPAUDG+ehGqQbsKTfYK9gGR2StQjRmTrXUFBVDNC9jy0XIEICp5AXeRmWEqAL0gttSORoctX2wLXclYoNFXivSkp+hOdDcYgsNxBYDDcYMhWEClzdKWBDgaWjzGRqp6D5Mc4oYiNywZT+RbnWNyLDtTbO1TC+ZlgtHurV/4zInawPNbWPvcCovotqTMcE9hLb2BcQqn6pkvOa3+KxGgVzxAm4QNcHsdd5hVa5OVjYanGRUBAjJRPsO0OduyRekJY6EdDIpn2JE2x1D2KEK1zXBB2wSWu4/zBu+GZEScQxVg/8CESZY7Pd+Nc7M8IxqrJ5uRWG/ForR2fNVbzTdWo0yhzcgd7p0QVcKoEbmeUdtXc1pEWn/CqGXfYBIlRUh1QU2YST7KlNn0Ba3w3xnZpMNSArCxb6gTnLElpFHnAW9UutKsGdxfpFM6myaou6kAAAAASUVORK5CYII=";
@@ -2746,7 +2744,7 @@ var init_data = __esmMin((() => {
2746
2744
  };
2747
2745
  }));
2748
2746
  //#endregion
2749
- //#region ../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/utils.js
2747
+ //#region ../../node_modules/.pnpm/fast-uri@3.1.4/node_modules/fast-uri/lib/utils.js
2750
2748
  var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2751
2749
  /** @type {(value: string) => boolean} */
2752
2750
  var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
@@ -3118,7 +3116,7 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3118
3116
  };
3119
3117
  }));
3120
3118
  //#endregion
3121
- //#region ../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/lib/schemes.js
3119
+ //#region ../../node_modules/.pnpm/fast-uri@3.1.4/node_modules/fast-uri/lib/schemes.js
3122
3120
  var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3123
3121
  var { isUUID } = require_utils();
3124
3122
  var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
@@ -3301,7 +3299,7 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3301
3299
  };
3302
3300
  }));
3303
3301
  //#endregion
3304
- //#region ../../node_modules/.pnpm/fast-uri@3.1.2/node_modules/fast-uri/index.js
3302
+ //#region ../../node_modules/.pnpm/fast-uri@3.1.4/node_modules/fast-uri/index.js
3305
3303
  var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3306
3304
  var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
3307
3305
  var { SCHEMES, getSchemeHandler } = require_schemes();
@@ -3440,6 +3438,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3440
3438
  return uriTokens.join("");
3441
3439
  }
3442
3440
  var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
3441
+ var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
3443
3442
  /**
3444
3443
  * @param {import('./types/index').URIComponent} parsed
3445
3444
  * @param {RegExpMatchArray} matches
@@ -3470,6 +3469,11 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3470
3469
  let isIP = false;
3471
3470
  if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri;
3472
3471
  else uri = "//" + uri;
3472
+ const authorityMatch = uri.match(AUTHORITY_PREFIX);
3473
+ if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
3474
+ parsed.error = "URI authority must not contain a literal backslash.";
3475
+ malformedAuthorityOrPort = true;
3476
+ }
3473
3477
  const matches = uri.match(URI_PARSE);
3474
3478
  if (matches) {
3475
3479
  parsed.scheme = matches[1];
@@ -3498,7 +3502,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3498
3502
  const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
3499
3503
  if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
3500
3504
  if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try {
3501
- parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
3505
+ parsed.host = new URL("http://" + parsed.host).hostname;
3502
3506
  } catch (e) {
3503
3507
  parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
3504
3508
  }
@@ -7688,13 +7692,29 @@ var EMPTY_COMPLETION_RESULT = { completion: {
7688
7692
  hasMore: false
7689
7693
  } };
7690
7694
  //#endregion
7691
- //#region ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs
7695
+ //#region ../../node_modules/.pnpm/@hono+node-server@2.0.11_hono@4.12.27/node_modules/@hono/node-server/dist/index.mjs
7692
7696
  var RequestError = class extends Error {
7693
7697
  constructor(message, options) {
7694
7698
  super(message, options);
7695
7699
  this.name = "RequestError";
7696
7700
  }
7697
7701
  };
7702
+ var reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
7703
+ var reDotSegment = /\/\.\.?(?:[/?#]|$)/;
7704
+ var reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
7705
+ var buildUrl = (scheme, host, incomingUrl) => {
7706
+ const url = `${scheme}://${host}${incomingUrl}`;
7707
+ if (!reValidHost.test(host)) {
7708
+ const urlObj = new URL(url);
7709
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
7710
+ return urlObj.href;
7711
+ } else if (incomingUrl.length === 0) return url + "/";
7712
+ else {
7713
+ if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
7714
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
7715
+ return url;
7716
+ }
7717
+ };
7698
7718
  var toRequestError = (e) => {
7699
7719
  if (e instanceof RequestError) return e;
7700
7720
  return new RequestError(e.message, { cause: e });
@@ -7702,21 +7722,73 @@ var toRequestError = (e) => {
7702
7722
  var GlobalRequest = global.Request;
7703
7723
  var Request$1 = class extends GlobalRequest {
7704
7724
  constructor(input, options) {
7705
- if (typeof input === "object" && getRequestCache in input) input = input[getRequestCache]();
7706
- if (typeof options?.body?.getReader !== "undefined") options.duplex ??= "half";
7725
+ if (typeof input === "object" && getRequestCache in input) {
7726
+ const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
7727
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
7728
+ input = input[getRequestCache]();
7729
+ }
7730
+ if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
7707
7731
  super(input, options);
7708
7732
  }
7709
7733
  };
7710
7734
  var newHeadersFromIncoming = (incoming) => {
7711
7735
  const headerRecord = [];
7712
7736
  const rawHeaders = incoming.rawHeaders;
7713
- for (let i = 0; i < rawHeaders.length; i += 2) {
7714
- const { [i]: key, [i + 1]: value } = rawHeaders;
7715
- if (key.charCodeAt(0) !== 58) headerRecord.push([key, value]);
7737
+ for (let i = 0, len = rawHeaders.length; i < len; i += 2) {
7738
+ const key = rawHeaders[i];
7739
+ if (key.charCodeAt(0) !== 58) headerRecord.push([key, rawHeaders[i + 1]]);
7716
7740
  }
7717
7741
  return new Headers(headerRecord);
7718
7742
  };
7719
7743
  var wrapBodyStream = Symbol("wrapBodyStream");
7744
+ var byteExactEncodings = /* @__PURE__ */ new Set([
7745
+ "latin1",
7746
+ "binary",
7747
+ "hex",
7748
+ "base64",
7749
+ "base64url"
7750
+ ]);
7751
+ var isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
7752
+ var bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
7753
+ var bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
7754
+ var toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
7755
+ var isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
7756
+ var recordBodyBufferedBeforeDisconnect = (incoming) => {
7757
+ if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
7758
+ const incomingWithRecovery = incoming;
7759
+ incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
7760
+ };
7761
+ var readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
7762
+ if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
7763
+ const incomingWithRecovery = incoming;
7764
+ if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
7765
+ let result;
7766
+ const errored = incoming.errored;
7767
+ if (errored && errored.code !== "ECONNRESET") result = errored;
7768
+ else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
7769
+ else {
7770
+ const bodyChunks = chunks ?? [];
7771
+ const chunk = incoming.read();
7772
+ if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
7773
+ const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
7774
+ result = buffer;
7775
+ const contentLength = incoming.headers["content-length"];
7776
+ if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
7777
+ const expectedLength = Number(contentLength);
7778
+ if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
7779
+ }
7780
+ }
7781
+ incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
7782
+ return result;
7783
+ };
7784
+ var enqueueBufferedBody = (controller, buffered) => {
7785
+ if (buffered instanceof Error) {
7786
+ controller.error(buffered);
7787
+ return;
7788
+ }
7789
+ if (buffered.length > 0) controller.enqueue(buffered);
7790
+ controller.close();
7791
+ };
7720
7792
  var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
7721
7793
  const init = {
7722
7794
  method,
@@ -7739,6 +7811,13 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
7739
7811
  let reader;
7740
7812
  init.body = new ReadableStream({ async pull(controller) {
7741
7813
  try {
7814
+ if (!reader) {
7815
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
7816
+ if (buffered !== void 0) {
7817
+ enqueueBufferedBody(controller, buffered);
7818
+ return;
7819
+ }
7820
+ }
7742
7821
  reader ||= Readable.toWeb(incoming).getReader();
7743
7822
  const { done, value } = await reader.read();
7744
7823
  if (done) controller.close();
@@ -7747,18 +7826,192 @@ var newRequestFromIncoming = (method, url, headers, incoming, abortController) =
7747
7826
  controller.error(error);
7748
7827
  }
7749
7828
  } });
7750
- } else init.body = Readable.toWeb(incoming);
7829
+ } else {
7830
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
7831
+ if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
7832
+ enqueueBufferedBody(controller, buffered);
7833
+ } });
7834
+ else init.body = Readable.toWeb(incoming);
7835
+ }
7751
7836
  return new Request$1(url, init);
7752
7837
  };
7753
7838
  var getRequestCache = Symbol("getRequestCache");
7754
7839
  var requestCache = Symbol("requestCache");
7755
7840
  var incomingKey = Symbol("incomingKey");
7756
7841
  var urlKey = Symbol("urlKey");
7842
+ var methodKey = Symbol("methodKey");
7757
7843
  var headersKey = Symbol("headersKey");
7758
7844
  var abortControllerKey = Symbol("abortControllerKey");
7845
+ var getAbortController = Symbol("getAbortController");
7846
+ var abortRequest = Symbol("abortRequest");
7847
+ var bodyBufferKey = Symbol("bodyBuffer");
7848
+ var bodyReadPromiseKey = Symbol("bodyReadPromise");
7849
+ var bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
7850
+ var bodyLockReaderKey = Symbol("bodyLockReader");
7851
+ var abortReasonKey = Symbol("abortReason");
7852
+ var newBodyUnusableError = () => {
7853
+ return /* @__PURE__ */ new TypeError("Body is unusable");
7854
+ };
7855
+ var rejectBodyUnusable = () => {
7856
+ return Promise.reject(newBodyUnusableError());
7857
+ };
7858
+ var textDecoder = new TextDecoder();
7859
+ var consumeBodyDirectOnce = (request) => {
7860
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
7861
+ request[bodyConsumedDirectlyKey] = true;
7862
+ };
7863
+ var toArrayBuffer = (buf) => {
7864
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
7865
+ };
7866
+ var contentType = (request) => {
7867
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
7868
+ };
7869
+ var methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
7870
+ var normalizeIncomingMethod = (method) => {
7871
+ if (typeof method !== "string" || method.length === 0) return "GET";
7872
+ switch (method) {
7873
+ case "DELETE":
7874
+ case "GET":
7875
+ case "HEAD":
7876
+ case "OPTIONS":
7877
+ case "PATCH":
7878
+ case "POST":
7879
+ case "PUT":
7880
+ case "QUERY": return method;
7881
+ }
7882
+ const upper = method.toUpperCase();
7883
+ switch (upper) {
7884
+ case "DELETE":
7885
+ case "GET":
7886
+ case "HEAD":
7887
+ case "OPTIONS":
7888
+ case "POST":
7889
+ case "PUT": return upper;
7890
+ default: return method;
7891
+ }
7892
+ };
7893
+ var validateDirectReadMethod = (method) => {
7894
+ if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
7895
+ const normalized = method.toUpperCase();
7896
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
7897
+ };
7898
+ var readBodyWithFastPath = (request, method, fromBuffer) => {
7899
+ if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
7900
+ const methodName = request.method;
7901
+ if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
7902
+ const methodValidationError = validateDirectReadMethod(methodName);
7903
+ if (methodValidationError) return Promise.reject(methodValidationError);
7904
+ if (request[requestCache]) {
7905
+ if (methodName !== "TRACE") return request[requestCache][method]();
7906
+ }
7907
+ const alreadyUsedError = consumeBodyDirectOnce(request);
7908
+ if (alreadyUsedError) return alreadyUsedError;
7909
+ const raw = readRawBodyIfAvailable(request);
7910
+ if (raw) {
7911
+ const result = Promise.resolve(fromBuffer(raw, request));
7912
+ request[bodyBufferKey] = void 0;
7913
+ return result;
7914
+ }
7915
+ return readBodyDirect(request).then((buf) => {
7916
+ const result = fromBuffer(buf, request);
7917
+ request[bodyBufferKey] = void 0;
7918
+ return result;
7919
+ });
7920
+ };
7921
+ var readRawBodyIfAvailable = (request) => {
7922
+ const incoming = request[incomingKey];
7923
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
7924
+ };
7925
+ var normalizeAbortError = (request, incoming) => {
7926
+ if (incoming.errored) return incoming.errored;
7927
+ const reason = request[abortReasonKey];
7928
+ if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
7929
+ return /* @__PURE__ */ new Error("Client connection prematurely closed.");
7930
+ };
7931
+ var readBodyDirect = (request) => {
7932
+ if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
7933
+ if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
7934
+ const incoming = request[incomingKey];
7935
+ if (incoming.readableDidRead) return rejectBodyUnusable();
7936
+ const buffered = readBodyBufferedBeforeDisconnect(incoming);
7937
+ if (buffered !== void 0) {
7938
+ if (buffered instanceof Error) return Promise.reject(buffered);
7939
+ request[bodyBufferKey] = buffered;
7940
+ return Promise.resolve(buffered);
7941
+ }
7942
+ const promise = new Promise((resolve, reject) => {
7943
+ const chunks = [];
7944
+ let settled = false;
7945
+ const finish = (callback) => {
7946
+ if (settled) return;
7947
+ settled = true;
7948
+ cleanup();
7949
+ callback();
7950
+ };
7951
+ const recoverCompleteBodyAfterDisconnect = (error) => {
7952
+ const streamError = incoming.errored ?? error;
7953
+ if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
7954
+ finish(() => {
7955
+ const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
7956
+ if (recovered instanceof Error) reject(recovered);
7957
+ else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
7958
+ else {
7959
+ request[bodyBufferKey] = recovered;
7960
+ resolve(recovered);
7961
+ }
7962
+ });
7963
+ return true;
7964
+ };
7965
+ const onData = (chunk) => {
7966
+ chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
7967
+ };
7968
+ const onEnd = () => {
7969
+ finish(() => {
7970
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
7971
+ request[bodyBufferKey] = buffer;
7972
+ resolve(buffer);
7973
+ });
7974
+ };
7975
+ const onError = (error) => {
7976
+ if (recoverCompleteBodyAfterDisconnect(error)) return;
7977
+ finish(() => {
7978
+ reject(error);
7979
+ });
7980
+ };
7981
+ const onClose = () => {
7982
+ if (incoming.readableEnded) {
7983
+ onEnd();
7984
+ return;
7985
+ }
7986
+ if (recoverCompleteBodyAfterDisconnect()) return;
7987
+ finish(() => {
7988
+ reject(normalizeAbortError(request, incoming));
7989
+ });
7990
+ };
7991
+ const cleanup = () => {
7992
+ incoming.off("data", onData);
7993
+ incoming.off("end", onEnd);
7994
+ incoming.off("error", onError);
7995
+ incoming.off("close", onClose);
7996
+ request[bodyReadPromiseKey] = void 0;
7997
+ };
7998
+ incoming.on("data", onData);
7999
+ incoming.on("end", onEnd);
8000
+ incoming.on("error", onError);
8001
+ incoming.on("close", onClose);
8002
+ queueMicrotask(() => {
8003
+ if (settled) return;
8004
+ if (incoming.readableEnded) onEnd();
8005
+ else if (incoming.errored) onError(incoming.errored);
8006
+ else if (incoming.destroyed) onClose();
8007
+ });
8008
+ });
8009
+ request[bodyReadPromiseKey] = promise;
8010
+ return promise;
8011
+ };
7759
8012
  var requestPrototype = {
7760
8013
  get method() {
7761
- return this[incomingKey].method || "GET";
8014
+ return this[methodKey];
7762
8015
  },
7763
8016
  get url() {
7764
8017
  return this[urlKey];
@@ -7766,18 +8019,57 @@ var requestPrototype = {
7766
8019
  get headers() {
7767
8020
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
7768
8021
  },
7769
- [Symbol("getAbortController")]() {
7770
- this[getRequestCache]();
8022
+ [abortRequest](reason) {
8023
+ if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
8024
+ const abortController = this[abortControllerKey];
8025
+ if (abortController && !abortController.signal.aborted) abortController.abort(reason);
8026
+ },
8027
+ [getAbortController]() {
8028
+ this[abortControllerKey] ||= new AbortController();
8029
+ if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
7771
8030
  return this[abortControllerKey];
7772
8031
  },
7773
8032
  [getRequestCache]() {
7774
- this[abortControllerKey] ||= new AbortController();
7775
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
8033
+ const abortController = this[getAbortController]();
8034
+ if (this[requestCache]) return this[requestCache];
8035
+ const method = this.method;
8036
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
8037
+ this[bodyBufferKey] = void 0;
8038
+ const init = {
8039
+ method: method === "TRACE" ? "GET" : method,
8040
+ headers: this.headers,
8041
+ signal: abortController.signal
8042
+ };
8043
+ if (method !== "TRACE") {
8044
+ init.body = new ReadableStream({ start(c) {
8045
+ c.close();
8046
+ } });
8047
+ init.duplex = "half";
8048
+ }
8049
+ const req = new Request$1(this[urlKey], init);
8050
+ if (method === "TRACE") Object.defineProperty(req, "method", { get() {
8051
+ return "TRACE";
8052
+ } });
8053
+ return this[requestCache] = req;
8054
+ }
8055
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
8056
+ },
8057
+ get body() {
8058
+ if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
8059
+ const request = this[getRequestCache]();
8060
+ if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
8061
+ return request.body;
8062
+ },
8063
+ get bodyUsed() {
8064
+ if (this[bodyConsumedDirectlyKey]) return true;
8065
+ if (this[requestCache]) return this[requestCache].bodyUsed;
8066
+ return false;
7776
8067
  }
7777
8068
  };
8069
+ Object.defineProperty(requestPrototype, "signal", { get() {
8070
+ return this[getAbortController]().signal;
8071
+ } });
7778
8072
  [
7779
- "body",
7780
- "bodyUsed",
7781
8073
  "cache",
7782
8074
  "credentials",
7783
8075
  "destination",
@@ -7786,25 +8078,37 @@ var requestPrototype = {
7786
8078
  "redirect",
7787
8079
  "referrer",
7788
8080
  "referrerPolicy",
7789
- "signal",
7790
8081
  "keepalive"
7791
8082
  ].forEach((k) => {
7792
8083
  Object.defineProperty(requestPrototype, k, { get() {
7793
8084
  return this[getRequestCache]()[k];
7794
8085
  } });
7795
8086
  });
7796
- [
7797
- "arrayBuffer",
7798
- "blob",
7799
- "clone",
7800
- "formData",
7801
- "json",
7802
- "text"
7803
- ].forEach((k) => {
8087
+ ["clone", "formData"].forEach((k) => {
7804
8088
  Object.defineProperty(requestPrototype, k, { value: function() {
8089
+ if (this[bodyConsumedDirectlyKey]) {
8090
+ if (k === "clone") throw newBodyUnusableError();
8091
+ return rejectBodyUnusable();
8092
+ }
7805
8093
  return this[getRequestCache]()[k]();
7806
8094
  } });
7807
8095
  });
8096
+ Object.defineProperty(requestPrototype, "text", { value: function() {
8097
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
8098
+ } });
8099
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
8100
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
8101
+ } });
8102
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
8103
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
8104
+ const type = contentType(request);
8105
+ return new Response(buf, type ? { headers: { "content-type": type } } : void 0).blob();
8106
+ });
8107
+ } });
8108
+ Object.defineProperty(requestPrototype, "json", { value: function() {
8109
+ if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
8110
+ return this.text().then(JSON.parse);
8111
+ } });
7808
8112
  Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
7809
8113
  return `Request (lightweight) ${inspectFn({
7810
8114
  method: this.method,
@@ -7820,6 +8124,7 @@ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
7820
8124
  var newRequest = (incoming, defaultHostname) => {
7821
8125
  const req = Object.create(requestPrototype);
7822
8126
  req[incomingKey] = incoming;
8127
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
7823
8128
  const incomingUrl = incoming.url || "";
7824
8129
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
7825
8130
  if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
@@ -7837,26 +8142,36 @@ var newRequest = (incoming, defaultHostname) => {
7837
8142
  scheme = incoming.scheme;
7838
8143
  if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
7839
8144
  } else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
7840
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
7841
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) throw new RequestError("Invalid host header");
7842
- req[urlKey] = url.href;
8145
+ try {
8146
+ req[urlKey] = buildUrl(scheme, host, incomingUrl);
8147
+ } catch (e) {
8148
+ if (e instanceof RequestError) throw e;
8149
+ else throw new RequestError("Invalid URL", { cause: e });
8150
+ }
7843
8151
  return req;
7844
8152
  };
8153
+ var defaultContentType = "text/plain; charset=UTF-8";
7845
8154
  var responseCache = Symbol("responseCache");
7846
8155
  var getResponseCache = Symbol("getResponseCache");
7847
8156
  var cacheKey = Symbol("cache");
7848
8157
  var GlobalResponse = global.Response;
7849
- var Response2 = class _Response {
8158
+ var Response$1 = class Response$1 {
7850
8159
  #body;
7851
8160
  #init;
7852
8161
  [getResponseCache]() {
8162
+ const cache = this[cacheKey];
8163
+ const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
7853
8164
  delete this[cacheKey];
7854
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
8165
+ return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
8166
+ status: this.#init?.status,
8167
+ statusText: this.#init?.statusText,
8168
+ headers: liveHeaders
8169
+ } : this.#init);
7855
8170
  }
7856
8171
  constructor(body, init) {
7857
8172
  let headers;
7858
8173
  this.#body = body;
7859
- if (init instanceof _Response) {
8174
+ if (init instanceof Response$1) {
7860
8175
  const cachedGlobalResponse = init[responseCache];
7861
8176
  if (cachedGlobalResponse) {
7862
8177
  this.#init = cachedGlobalResponse;
@@ -7864,19 +8179,19 @@ var Response2 = class _Response {
7864
8179
  return;
7865
8180
  } else {
7866
8181
  this.#init = init.#init;
7867
- headers = new Headers(init.#init.headers);
8182
+ headers = new Headers(init.headers);
7868
8183
  }
7869
8184
  } else this.#init = init;
7870
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
8185
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
7871
8186
  init?.status || 200,
7872
- body,
8187
+ body ?? null,
7873
8188
  headers || init?.headers
7874
8189
  ];
7875
8190
  }
7876
8191
  get headers() {
7877
8192
  const cache = this[cacheKey];
7878
8193
  if (cache) {
7879
- if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
8194
+ if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
7880
8195
  return cache[2];
7881
8196
  }
7882
8197
  return this[getResponseCache]().headers;
@@ -7898,7 +8213,7 @@ var Response2 = class _Response {
7898
8213
  "type",
7899
8214
  "url"
7900
8215
  ].forEach((k) => {
7901
- Object.defineProperty(Response2.prototype, k, { get() {
8216
+ Object.defineProperty(Response$1.prototype, k, { get() {
7902
8217
  return this[getResponseCache]()[k];
7903
8218
  } });
7904
8219
  });
@@ -7910,11 +8225,11 @@ var Response2 = class _Response {
7910
8225
  "json",
7911
8226
  "text"
7912
8227
  ].forEach((k) => {
7913
- Object.defineProperty(Response2.prototype, k, { value: function() {
8228
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
7914
8229
  return this[getResponseCache]()[k]();
7915
8230
  } });
7916
8231
  });
7917
- Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
8232
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
7918
8233
  return `Response (lightweight) ${inspectFn({
7919
8234
  status: this.status,
7920
8235
  headers: this.headers,
@@ -7925,8 +8240,51 @@ Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custo
7925
8240
  depth: depth == null ? null : depth - 1
7926
8241
  })}`;
7927
8242
  } });
7928
- Object.setPrototypeOf(Response2, GlobalResponse);
7929
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
8243
+ Object.setPrototypeOf(Response$1, GlobalResponse);
8244
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
8245
+ var validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
8246
+ var parseRedirectUrl = (url) => {
8247
+ if (url instanceof URL) return url.href;
8248
+ if (validRedirectUrl.test(url)) return url;
8249
+ return new URL(url).href;
8250
+ };
8251
+ var validRedirectStatuses = /* @__PURE__ */ new Set([
8252
+ 301,
8253
+ 302,
8254
+ 303,
8255
+ 307,
8256
+ 308
8257
+ ]);
8258
+ Object.defineProperty(Response$1, "redirect", {
8259
+ value: function redirect(url, status = 302) {
8260
+ if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
8261
+ return new Response$1(null, {
8262
+ status,
8263
+ headers: { location: parseRedirectUrl(url) }
8264
+ });
8265
+ },
8266
+ writable: true,
8267
+ configurable: true
8268
+ });
8269
+ Object.defineProperty(Response$1, "json", {
8270
+ value: function json(data, init) {
8271
+ const body = JSON.stringify(data);
8272
+ if (body === void 0) throw new TypeError("The data is not JSON serializable");
8273
+ const initHeaders = init?.headers;
8274
+ let headers;
8275
+ if (initHeaders) {
8276
+ headers = new Headers(initHeaders);
8277
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
8278
+ } else headers = { "content-type": "application/json" };
8279
+ return new Response$1(body, {
8280
+ status: init?.status ?? 200,
8281
+ statusText: init?.statusText,
8282
+ headers
8283
+ });
8284
+ },
8285
+ writable: true,
8286
+ configurable: true
8287
+ });
7930
8288
  async function readWithoutBlocking(readPromise) {
7931
8289
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
7932
8290
  }
@@ -7962,18 +8320,18 @@ function writeFromReadableStream(stream, writable) {
7962
8320
  else if (writable.destroyed) return;
7963
8321
  return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
7964
8322
  }
7965
- var buildOutgoingHttpHeaders = (headers) => {
8323
+ var buildOutgoingHttpHeaders = (headers, defaultContentType) => {
7966
8324
  const res = {};
7967
8325
  if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
7968
- const cookies = [];
7969
- for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
7970
- else res[k] = v;
7971
- if (cookies.length > 0) res["set-cookie"] = cookies;
7972
- res["content-type"] ??= "text/plain; charset=UTF-8";
8326
+ if (headers.has("set-cookie")) {
8327
+ const cookies = [];
8328
+ for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
8329
+ else res[k] = v;
8330
+ if (cookies.length > 0) res["set-cookie"] = cookies;
8331
+ } else for (const [k, v] of headers) res[k] = v;
8332
+ if (defaultContentType) res["content-type"] ??= defaultContentType;
7973
8333
  return res;
7974
8334
  };
7975
- var X_ALREADY_SENT = "x-hono-already-sent";
7976
- if (typeof global.crypto === "undefined") global.crypto = crypto$1;
7977
8335
  var outgoingEnded = Symbol("outgoingEnded");
7978
8336
  var incomingDraining = Symbol("incomingDraining");
7979
8337
  var DRAIN_TIMEOUT_MS = 500;
@@ -8011,6 +8369,25 @@ var drainIncoming = (incoming) => {
8011
8369
  incoming.on("error", cleanup);
8012
8370
  incoming.resume();
8013
8371
  };
8372
+ var makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
8373
+ if (incoming.errored) {
8374
+ recordBodyBufferedBeforeDisconnect(incoming);
8375
+ req[abortRequest](incoming.errored.toString());
8376
+ } else if (!outgoing.writableFinished) {
8377
+ recordBodyBufferedBeforeDisconnect(incoming);
8378
+ req[abortRequest]("Client connection prematurely closed.");
8379
+ }
8380
+ if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
8381
+ if (!incoming.readableEnded) setTimeout(() => {
8382
+ drainIncoming(incoming);
8383
+ });
8384
+ });
8385
+ };
8386
+ var isImmediateCacheableResponse = (res) => {
8387
+ if (!(cacheKey in res)) return false;
8388
+ const body = res[cacheKey][1];
8389
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
8390
+ };
8014
8391
  var handleRequestError = () => new Response(null, { status: 400 });
8015
8392
  var handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
8016
8393
  var handleResponseError = (e, outgoing) => {
@@ -8028,15 +8405,44 @@ var flushHeaders = (outgoing) => {
8028
8405
  };
8029
8406
  var responseViaCache = async (res, outgoing) => {
8030
8407
  let [status, body, header] = res[cacheKey];
8408
+ if (!header) {
8409
+ if (body === null) {
8410
+ outgoing.writeHead(status);
8411
+ outgoing.end();
8412
+ } else if (typeof body === "string") {
8413
+ outgoing.writeHead(status, {
8414
+ "Content-Type": defaultContentType,
8415
+ "Content-Length": Buffer.byteLength(body)
8416
+ });
8417
+ outgoing.end(body);
8418
+ } else if (body instanceof Uint8Array) {
8419
+ outgoing.writeHead(status, {
8420
+ "Content-Type": defaultContentType,
8421
+ "Content-Length": body.byteLength
8422
+ });
8423
+ outgoing.end(body);
8424
+ } else if (body instanceof Blob) {
8425
+ outgoing.writeHead(status, {
8426
+ "Content-Type": defaultContentType,
8427
+ "Content-Length": body.size
8428
+ });
8429
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
8430
+ } else {
8431
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
8432
+ flushHeaders(outgoing);
8433
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
8434
+ }
8435
+ outgoing[outgoingEnded]?.();
8436
+ return;
8437
+ }
8031
8438
  let hasContentLength = false;
8032
- if (!header) header = { "content-type": "text/plain; charset=UTF-8" };
8033
- else if (header instanceof Headers) {
8439
+ if (header instanceof Headers) {
8034
8440
  hasContentLength = header.has("content-length");
8035
- header = buildOutgoingHttpHeaders(header);
8441
+ header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
8036
8442
  } else if (Array.isArray(header)) {
8037
8443
  const headerObj = new Headers(header);
8038
8444
  hasContentLength = headerObj.has("content-length");
8039
- header = buildOutgoingHttpHeaders(headerObj);
8445
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
8040
8446
  } else for (const key in header) if (key.length === 14 && key.toLowerCase() === "content-length") {
8041
8447
  hasContentLength = true;
8042
8448
  break;
@@ -8047,7 +8453,8 @@ var responseViaCache = async (res, outgoing) => {
8047
8453
  else if (body instanceof Blob) header["Content-Length"] = body.size;
8048
8454
  }
8049
8455
  outgoing.writeHead(status, header);
8050
- if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
8456
+ if (body == null) outgoing.end();
8457
+ else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
8051
8458
  else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
8052
8459
  else {
8053
8460
  flushHeaders(outgoing);
@@ -8066,7 +8473,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
8066
8473
  }
8067
8474
  else res = await res.catch(handleFetchError);
8068
8475
  if (cacheKey in res) return responseViaCache(res, outgoing);
8069
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
8476
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
8070
8477
  if (res.body) {
8071
8478
  const reader = res.body.getReader();
8072
8479
  const values = [];
@@ -8106,7 +8513,7 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
8106
8513
  if (values.length === 0) flushHeaders(outgoing);
8107
8514
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
8108
8515
  }
8109
- } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
8516
+ } else if (resHeaderRecord["x-hono-already-sent"]) {} else {
8110
8517
  outgoing.writeHead(res.status, resHeaderRecord);
8111
8518
  outgoing.end();
8112
8519
  }
@@ -8116,47 +8523,45 @@ var getRequestListener = (fetchCallback, options = {}) => {
8116
8523
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
8117
8524
  if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
8118
8525
  Object.defineProperty(global, "Request", { value: Request$1 });
8119
- Object.defineProperty(global, "Response", { value: Response2 });
8526
+ Object.defineProperty(global, "Response", { value: Response$1 });
8120
8527
  }
8121
8528
  return async (incoming, outgoing) => {
8122
8529
  let res, req;
8530
+ let needsBodyCleanup = false;
8531
+ let closeHandlerAttached = false;
8532
+ const ensureCloseHandler = () => {
8533
+ if (!req || closeHandlerAttached) return;
8534
+ closeHandlerAttached = true;
8535
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
8536
+ };
8123
8537
  try {
8124
8538
  req = newRequest(incoming, options.hostname);
8125
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
8126
- if (!incomingEnded) {
8539
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
8540
+ if (needsBodyCleanup) {
8127
8541
  incoming[wrapBodyStream] = true;
8128
- incoming.on("end", () => {
8129
- incomingEnded = true;
8130
- });
8131
8542
  if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
8132
- if (!incomingEnded) setTimeout(() => {
8133
- if (!incomingEnded) setTimeout(() => {
8134
- drainIncoming(incoming);
8543
+ if (!incoming.readableEnded) setTimeout(() => {
8544
+ if (!incoming.readableEnded) setTimeout(() => {
8545
+ incoming.destroy();
8546
+ outgoing.destroy();
8135
8547
  });
8136
8548
  });
8137
8549
  };
8138
- outgoing.on("finish", () => {
8139
- if (!incomingEnded) drainIncoming(incoming);
8140
- });
8141
8550
  }
8142
- outgoing.on("close", () => {
8143
- if (req[abortControllerKey]) {
8144
- if (incoming.errored) req[abortControllerKey].abort(incoming.errored.toString());
8145
- else if (!outgoing.writableFinished) req[abortControllerKey].abort("Client connection prematurely closed.");
8146
- }
8147
- if (!incomingEnded) setTimeout(() => {
8148
- if (!incomingEnded) setTimeout(() => {
8149
- drainIncoming(incoming);
8150
- });
8151
- });
8152
- });
8153
8551
  res = fetchCallback(req, {
8154
8552
  incoming,
8155
8553
  outgoing
8156
8554
  });
8157
- if (cacheKey in res) return responseViaCache(res, outgoing);
8555
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
8556
+ if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
8557
+ if (!incoming.readableEnded) drainIncoming(incoming);
8558
+ });
8559
+ return responseViaCache(res, outgoing);
8560
+ }
8561
+ ensureCloseHandler();
8158
8562
  } catch (e) {
8159
8563
  if (!res) if (options.errorHandler) {
8564
+ ensureCloseHandler();
8160
8565
  res = await options.errorHandler(req ? e : toRequestError(e));
8161
8566
  if (!res) return;
8162
8567
  } else if (!req) res = handleRequestError();
@@ -8170,6 +8575,8 @@ var getRequestListener = (fetchCallback, options = {}) => {
8170
8575
  }
8171
8576
  };
8172
8577
  };
8578
+ globalThis.CloseEvent;
8579
+ globalThis.ErrorEvent;
8173
8580
  //#endregion
8174
8581
  //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js
8175
8582
  /**
@@ -8874,16 +9281,18 @@ var StreamableHTTPServerTransport = class {
8874
9281
  }
8875
9282
  };
8876
9283
  //#endregion
8877
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+ext-apps@1.7.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__react-_bc4d5adeaec14d46b9a46bfff8177b13/node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.js
9284
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+ext-apps@1.7.4_@modelcontextprotocol+sdk@1.29.0_zod@4.4.3__react-_b5c68214f1621bc5f24903738e19c6a8/node_modules/@modelcontextprotocol/ext-apps/dist/src/server/index.js
8878
9285
  ((Z) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(Z, { get: ($, J) => (typeof __require < "u" ? __require : $)[J] }) : Z)(function(Z) {
8879
9286
  if (typeof __require < "u") return __require.apply(this, arguments);
8880
9287
  throw Error("Dynamic require of \"" + Z + "\" is not supported");
8881
9288
  });
8882
- var v = union([literal("light"), literal("dark")]).describe("Color theme preference for the host environment."), K = union([
9289
+ var v = union([literal("light"), literal("dark")]).describe("Color theme preference for the host environment.");
9290
+ var K = union([
8883
9291
  literal("inline"),
8884
9292
  literal("fullscreen"),
8885
9293
  literal("pip")
8886
- ]).describe("Display mode for UI presentation."), ZQ = record(union([
9294
+ ]).describe("Display mode for UI presentation.");
9295
+ var ZQ = record(union([
8887
9296
  literal("--color-background-primary"),
8888
9297
  literal("--color-background-secondary"),
8889
9298
  literal("--color-background-tertiary"),
@@ -8998,7 +9407,8 @@ var Y = object({
8998
9407
  resourceDomains: array(string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),
8999
9408
  frameDomains: array(string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),
9000
9409
  baseUriDomains: array(string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")
9001
- }), j = object({
9410
+ });
9411
+ var j = object({
9002
9412
  camera: object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),
9003
9413
  microphone: object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),
9004
9414
  geolocation: object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),
@@ -9023,7 +9433,8 @@ object({
9023
9433
  method: literal("ui/notifications/tool-cancelled"),
9024
9434
  params: object({ reason: string().optional().describe("Optional reason for the cancellation (e.g., \"user action\", \"timeout\").") })
9025
9435
  });
9026
- var f = object({ fonts: string().optional() }), u = object({
9436
+ var f = object({ fonts: string().optional() });
9437
+ var u = object({
9027
9438
  variables: ZQ.optional().describe("CSS variables for theming the app."),
9028
9439
  css: f.optional().describe("CSS blocks that apps can inject.")
9029
9440
  });
@@ -9058,7 +9469,8 @@ var d = object({
9058
9469
  updateModelContext: O.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),
9059
9470
  message: O.optional().describe("Host supports receiving content messages (ui/message) from the view."),
9060
9471
  sampling: object({ tools: object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.") }).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")
9061
- }), h = object({
9472
+ });
9473
+ var h = object({
9062
9474
  experimental: object({}).optional().describe("Experimental features (structure TBD)."),
9063
9475
  tools: object({ listChanged: boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."),
9064
9476
  availableDisplayModes: array(K).optional().describe("Display modes the app supports.")
@@ -9181,7 +9593,8 @@ object({
9181
9593
  hostCapabilities: d.describe("Features and capabilities provided by the host."),
9182
9594
  hostContext: T.describe("Rich context about the host environment.")
9183
9595
  }).passthrough();
9184
- var C = "ui/resourceUri", p = "text/html;profile=mcp-app";
9596
+ var C = "ui/resourceUri";
9597
+ var p = "text/html;profile=mcp-app";
9185
9598
  function K3(Z, $, J, X) {
9186
9599
  let V = J._meta, D = V.ui, L = V[C], W = V;
9187
9600
  if (D?.resourceUri && !L) W = {