@cyanheads/git-mcp-server 2.11.1 → 2.12.0

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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +907 -361
  3. package/package.json +11 -11
package/dist/index.js CHANGED
@@ -15284,7 +15284,7 @@ var package_default;
15284
15284
  var init_package = __esm(() => {
15285
15285
  package_default = {
15286
15286
  name: "@cyanheads/git-mcp-server",
15287
- version: "2.11.1",
15287
+ version: "2.12.0",
15288
15288
  mcpName: "io.github.cyanheads/git-mcp-server",
15289
15289
  description: "A secure and scalable Git MCP server enabling AI agents to perform comprehensive Git version control operations via STDIO and Streamable HTTP.",
15290
15290
  main: "dist/index.js",
@@ -15343,10 +15343,10 @@ var init_package = __esm(() => {
15343
15343
  "publish-mcp": "bun scripts/validate-mcp-publish-schema.ts"
15344
15344
  },
15345
15345
  devDependencies: {
15346
- "@cloudflare/workers-types": "^4.20260418.1",
15346
+ "@cloudflare/workers-types": "^4.20260423.1",
15347
15347
  "@eslint/js": "^10.0.1",
15348
15348
  "@hono/mcp": "^0.2.5",
15349
- "@hono/node-server": "^1.19.14",
15349
+ "@hono/node-server": "^2.0.0",
15350
15350
  "@modelcontextprotocol/sdk": "^1.29.0",
15351
15351
  "@opentelemetry/api": "^1.9.1",
15352
15352
  "@opentelemetry/auto-instrumentations-node": "^0.73.0",
@@ -15358,13 +15358,13 @@ var init_package = __esm(() => {
15358
15358
  "@opentelemetry/sdk-node": "^0.215.0",
15359
15359
  "@opentelemetry/sdk-trace-node": "^2.7.0",
15360
15360
  "@opentelemetry/semantic-conventions": "^1.40.0",
15361
- "@supabase/supabase-js": "^2.103.3",
15362
- "@types/bun": "^1.3.12",
15361
+ "@supabase/supabase-js": "^2.104.1",
15362
+ "@types/bun": "^1.3.13",
15363
15363
  "@types/cross-spawn": "^6.0.6",
15364
15364
  "@types/node": "^25.6.0",
15365
15365
  "@types/validator": "^13.15.10",
15366
- "@vitest/coverage-v8": "^4.1.4",
15367
- "bun-types": "^1.3.12",
15366
+ "@vitest/coverage-v8": "^4.1.5",
15367
+ "bun-types": "^1.3.13",
15368
15368
  depcheck: "^1.4.7",
15369
15369
  dotenv: "^17.4.2",
15370
15370
  eslint: "^10.2.1",
@@ -15374,7 +15374,7 @@ var init_package = __esm(() => {
15374
15374
  husky: "^9.1.7",
15375
15375
  ignore: "^7.0.5",
15376
15376
  jose: "^6.2.2",
15377
- msw: "^2.13.4",
15377
+ msw: "^2.13.5",
15378
15378
  prettier: "^3.8.3",
15379
15379
  "reflect-metadata": "^0.2.2",
15380
15380
  repomix: "^1.13.1",
@@ -15382,11 +15382,11 @@ var init_package = __esm(() => {
15382
15382
  tsyringe: "^4.10.0",
15383
15383
  typedoc: "^0.28.19",
15384
15384
  typescript: "^6.0.3",
15385
- "typescript-eslint": "^8.58.2",
15385
+ "typescript-eslint": "^8.59.0",
15386
15386
  validator: "^13.15.35",
15387
- vite: "^8.0.8",
15387
+ vite: "^8.0.10",
15388
15388
  "vite-tsconfig-paths": "^6.1.1",
15389
- vitest: "^4.1.4",
15389
+ vitest: "^4.1.5",
15390
15390
  zod: "^4.3.6"
15391
15391
  },
15392
15392
  keywords: [
@@ -60779,7 +60779,7 @@ var require_root = __commonJS((exports, module) => {
60779
60779
  return values;
60780
60780
  }();
60781
60781
  Span.Event = function() {
60782
- function Event(properties) {
60782
+ function Event2(properties) {
60783
60783
  this.attributes = [];
60784
60784
  if (properties) {
60785
60785
  for (var keys = Object.keys(properties), i2 = 0;i2 < keys.length; ++i2)
@@ -60787,14 +60787,14 @@ var require_root = __commonJS((exports, module) => {
60787
60787
  this[keys[i2]] = properties[keys[i2]];
60788
60788
  }
60789
60789
  }
60790
- Event.prototype.timeUnixNano = null;
60791
- Event.prototype.name = null;
60792
- Event.prototype.attributes = $util.emptyArray;
60793
- Event.prototype.droppedAttributesCount = null;
60794
- Event.create = function create(properties) {
60795
- return new Event(properties);
60790
+ Event2.prototype.timeUnixNano = null;
60791
+ Event2.prototype.name = null;
60792
+ Event2.prototype.attributes = $util.emptyArray;
60793
+ Event2.prototype.droppedAttributesCount = null;
60794
+ Event2.create = function create(properties) {
60795
+ return new Event2(properties);
60796
60796
  };
60797
- Event.encode = function encode3(message, writer) {
60797
+ Event2.encode = function encode3(message, writer) {
60798
60798
  if (!writer)
60799
60799
  writer = $Writer.create();
60800
60800
  if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano"))
@@ -60808,10 +60808,10 @@ var require_root = __commonJS((exports, module) => {
60808
60808
  writer.uint32(32).uint32(message.droppedAttributesCount);
60809
60809
  return writer;
60810
60810
  };
60811
- Event.encodeDelimited = function encodeDelimited(message, writer) {
60811
+ Event2.encodeDelimited = function encodeDelimited(message, writer) {
60812
60812
  return this.encode(message, writer).ldelim();
60813
60813
  };
60814
- Event.decode = function decode3(reader, length, error48) {
60814
+ Event2.decode = function decode3(reader, length, error48) {
60815
60815
  if (!(reader instanceof $Reader))
60816
60816
  reader = $Reader.create(reader);
60817
60817
  var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Event;
@@ -60845,12 +60845,12 @@ var require_root = __commonJS((exports, module) => {
60845
60845
  }
60846
60846
  return message;
60847
60847
  };
60848
- Event.decodeDelimited = function decodeDelimited(reader) {
60848
+ Event2.decodeDelimited = function decodeDelimited(reader) {
60849
60849
  if (!(reader instanceof $Reader))
60850
60850
  reader = new $Reader(reader);
60851
60851
  return this.decode(reader, reader.uint32());
60852
60852
  };
60853
- Event.verify = function verify(message) {
60853
+ Event2.verify = function verify(message) {
60854
60854
  if (typeof message !== "object" || message === null)
60855
60855
  return "object expected";
60856
60856
  if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) {
@@ -60876,7 +60876,7 @@ var require_root = __commonJS((exports, module) => {
60876
60876
  }
60877
60877
  return null;
60878
60878
  };
60879
- Event.fromObject = function fromObject(object2) {
60879
+ Event2.fromObject = function fromObject(object2) {
60880
60880
  if (object2 instanceof $root.opentelemetry.proto.trace.v1.Span.Event)
60881
60881
  return object2;
60882
60882
  var message = new $root.opentelemetry.proto.trace.v1.Span.Event;
@@ -60906,7 +60906,7 @@ var require_root = __commonJS((exports, module) => {
60906
60906
  message.droppedAttributesCount = object2.droppedAttributesCount >>> 0;
60907
60907
  return message;
60908
60908
  };
60909
- Event.toObject = function toObject(message, options) {
60909
+ Event2.toObject = function toObject(message, options) {
60910
60910
  if (!options)
60911
60911
  options = {};
60912
60912
  var object2 = {};
@@ -60937,16 +60937,16 @@ var require_root = __commonJS((exports, module) => {
60937
60937
  object2.droppedAttributesCount = message.droppedAttributesCount;
60938
60938
  return object2;
60939
60939
  };
60940
- Event.prototype.toJSON = function toJSON() {
60940
+ Event2.prototype.toJSON = function toJSON() {
60941
60941
  return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
60942
60942
  };
60943
- Event.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
60943
+ Event2.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
60944
60944
  if (typeUrlPrefix === undefined) {
60945
60945
  typeUrlPrefix = "type.googleapis.com";
60946
60946
  }
60947
60947
  return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Event";
60948
60948
  };
60949
- return Event;
60949
+ return Event2;
60950
60950
  }();
60951
60951
  Span.Link = function() {
60952
60952
  function Link(properties) {
@@ -105608,7 +105608,8 @@ var init_requestContext = __esm(() => {
105608
105608
  }
105609
105609
  const authStore = authContext.getStore();
105610
105610
  const tenantIdFromAuth = authStore?.authInfo?.tenantId;
105611
- const requestId = typeof inheritedContext.requestId === "string" && inheritedContext.requestId ? inheritedContext.requestId : generateRequestContextId();
105611
+ const inheritedRequestId = inheritedContext.requestId;
105612
+ const requestId = typeof inheritedRequestId === "string" && inheritedRequestId ? inheritedRequestId : generateRequestContextId();
105612
105613
  const timestamp = new Date().toISOString();
105613
105614
  const restTenantId = typeof rest.tenantId === "string" ? rest.tenantId : undefined;
105614
105615
  const additionalTenantId = additionalContext && typeof additionalContext === "object" && typeof additionalContext.tenantId === "string" ? additionalContext.tenantId : undefined;
@@ -115934,7 +115935,7 @@ Suggested solution: ${env.workaround}`;
115934
115935
  var require_version48 = __commonJS((exports) => {
115935
115936
  Object.defineProperty(exports, "__esModule", { value: true });
115936
115937
  exports.version = undefined;
115937
- exports.version = "2.103.3";
115938
+ exports.version = "2.104.1";
115938
115939
  });
115939
115940
 
115940
115941
  // node_modules/@supabase/realtime-js/dist/main/lib/constants.js
@@ -118798,7 +118799,7 @@ var require_main3 = __commonJS((exports) => {
118798
118799
  var require_version49 = __commonJS((exports) => {
118799
118800
  Object.defineProperty(exports, "__esModule", { value: true });
118800
118801
  exports.version = undefined;
118801
- exports.version = "2.103.3";
118802
+ exports.version = "2.104.1";
118802
118803
  });
118803
118804
 
118804
118805
  // node_modules/@supabase/auth-js/dist/main/lib/constants.js
@@ -119380,7 +119381,7 @@ var require_helpers2 = __commonJS((exports) => {
119380
119381
  const codeVerifier = generatePKCEVerifier();
119381
119382
  let storedCodeVerifier = codeVerifier;
119382
119383
  if (isPasswordRecovery) {
119383
- storedCodeVerifier += "/PASSWORD_RECOVERY";
119384
+ storedCodeVerifier += "/recovery";
119384
119385
  }
119385
119386
  await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier);
119386
119387
  const codeChallenge = await generatePKCEChallenge(codeVerifier);
@@ -121615,7 +121616,7 @@ var require_GoTrueClient = __commonJS((exports) => {
121615
121616
  }
121616
121617
  if (data.session) {
121617
121618
  await this._saveSession(data.session);
121618
- await this._notifyAllSubscribers("SIGNED_IN", data.session);
121619
+ await this._notifyAllSubscribers(redirectType === "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", data.session);
121619
121620
  }
121620
121621
  return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== undefined ? redirectType : null }), error: error48 });
121621
121622
  } catch (error48) {
@@ -122130,6 +122131,7 @@ var require_GoTrueClient = __commonJS((exports) => {
122130
122131
  }
122131
122132
  }
122132
122133
  async _getSessionFromURL(params, callbackUrlType) {
122134
+ var _a2;
122133
122135
  try {
122134
122136
  if (!(0, helpers_1.isBrowser)())
122135
122137
  throw new errors_1.AuthImplicitGrantRedirectError("No browser detected.");
@@ -122162,7 +122164,10 @@ var require_GoTrueClient = __commonJS((exports) => {
122162
122164
  const url2 = new URL(window.location.href);
122163
122165
  url2.searchParams.delete("code");
122164
122166
  window.history.replaceState(window.history.state, "", url2.toString());
122165
- return { data: { session: data2.session, redirectType: null }, error: null };
122167
+ return {
122168
+ data: { session: data2.session, redirectType: (_a2 = data2.redirectType) !== null && _a2 !== undefined ? _a2 : null },
122169
+ error: null
122170
+ };
122166
122171
  }
122167
122172
  const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type } = params;
122168
122173
  if (!access_token || !expires_in || !refresh_token || !token_type) {
@@ -131567,6 +131572,21 @@ var StorageVectorsErrorCode = /* @__PURE__ */ function(StorageVectorsErrorCode$1
131567
131572
  StorageVectorsErrorCode$1["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded";
131568
131573
  return StorageVectorsErrorCode$1;
131569
131574
  }({});
131575
+ function setHeader(headers, name, value) {
131576
+ const result = _objectSpread22({}, headers);
131577
+ const nameLower = name.toLowerCase();
131578
+ for (const key of Object.keys(result))
131579
+ if (key.toLowerCase() === nameLower)
131580
+ delete result[key];
131581
+ result[nameLower] = value;
131582
+ return result;
131583
+ }
131584
+ function normalizeHeaders(headers) {
131585
+ const result = {};
131586
+ for (const [key, value] of Object.entries(headers))
131587
+ result[key.toLowerCase()] = value;
131588
+ return result;
131589
+ }
131570
131590
  var resolveFetch = (customFetch) => {
131571
131591
  if (customFetch)
131572
131592
  return (...args) => customFetch(...args);
@@ -131635,7 +131655,7 @@ var _getRequestParams = (method, options, parameters, body) => {
131635
131655
  for (const [key, value] of Object.entries(headers))
131636
131656
  if (key.toLowerCase() === "content-type")
131637
131657
  contentType = value;
131638
- params.headers = setRequestHeader(headers, "Content-Type", (_contentType = contentType) !== null && _contentType !== undefined ? _contentType : "application/json");
131658
+ params.headers = setHeader(headers, "Content-Type", (_contentType = contentType) !== null && _contentType !== undefined ? _contentType : "application/json");
131639
131659
  params.body = JSON.stringify(body);
131640
131660
  } else
131641
131661
  params.body = body;
@@ -131643,14 +131663,6 @@ var _getRequestParams = (method, options, parameters, body) => {
131643
131663
  params.duplex = options.duplex;
131644
131664
  return _objectSpread22(_objectSpread22({}, params), parameters);
131645
131665
  };
131646
- function setRequestHeader(headers, name, value) {
131647
- const nextHeaders = _objectSpread22({}, headers);
131648
- for (const key of Object.keys(nextHeaders))
131649
- if (key.toLowerCase() === name.toLowerCase())
131650
- delete nextHeaders[key];
131651
- nextHeaders[name] = value;
131652
- return nextHeaders;
131653
- }
131654
131666
  async function _handleRequest(fetcher, method, url2, options, parameters, body, namespace) {
131655
131667
  return new Promise((resolve, reject) => {
131656
131668
  fetcher(url2, _getRequestParams(method, options, parameters, body)).then((result) => {
@@ -131695,7 +131707,7 @@ var BaseApiClient = class {
131695
131707
  constructor(url2, headers = {}, fetch$1, namespace = "storage") {
131696
131708
  this.shouldThrowOnError = false;
131697
131709
  this.url = url2;
131698
- this.headers = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
131710
+ this.headers = normalizeHeaders(headers);
131699
131711
  this.fetch = resolveFetch(fetch$1);
131700
131712
  this.namespace = namespace;
131701
131713
  }
@@ -131704,7 +131716,7 @@ var BaseApiClient = class {
131704
131716
  return this;
131705
131717
  }
131706
131718
  setHeader(name, value) {
131707
- this.headers = _objectSpread22(_objectSpread22({}, this.headers), {}, { [name.toLowerCase()]: value });
131719
+ this.headers = setHeader(this.headers, name, value);
131708
131720
  return this;
131709
131721
  }
131710
131722
  async handleOperation(operation) {
@@ -131845,7 +131857,8 @@ var StorageFileApi = class extends BaseApiClient {
131845
131857
  options.duplex = "half";
131846
131858
  }
131847
131859
  if (fileOptions === null || fileOptions === undefined ? undefined : fileOptions.headers)
131848
- headers = _objectSpread22(_objectSpread22({}, headers), fileOptions.headers);
131860
+ for (const [key, value] of Object.entries(fileOptions.headers))
131861
+ headers = setHeader(headers, key, value);
131849
131862
  const cleanPath = _this._removeEmptyFolders(path2);
131850
131863
  const _path = _this._getFinalPath(cleanPath);
131851
131864
  const data = await (method == "PUT" ? put : post)(_this.fetch, `${_this.url}/object/${_path}`, body, _objectSpread22({ headers }, (options === null || options === undefined ? undefined : options.duplex) ? { duplex: options.duplex } : {}));
@@ -132069,7 +132082,7 @@ var StorageFileApi = class extends BaseApiClient {
132069
132082
  return query;
132070
132083
  }
132071
132084
  };
132072
- var version2 = "2.103.3";
132085
+ var version2 = "2.104.1";
132073
132086
  var DEFAULT_HEADERS = { "X-Client-Info": `storage-js/${version2}` };
132074
132087
  var StorageBucketApi = class extends BaseApiClient {
132075
132088
  constructor(url2, headers = {}, fetch$1, opts) {
@@ -132452,7 +132465,7 @@ var StorageClient = class extends StorageBucketApi {
132452
132465
  var import_auth_js = __toESM(require_main4(), 1);
132453
132466
  __reExport(exports_dist3, __toESM(require_main3(), 1));
132454
132467
  __reExport(exports_dist3, __toESM(require_main4(), 1));
132455
- var version3 = "2.103.3";
132468
+ var version3 = "2.104.1";
132456
132469
  var JS_ENV = "";
132457
132470
  if (typeof Deno !== "undefined")
132458
132471
  JS_ENV = "deno";
@@ -132620,7 +132633,8 @@ var SupabaseClient = class {
132620
132633
  this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch);
132621
132634
  this.realtime = this._initRealtimeClient(_objectSpread23({
132622
132635
  headers: this.headers,
132623
- accessToken: this._getAccessToken.bind(this)
132636
+ accessToken: this._getAccessToken.bind(this),
132637
+ fetch: this.fetch
132624
132638
  }, settings.realtime));
132625
132639
  if (this.accessToken)
132626
132640
  Promise.resolve(this.accessToken()).then((token) => this.realtime.setAuth(token)).catch((e2) => console.warn("Failed to set initial Realtime auth token:", e2));
@@ -146537,11 +146551,10 @@ import path4 from "path";
146537
146551
  init_config();
146538
146552
  var TOOL_NAME10 = "git_wrapup_instructions";
146539
146553
  var TOOL_TITLE10 = "Git Wrap-up Instructions";
146540
- var TOOL_DESCRIPTION10 = "Provides the user's desired Git wrap-up workflow and instructions. Returns custom workflow steps (if configured) or default best practices for reviewing, documenting, and committing changes. Includes current repository status to guide next actions.";
146554
+ var TOOL_DESCRIPTION10 = "Returns a Git wrap-up protocol: an acceptance-criteria checklist the agent must satisfy before the session is considered shipped. Uses the operator's custom instructions if configured, otherwise emits a generic goals-strict/mechanism-generic default. Includes current repository status to guide next actions.";
146541
146555
  var InputSchema10 = exports_external.object({
146542
146556
  acknowledgement: exports_external.enum(["Y", "y", "Yes", "yes"]).describe("Acknowledgement to initiate the wrap-up workflow."),
146543
- updateAgentMetaFiles: exports_external.enum(["Y", "y", "Yes", "yes"]).optional().describe("Include an instruction to update agent-specific meta files."),
146544
- createTag: exports_external.boolean().optional().describe("If true, instructs the agent to create a Git tag after committing all changes. Only set to true if given permission to do so.")
146557
+ createTag: exports_external.boolean().optional().describe("Controls whether the tag criterion appears in the emitted protocol. Omit or set `true` to include the tag step. Set `false` to omit it entirely — e.g., when tagging is deferred to a separate release step.")
146545
146558
  });
146546
146559
  var OutputSchema11 = exports_external.object({
146547
146560
  instructions: exports_external.string().describe("The set of instructions for the wrap-up workflow."),
@@ -146553,71 +146566,73 @@ var OutputSchema11 = exports_external.object({
146553
146566
  }).optional().describe("The current structured git status."),
146554
146567
  gitStatusError: exports_external.string().optional().describe("Any error message if getting git status failed.")
146555
146568
  });
146556
- var DEFAULT_WRAPUP_INSTRUCTIONS = `
146557
- # Git Wrap-up Protocol
146569
+ function buildDefaultInstructions(input) {
146570
+ const tagCriterion = input.createTag === false ? "" : "\n- [ ] Annotated tag at the project's convention (typically `v<version>`) with a concise message summarizing the real changes — no filler. Flag if a tag already exists at this commit.";
146571
+ return `# Git Wrap-up
146572
+
146573
+ **Outcome**: a new release — version bumped, changes documented and verified, committed atomically, and tagged.
146574
+
146575
+ **Philosophy**: strict on goals, generic on mechanism. The acceptance checkboxes are fixed; everything beneath them is guidance that defers to project convention.
146558
146576
 
146559
- **Objective**: Systematically review, document, and commit all pending changes in the repository. Adherence to this protocol is mandatory.
146577
+ ## Orient
146560
146578
 
146561
- ### Phase 1: Analysis and Planning
146579
+ Before touching git, read the project. Check the root agent-instruction file (\`AGENTS.md\`, \`CLAUDE.md\`, or equivalent) for wrap-up expectations, version locations, and any bespoke checklist. Identify:
146562
146580
 
146563
- You must begin by creating a task list that mirrors this protocol. This is your operational plan.
146581
+ - how changes are recorded (flat changelog, directory-based, release-notes tooling, or none)
146582
+ - where versions are declared (manifest, server descriptor, \`VERSION\` file, tag-driven, or embedded in docs)
146583
+ - what verification looks like (the project's check-suite, which may be a single combined command or several run in sequence)
146584
+ - what mirrors version or structure (badges, generated docs, agent-instruction files, templated files)
146564
146585
 
146565
- **Example Task List:**
146566
- \`\`\`
146567
- - [ ] Set Git working directory (if not set)
146568
- - [ ] Analyze repository changes with git_diff
146569
- - [ ] Update CHANGELOG.md with all modifications
146570
- - [ ] Review and update README.md for currency
146571
- - [ ] Commit changes in logical, atomic units
146572
- - [ ] Verify final repository status
146573
- \`\`\`
146586
+ If the project documents its own wrap-up procedure, follow it — the checklist below is the baseline, not an override.
146574
146587
 
146575
- ### Phase 2: Execution Workflow
146588
+ ## Acceptance criteria
146576
146589
 
146577
- Execute the following steps sequentially. Do not proceed until the prior step is confirmed complete.
146590
+ A wrap-up is complete when every checkbox is satisfied. Every wrap-up is a release: minimum patch bump unless the change warrants minor or major.
146578
146591
 
146579
- 1. **Set Context**: Ensure the working directory is correctly set using **\`git_set_working_dir\`**. This is a mandatory first step.
146592
+ - [ ] Full diff reviewed end-to-end before commits are planned
146593
+ - [ ] Version bumped per semver (default patch; minor/major when warranted) across every place the project declares it — manifest, server descriptor, badges, agent-instruction files, templated mirrors
146594
+ - [ ] Changelog updated under the new version in the project's existing format, or created conventionally if none exists
146595
+ - [ ] Documentation that references changed behaviour is current
146596
+ - [ ] Verification suite passes against the tree being committed
146597
+ - [ ] Commits are atomic and in Conventional Commits form${tagCriterion}
146580
146598
 
146581
- 2. **Analyze Changes**: Execute **\`git_diff\`** with the \`includeUntracked: true\` parameter. You must thoroughly analyze the output to understand the full scope and rationale of every modification. This analysis will inform & influence your commit strategy, commit messages, and overall workflow.
146599
+ **Commonly relevant files** (check these if present; exact names vary by project):
146582
146600
 
146583
- 3. **Update Changelog**: Read the **\`CHANGELOG.md\`** file. Append a new version entry detailing all changes. Your entry must be concise, use the past tense, and categorize modifications (e.g., "Added," "Changed," "Fixed").
146601
+ - **Documentation**: \`README.md\`, generated structure docs like \`docs/tree.md\`, and any usage or reference docs affected by the change.
146602
+ - **Agent-instruction files**: \`AGENTS.md\`, \`CLAUDE.md\`, or equivalents — if the code changes alter anything these files describe (architecture, available tools, conventions, file layout), update them to match. If they are symlinked or mirrored, edit the source; the link or mirror reflects automatically.
146603
+ - **Version sources**: manifests (\`package.json\`, \`pyproject.toml\`, \`Cargo.toml\`), server descriptors (\`server.json\`), \`VERSION\` files — bump in lockstep.
146584
146604
 
146585
- 4. **Review Documentation**: For any substantial code changes, you are required to review **\`README.md\`**. Ensure it accurately reflects the current state of the codebase. Update it as necessary.
146605
+ **Style defaults** (overridable by project convention):
146586
146606
 
146587
- 5. **Commit Changes**: Execute **\`git_commit\`** for each logical group of changes.
146588
- - Commits **must be atomic** and group related changes.
146589
- - Commit messages **must adhere** to the **Conventional Commits** standard (e.g., \`feat(auth): implement password reset\`).
146590
- - Use the \`filesToStage\` parameter to precisely control which files are included in each commit.
146607
+ - Cross-reference issues and PRs with full URLs — \`[#42](https://github.com/owner/repo/pull/42)\` or \`owner/repo#42\`. Bare \`#42\` breaks outside the GitHub web UI.
146608
+ - Commit and changelog entries lead with specifics — name the tool, service, or module affected in the first few words.
146591
146609
 
146592
- **Directive**: Create your task list now. Then, execute the protocol. Do not push to the remote unless explicitly instructed.
146610
+ ## Constraints
146611
+
146612
+ - Do not push to the remote unless explicitly instructed.
146613
+ - Do not bypass verification failures to land a green commit.
146614
+ - Do not rewrite published history.
146593
146615
  `;
146594
- function loadInstructions(filePath) {
146616
+ }
146617
+ function loadCustomInstructions(filePath) {
146595
146618
  if (!filePath) {
146596
- logger.debug("No custom instructions path configured, using default.");
146597
- return DEFAULT_WRAPUP_INSTRUCTIONS;
146619
+ logger.debug("No custom wrap-up instructions configured; using built-in default.");
146620
+ return null;
146598
146621
  }
146599
146622
  try {
146600
146623
  const resolvedPath = path4.resolve(filePath);
146601
- logger.debug(`Loading custom instructions from ${resolvedPath} at module initialization`);
146624
+ logger.debug(`Loading custom wrap-up instructions from ${resolvedPath} at module initialization.`);
146602
146625
  return readFileSync(resolvedPath, "utf-8");
146603
146626
  } catch (error48) {
146604
146627
  const errorMessage = error48 instanceof Error ? error48.message : "An unknown error occurred";
146605
- logger.warning(`Failed to load custom instructions from '${filePath}': ${errorMessage}. Falling back to default instructions.`);
146606
- return DEFAULT_WRAPUP_INSTRUCTIONS;
146628
+ logger.warning(`Failed to load custom wrap-up instructions from '${filePath}': ${errorMessage}. Falling back to built-in default.`);
146629
+ return null;
146607
146630
  }
146608
146631
  }
146609
- var baseInstructions = loadInstructions(config2?.git?.wrapupInstructionsPath);
146632
+ var customInstructions = loadCustomInstructions(config2?.git?.wrapupInstructionsPath);
146610
146633
  async function gitWrapupInstructionsLogic(input, { provider, storage, appContext }) {
146611
146634
  const tenantId = appContext.tenantId || "default-tenant";
146612
- let finalInstructions = baseInstructions;
146613
- if (input.updateAgentMetaFiles) {
146614
- finalInstructions += `
146615
- Extra request: review and update if needed the .cline_rules and claude.md files if present.`;
146616
- }
146617
- if (input.createTag) {
146618
- finalInstructions += `
146619
- 6. After all changes are committed and confirmed via 'git_status', use the 'git_tag' tool to create a new annotated tag. The tag name should follow semantic versioning (e.g., v1.2.3), and the annotation message should summarize the key changes in this wrap-up.`;
146620
- }
146635
+ const finalInstructions = customInstructions ?? buildDefaultInstructions(input);
146621
146636
  let gitStatus;
146622
146637
  let gitStatusError;
146623
146638
  try {
@@ -151098,44 +151113,115 @@ var RingBuffer = class {
151098
151113
  }
151099
151114
  };
151100
151115
 
151116
+ // node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs
151117
+ var X_ALREADY_SENT = "x-hono-already-sent";
151118
+
151119
+ // node_modules/@hono/node-server/dist/index.mjs
151120
+ import { STATUS_CODES, createServer } from "node:http";
151121
+ import { Http2ServerRequest, constants } from "node:http2";
151122
+ import { Readable } from "node:stream";
151123
+
151124
+ // node_modules/hono/dist/helper/websocket/index.js
151125
+ var WSContext = class {
151126
+ #init;
151127
+ constructor(init) {
151128
+ this.#init = init;
151129
+ this.raw = init.raw;
151130
+ this.url = init.url ? new URL(init.url) : null;
151131
+ this.protocol = init.protocol ?? null;
151132
+ }
151133
+ send(source, options) {
151134
+ this.#init.send(source, options ?? {});
151135
+ }
151136
+ raw;
151137
+ binaryType = "arraybuffer";
151138
+ get readyState() {
151139
+ return this.#init.readyState;
151140
+ }
151141
+ url;
151142
+ protocol;
151143
+ close(code, reason) {
151144
+ this.#init.close(code, reason);
151145
+ }
151146
+ };
151147
+ var defineWebSocketHelper = (handler) => {
151148
+ return (...args) => {
151149
+ if (typeof args[0] === "function") {
151150
+ const [createEvents, options] = args;
151151
+ return async function upgradeWebSocket(c, next) {
151152
+ const events = await createEvents(c);
151153
+ const result = await handler(c, events, options);
151154
+ if (result) {
151155
+ return result;
151156
+ }
151157
+ await next();
151158
+ };
151159
+ } else {
151160
+ const [c, events, options] = args;
151161
+ return (async () => {
151162
+ const upgraded = await handler(c, events, options);
151163
+ if (!upgraded) {
151164
+ throw new Error("Failed to upgrade WebSocket");
151165
+ }
151166
+ return upgraded;
151167
+ })();
151168
+ }
151169
+ };
151170
+ };
151171
+
151101
151172
  // node_modules/@hono/node-server/dist/index.mjs
151102
- import { createServer as createServerHTTP } from "http";
151103
- import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
151104
- import { Http2ServerRequest } from "http2";
151105
- import { Readable } from "stream";
151106
- import crypto3 from "crypto";
151107
151173
  var RequestError = class extends Error {
151108
151174
  constructor(message, options) {
151109
151175
  super(message, options);
151110
151176
  this.name = "RequestError";
151111
151177
  }
151112
151178
  };
151179
+ var reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
151180
+ var reDotSegment = /\/\.\.?(?:[/?#]|$)/;
151181
+ var reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
151182
+ var buildUrl2 = (scheme, host, incomingUrl) => {
151183
+ const url2 = `${scheme}://${host}${incomingUrl}`;
151184
+ if (!reValidHost.test(host)) {
151185
+ const urlObj = new URL(url2);
151186
+ if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase())
151187
+ throw new RequestError("Invalid host header");
151188
+ return urlObj.href;
151189
+ } else if (incomingUrl.length === 0)
151190
+ return url2 + "/";
151191
+ else {
151192
+ if (incomingUrl.charCodeAt(0) !== 47)
151193
+ throw new RequestError("Invalid URL");
151194
+ if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl))
151195
+ return new URL(url2).href;
151196
+ return url2;
151197
+ }
151198
+ };
151113
151199
  var toRequestError = (e2) => {
151114
- if (e2 instanceof RequestError) {
151200
+ if (e2 instanceof RequestError)
151115
151201
  return e2;
151116
- }
151117
151202
  return new RequestError(e2.message, { cause: e2 });
151118
151203
  };
151119
151204
  var GlobalRequest = global.Request;
151120
- var Request3 = class extends GlobalRequest {
151205
+ var Request$1 = class extends GlobalRequest {
151121
151206
  constructor(input, options) {
151122
151207
  if (typeof input === "object" && getRequestCache in input) {
151208
+ const hasReplacementBody = options !== undefined && "body" in options && options.body != null;
151209
+ if (input[bodyConsumedDirectlyKey] && !hasReplacementBody)
151210
+ throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
151123
151211
  input = input[getRequestCache]();
151124
151212
  }
151125
- if (typeof options?.body?.getReader !== "undefined") {
151213
+ if (typeof options?.body?.getReader !== "undefined")
151126
151214
  options.duplex ??= "half";
151127
- }
151128
151215
  super(input, options);
151129
151216
  }
151130
151217
  };
151131
151218
  var newHeadersFromIncoming = (incoming) => {
151132
151219
  const headerRecord = [];
151133
151220
  const rawHeaders = incoming.rawHeaders;
151134
- for (let i2 = 0;i2 < rawHeaders.length; i2 += 2) {
151135
- const { [i2]: key, [i2 + 1]: value } = rawHeaders;
151136
- if (key.charCodeAt(0) !== 58) {
151137
- headerRecord.push([key, value]);
151138
- }
151221
+ for (let i2 = 0, len = rawHeaders.length;i2 < len; i2 += 2) {
151222
+ const key = rawHeaders[i2];
151223
+ if (key.charCodeAt(0) !== 58)
151224
+ headerRecord.push([key, rawHeaders[i2 + 1]]);
151139
151225
  }
151140
151226
  return new Headers(headerRecord);
151141
151227
  };
@@ -151148,55 +151234,213 @@ var newRequestFromIncoming = (method, url2, headers, incoming, abortController)
151148
151234
  };
151149
151235
  if (method === "TRACE") {
151150
151236
  init.method = "GET";
151151
- const req = new Request3(url2, init);
151152
- Object.defineProperty(req, "method", {
151153
- get() {
151154
- return "TRACE";
151155
- }
151156
- });
151237
+ const req = new Request$1(url2, init);
151238
+ Object.defineProperty(req, "method", { get() {
151239
+ return "TRACE";
151240
+ } });
151157
151241
  return req;
151158
151242
  }
151159
- if (!(method === "GET" || method === "HEAD")) {
151160
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
151161
- init.body = new ReadableStream({
151162
- start(controller) {
151163
- controller.enqueue(incoming.rawBody);
151164
- controller.close();
151165
- }
151166
- });
151167
- } else if (incoming[wrapBodyStream]) {
151243
+ if (!(method === "GET" || method === "HEAD"))
151244
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer)
151245
+ init.body = new ReadableStream({ start(controller) {
151246
+ controller.enqueue(incoming.rawBody);
151247
+ controller.close();
151248
+ } });
151249
+ else if (incoming[wrapBodyStream]) {
151168
151250
  let reader;
151169
- init.body = new ReadableStream({
151170
- async pull(controller) {
151171
- try {
151172
- reader ||= Readable.toWeb(incoming).getReader();
151173
- const { done, value } = await reader.read();
151174
- if (done) {
151175
- controller.close();
151176
- } else {
151177
- controller.enqueue(value);
151178
- }
151179
- } catch (error48) {
151180
- controller.error(error48);
151181
- }
151251
+ init.body = new ReadableStream({ async pull(controller) {
151252
+ try {
151253
+ reader ||= Readable.toWeb(incoming).getReader();
151254
+ const { done, value } = await reader.read();
151255
+ if (done)
151256
+ controller.close();
151257
+ else
151258
+ controller.enqueue(value);
151259
+ } catch (error48) {
151260
+ controller.error(error48);
151182
151261
  }
151183
- });
151184
- } else {
151262
+ } });
151263
+ } else
151185
151264
  init.body = Readable.toWeb(incoming);
151186
- }
151187
- }
151188
- return new Request3(url2, init);
151265
+ return new Request$1(url2, init);
151189
151266
  };
151190
151267
  var getRequestCache = Symbol("getRequestCache");
151191
151268
  var requestCache = Symbol("requestCache");
151192
151269
  var incomingKey = Symbol("incomingKey");
151193
151270
  var urlKey = Symbol("urlKey");
151271
+ var methodKey = Symbol("methodKey");
151194
151272
  var headersKey = Symbol("headersKey");
151195
151273
  var abortControllerKey = Symbol("abortControllerKey");
151196
151274
  var getAbortController = Symbol("getAbortController");
151275
+ var abortRequest = Symbol("abortRequest");
151276
+ var bodyBufferKey = Symbol("bodyBuffer");
151277
+ var bodyReadPromiseKey = Symbol("bodyReadPromise");
151278
+ var bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
151279
+ var bodyLockReaderKey = Symbol("bodyLockReader");
151280
+ var abortReasonKey = Symbol("abortReason");
151281
+ var newBodyUnusableError = () => {
151282
+ return /* @__PURE__ */ new TypeError("Body is unusable");
151283
+ };
151284
+ var rejectBodyUnusable = () => {
151285
+ return Promise.reject(newBodyUnusableError());
151286
+ };
151287
+ var textDecoder = new TextDecoder;
151288
+ var consumeBodyDirectOnce = (request) => {
151289
+ if (request[bodyConsumedDirectlyKey])
151290
+ return rejectBodyUnusable();
151291
+ request[bodyConsumedDirectlyKey] = true;
151292
+ };
151293
+ var toArrayBuffer = (buf) => {
151294
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
151295
+ };
151296
+ var contentType = (request) => {
151297
+ return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
151298
+ };
151299
+ var methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
151300
+ var normalizeIncomingMethod = (method) => {
151301
+ if (typeof method !== "string" || method.length === 0)
151302
+ return "GET";
151303
+ switch (method) {
151304
+ case "DELETE":
151305
+ case "GET":
151306
+ case "HEAD":
151307
+ case "OPTIONS":
151308
+ case "POST":
151309
+ case "PUT":
151310
+ return method;
151311
+ }
151312
+ const upper = method.toUpperCase();
151313
+ switch (upper) {
151314
+ case "DELETE":
151315
+ case "GET":
151316
+ case "HEAD":
151317
+ case "OPTIONS":
151318
+ case "POST":
151319
+ case "PUT":
151320
+ return upper;
151321
+ default:
151322
+ return method;
151323
+ }
151324
+ };
151325
+ var validateDirectReadMethod = (method) => {
151326
+ if (!methodTokenRegExp.test(method))
151327
+ return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
151328
+ const normalized = method.toUpperCase();
151329
+ if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE")
151330
+ return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
151331
+ };
151332
+ var readBodyWithFastPath = (request, method, fromBuffer) => {
151333
+ if (request[bodyConsumedDirectlyKey])
151334
+ return rejectBodyUnusable();
151335
+ const methodName = request.method;
151336
+ if (methodName === "GET" || methodName === "HEAD")
151337
+ return request[getRequestCache]()[method]();
151338
+ const methodValidationError = validateDirectReadMethod(methodName);
151339
+ if (methodValidationError)
151340
+ return Promise.reject(methodValidationError);
151341
+ if (request[requestCache]) {
151342
+ if (methodName !== "TRACE")
151343
+ return request[requestCache][method]();
151344
+ }
151345
+ const alreadyUsedError = consumeBodyDirectOnce(request);
151346
+ if (alreadyUsedError)
151347
+ return alreadyUsedError;
151348
+ const raw2 = readRawBodyIfAvailable(request);
151349
+ if (raw2) {
151350
+ const result = Promise.resolve(fromBuffer(raw2, request));
151351
+ request[bodyBufferKey] = undefined;
151352
+ return result;
151353
+ }
151354
+ return readBodyDirect(request).then((buf) => {
151355
+ const result = fromBuffer(buf, request);
151356
+ request[bodyBufferKey] = undefined;
151357
+ return result;
151358
+ });
151359
+ };
151360
+ var readRawBodyIfAvailable = (request) => {
151361
+ const incoming = request[incomingKey];
151362
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer)
151363
+ return incoming.rawBody;
151364
+ };
151365
+ var readBodyDirect = (request) => {
151366
+ if (request[bodyBufferKey])
151367
+ return Promise.resolve(request[bodyBufferKey]);
151368
+ if (request[bodyReadPromiseKey])
151369
+ return request[bodyReadPromiseKey];
151370
+ const incoming = request[incomingKey];
151371
+ if (Readable.isDisturbed(incoming))
151372
+ return rejectBodyUnusable();
151373
+ const promise3 = new Promise((resolve2, reject) => {
151374
+ const chunks = [];
151375
+ let settled = false;
151376
+ const finish = (callback) => {
151377
+ if (settled)
151378
+ return;
151379
+ settled = true;
151380
+ cleanup();
151381
+ callback();
151382
+ };
151383
+ const onData = (chunk) => {
151384
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
151385
+ };
151386
+ const onEnd = () => {
151387
+ finish(() => {
151388
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
151389
+ request[bodyBufferKey] = buffer;
151390
+ resolve2(buffer);
151391
+ });
151392
+ };
151393
+ const onError = (error48) => {
151394
+ finish(() => {
151395
+ reject(error48);
151396
+ });
151397
+ };
151398
+ const onClose = () => {
151399
+ if (incoming.readableEnded) {
151400
+ onEnd();
151401
+ return;
151402
+ }
151403
+ finish(() => {
151404
+ if (incoming.errored) {
151405
+ reject(incoming.errored);
151406
+ return;
151407
+ }
151408
+ const reason = request[abortReasonKey];
151409
+ if (reason !== undefined) {
151410
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
151411
+ return;
151412
+ }
151413
+ reject(/* @__PURE__ */ new Error("Client connection prematurely closed."));
151414
+ });
151415
+ };
151416
+ const cleanup = () => {
151417
+ incoming.off("data", onData);
151418
+ incoming.off("end", onEnd);
151419
+ incoming.off("error", onError);
151420
+ incoming.off("close", onClose);
151421
+ request[bodyReadPromiseKey] = undefined;
151422
+ };
151423
+ incoming.on("data", onData);
151424
+ incoming.on("end", onEnd);
151425
+ incoming.on("error", onError);
151426
+ incoming.on("close", onClose);
151427
+ queueMicrotask(() => {
151428
+ if (settled)
151429
+ return;
151430
+ if (incoming.readableEnded)
151431
+ onEnd();
151432
+ else if (incoming.errored)
151433
+ onError(incoming.errored);
151434
+ else if (incoming.destroyed)
151435
+ onClose();
151436
+ });
151437
+ });
151438
+ request[bodyReadPromiseKey] = promise3;
151439
+ return promise3;
151440
+ };
151197
151441
  var requestPrototype = {
151198
151442
  get method() {
151199
- return this[incomingKey].method || "GET";
151443
+ return this[methodKey];
151200
151444
  },
151201
151445
  get url() {
151202
151446
  return this[urlKey];
@@ -151204,18 +151448,66 @@ var requestPrototype = {
151204
151448
  get headers() {
151205
151449
  return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
151206
151450
  },
151451
+ [abortRequest](reason) {
151452
+ if (this[abortReasonKey] === undefined)
151453
+ this[abortReasonKey] = reason;
151454
+ const abortController = this[abortControllerKey];
151455
+ if (abortController && !abortController.signal.aborted)
151456
+ abortController.abort(reason);
151457
+ },
151207
151458
  [getAbortController]() {
151208
- this[getRequestCache]();
151459
+ this[abortControllerKey] ||= new AbortController;
151460
+ if (this[abortReasonKey] !== undefined && !this[abortControllerKey].signal.aborted)
151461
+ this[abortControllerKey].abort(this[abortReasonKey]);
151209
151462
  return this[abortControllerKey];
151210
151463
  },
151211
151464
  [getRequestCache]() {
151212
- this[abortControllerKey] ||= new AbortController;
151213
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
151465
+ const abortController = this[getAbortController]();
151466
+ if (this[requestCache])
151467
+ return this[requestCache];
151468
+ const method = this.method;
151469
+ if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
151470
+ this[bodyBufferKey] = undefined;
151471
+ const init = {
151472
+ method: method === "TRACE" ? "GET" : method,
151473
+ headers: this.headers,
151474
+ signal: abortController.signal
151475
+ };
151476
+ if (method !== "TRACE") {
151477
+ init.body = new ReadableStream({ start(c) {
151478
+ c.close();
151479
+ } });
151480
+ init.duplex = "half";
151481
+ }
151482
+ const req = new Request$1(this[urlKey], init);
151483
+ if (method === "TRACE")
151484
+ Object.defineProperty(req, "method", { get() {
151485
+ return "TRACE";
151486
+ } });
151487
+ return this[requestCache] = req;
151488
+ }
151489
+ return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
151490
+ },
151491
+ get body() {
151492
+ if (!this[bodyConsumedDirectlyKey])
151493
+ return this[getRequestCache]().body;
151494
+ const request = this[getRequestCache]();
151495
+ if (!this[bodyLockReaderKey] && request.body)
151496
+ this[bodyLockReaderKey] = request.body.getReader();
151497
+ return request.body;
151498
+ },
151499
+ get bodyUsed() {
151500
+ if (this[bodyConsumedDirectlyKey])
151501
+ return true;
151502
+ if (this[requestCache])
151503
+ return this[requestCache].bodyUsed;
151504
+ return false;
151214
151505
  }
151215
151506
  };
151507
+ Object.defineProperty(requestPrototype, "signal", { get() {
151508
+ return this[getAbortController]().signal;
151509
+ } });
151216
151510
  [
151217
- "body",
151218
- "bodyUsed",
151219
151511
  "cache",
151220
151512
  "credentials",
151221
151513
  "destination",
@@ -151224,75 +151516,93 @@ var requestPrototype = {
151224
151516
  "redirect",
151225
151517
  "referrer",
151226
151518
  "referrerPolicy",
151227
- "signal",
151228
151519
  "keepalive"
151229
151520
  ].forEach((k) => {
151230
- Object.defineProperty(requestPrototype, k, {
151231
- get() {
151232
- return this[getRequestCache]()[k];
151233
- }
151234
- });
151235
- });
151236
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
151237
- Object.defineProperty(requestPrototype, k, {
151238
- value: function() {
151239
- return this[getRequestCache]()[k]();
151240
- }
151241
- });
151242
- });
151243
- Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
151244
- value: function(depth, options, inspectFn) {
151245
- const props = {
151246
- method: this.method,
151247
- url: this.url,
151248
- headers: this.headers,
151249
- nativeRequest: this[requestCache]
151250
- };
151251
- return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
151252
- }
151253
- });
151254
- Object.setPrototypeOf(requestPrototype, Request3.prototype);
151521
+ Object.defineProperty(requestPrototype, k, { get() {
151522
+ return this[getRequestCache]()[k];
151523
+ } });
151524
+ });
151525
+ ["clone", "formData"].forEach((k) => {
151526
+ Object.defineProperty(requestPrototype, k, { value: function() {
151527
+ if (this[bodyConsumedDirectlyKey]) {
151528
+ if (k === "clone")
151529
+ throw newBodyUnusableError();
151530
+ return rejectBodyUnusable();
151531
+ }
151532
+ return this[getRequestCache]()[k]();
151533
+ } });
151534
+ });
151535
+ Object.defineProperty(requestPrototype, "text", { value: function() {
151536
+ return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
151537
+ } });
151538
+ Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
151539
+ return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
151540
+ } });
151541
+ Object.defineProperty(requestPrototype, "blob", { value: function() {
151542
+ return readBodyWithFastPath(this, "blob", (buf, request) => {
151543
+ const type = contentType(request);
151544
+ const init = type ? { headers: { "content-type": type } } : undefined;
151545
+ return new Response(buf, init).blob();
151546
+ });
151547
+ } });
151548
+ Object.defineProperty(requestPrototype, "json", { value: function() {
151549
+ if (this[bodyConsumedDirectlyKey])
151550
+ return rejectBodyUnusable();
151551
+ return this.text().then(JSON.parse);
151552
+ } });
151553
+ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
151554
+ return `Request (lightweight) ${inspectFn({
151555
+ method: this.method,
151556
+ url: this.url,
151557
+ headers: this.headers,
151558
+ nativeRequest: this[requestCache]
151559
+ }, {
151560
+ ...options,
151561
+ depth: depth == null ? null : depth - 1
151562
+ })}`;
151563
+ } });
151564
+ Object.setPrototypeOf(requestPrototype, Request$1.prototype);
151255
151565
  var newRequest = (incoming, defaultHostname) => {
151256
151566
  const req = Object.create(requestPrototype);
151257
151567
  req[incomingKey] = incoming;
151568
+ req[methodKey] = normalizeIncomingMethod(incoming.method);
151258
151569
  const incomingUrl = incoming.url || "";
151259
151570
  if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
151260
- if (incoming instanceof Http2ServerRequest) {
151571
+ if (incoming instanceof Http2ServerRequest)
151261
151572
  throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
151262
- }
151263
151573
  try {
151264
- const url22 = new URL(incomingUrl);
151265
- req[urlKey] = url22.href;
151574
+ req[urlKey] = new URL(incomingUrl).href;
151266
151575
  } catch (e2) {
151267
151576
  throw new RequestError("Invalid absolute URL", { cause: e2 });
151268
151577
  }
151269
151578
  return req;
151270
151579
  }
151271
151580
  const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
151272
- if (!host) {
151581
+ if (!host)
151273
151582
  throw new RequestError("Missing host header");
151274
- }
151275
151583
  let scheme;
151276
151584
  if (incoming instanceof Http2ServerRequest) {
151277
151585
  scheme = incoming.scheme;
151278
- if (!(scheme === "http" || scheme === "https")) {
151586
+ if (!(scheme === "http" || scheme === "https"))
151279
151587
  throw new RequestError("Unsupported scheme");
151280
- }
151281
- } else {
151588
+ } else
151282
151589
  scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
151590
+ try {
151591
+ req[urlKey] = buildUrl2(scheme, host, incomingUrl);
151592
+ } catch (e2) {
151593
+ if (e2 instanceof RequestError)
151594
+ throw e2;
151595
+ else
151596
+ throw new RequestError("Invalid URL", { cause: e2 });
151283
151597
  }
151284
- const url2 = new URL(`${scheme}://${host}${incomingUrl}`);
151285
- if (url2.hostname.length !== host.length && url2.hostname !== host.replace(/:\d+$/, "")) {
151286
- throw new RequestError("Invalid host header");
151287
- }
151288
- req[urlKey] = url2.href;
151289
151598
  return req;
151290
151599
  };
151600
+ var defaultContentType = "text/plain; charset=UTF-8";
151291
151601
  var responseCache = Symbol("responseCache");
151292
151602
  var getResponseCache = Symbol("getResponseCache");
151293
151603
  var cacheKey = Symbol("cache");
151294
151604
  var GlobalResponse = global.Response;
151295
- var Response22 = class _Response {
151605
+ var Response$1 = class Response$12 {
151296
151606
  #body;
151297
151607
  #init;
151298
151608
  [getResponseCache]() {
@@ -151302,7 +151612,7 @@ var Response22 = class _Response {
151302
151612
  constructor(body, init) {
151303
151613
  let headers;
151304
151614
  this.#body = body;
151305
- if (init instanceof _Response) {
151615
+ if (init instanceof Response$12) {
151306
151616
  const cachedGlobalResponse = init[responseCache];
151307
151617
  if (cachedGlobalResponse) {
151308
151618
  this.#init = cachedGlobalResponse;
@@ -151312,19 +151622,20 @@ var Response22 = class _Response {
151312
151622
  this.#init = init.#init;
151313
151623
  headers = new Headers(init.#init.headers);
151314
151624
  }
151315
- } else {
151625
+ } else
151316
151626
  this.#init = init;
151317
- }
151318
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
151319
- this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
151320
- }
151627
+ if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array)
151628
+ this[cacheKey] = [
151629
+ init?.status || 200,
151630
+ body ?? null,
151631
+ headers || init?.headers
151632
+ ];
151321
151633
  }
151322
151634
  get headers() {
151323
151635
  const cache = this[cacheKey];
151324
151636
  if (cache) {
151325
- if (!(cache[2] instanceof Headers)) {
151326
- cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
151327
- }
151637
+ if (!(cache[2] instanceof Headers))
151638
+ cache[2] = new Headers(cache[2] || (cache[1] === null ? undefined : { "content-type": defaultContentType }));
151328
151639
  return cache[2];
151329
151640
  }
151330
151641
  return this[getResponseCache]().headers;
@@ -151337,33 +151648,93 @@ var Response22 = class _Response {
151337
151648
  return status >= 200 && status < 300;
151338
151649
  }
151339
151650
  };
151340
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
151341
- Object.defineProperty(Response22.prototype, k, {
151342
- get() {
151343
- return this[getResponseCache]()[k];
151344
- }
151345
- });
151651
+ [
151652
+ "body",
151653
+ "bodyUsed",
151654
+ "redirected",
151655
+ "statusText",
151656
+ "trailers",
151657
+ "type",
151658
+ "url"
151659
+ ].forEach((k) => {
151660
+ Object.defineProperty(Response$1.prototype, k, { get() {
151661
+ return this[getResponseCache]()[k];
151662
+ } });
151346
151663
  });
151347
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
151348
- Object.defineProperty(Response22.prototype, k, {
151349
- value: function() {
151350
- return this[getResponseCache]()[k]();
151351
- }
151352
- });
151664
+ [
151665
+ "arrayBuffer",
151666
+ "blob",
151667
+ "clone",
151668
+ "formData",
151669
+ "json",
151670
+ "text"
151671
+ ].forEach((k) => {
151672
+ Object.defineProperty(Response$1.prototype, k, { value: function() {
151673
+ return this[getResponseCache]()[k]();
151674
+ } });
151353
151675
  });
151354
- Object.defineProperty(Response22.prototype, Symbol.for("nodejs.util.inspect.custom"), {
151355
- value: function(depth, options, inspectFn) {
151356
- const props = {
151357
- status: this.status,
151358
- headers: this.headers,
151359
- ok: this.ok,
151360
- nativeResponse: this[responseCache]
151361
- };
151362
- return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
151363
- }
151676
+ Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
151677
+ return `Response (lightweight) ${inspectFn({
151678
+ status: this.status,
151679
+ headers: this.headers,
151680
+ ok: this.ok,
151681
+ nativeResponse: this[responseCache]
151682
+ }, {
151683
+ ...options,
151684
+ depth: depth == null ? null : depth - 1
151685
+ })}`;
151686
+ } });
151687
+ Object.setPrototypeOf(Response$1, GlobalResponse);
151688
+ Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
151689
+ var validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
151690
+ var parseRedirectUrl = (url2) => {
151691
+ if (url2 instanceof URL)
151692
+ return url2.href;
151693
+ if (validRedirectUrl.test(url2))
151694
+ return url2;
151695
+ return new URL(url2).href;
151696
+ };
151697
+ var validRedirectStatuses = new Set([
151698
+ 301,
151699
+ 302,
151700
+ 303,
151701
+ 307,
151702
+ 308
151703
+ ]);
151704
+ Object.defineProperty(Response$1, "redirect", {
151705
+ value: function redirect(url2, status = 302) {
151706
+ if (!validRedirectStatuses.has(status))
151707
+ throw new RangeError("Invalid status code");
151708
+ return new Response$1(null, {
151709
+ status,
151710
+ headers: { location: parseRedirectUrl(url2) }
151711
+ });
151712
+ },
151713
+ writable: true,
151714
+ configurable: true
151715
+ });
151716
+ Object.defineProperty(Response$1, "json", {
151717
+ value: function json2(data, init) {
151718
+ const body = JSON.stringify(data);
151719
+ if (body === undefined)
151720
+ throw new TypeError("The data is not JSON serializable");
151721
+ const initHeaders = init?.headers;
151722
+ let headers;
151723
+ if (initHeaders) {
151724
+ headers = new Headers(initHeaders);
151725
+ if (!headers.has("content-type"))
151726
+ headers.set("content-type", "application/json");
151727
+ } else
151728
+ headers = { "content-type": "application/json" };
151729
+ return new Response$1(body, {
151730
+ status: init?.status ?? 200,
151731
+ statusText: init?.statusText,
151732
+ headers
151733
+ });
151734
+ },
151735
+ writable: true,
151736
+ configurable: true
151364
151737
  });
151365
- Object.setPrototypeOf(Response22, GlobalResponse);
151366
- Object.setPrototypeOf(Response22.prototype, GlobalResponse.prototype);
151367
151738
  async function readWithoutBlocking(readPromise) {
151368
151739
  return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(undefined))]);
151369
151740
  }
@@ -151379,71 +151750,64 @@ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromi
151379
151750
  writable.off("error", cancel);
151380
151751
  });
151381
151752
  function handleStreamError(error48) {
151382
- if (error48) {
151753
+ if (error48)
151383
151754
  writable.destroy(error48);
151384
- }
151385
151755
  }
151386
151756
  function onDrain() {
151387
151757
  reader.read().then(flow, handleStreamError);
151388
151758
  }
151389
151759
  function flow({ done, value }) {
151390
151760
  try {
151391
- if (done) {
151761
+ if (done)
151392
151762
  writable.end();
151393
- } else if (!writable.write(value)) {
151763
+ else if (!writable.write(value))
151394
151764
  writable.once("drain", onDrain);
151395
- } else {
151765
+ else
151396
151766
  return reader.read().then(flow, handleStreamError);
151397
- }
151398
151767
  } catch (e2) {
151399
151768
  handleStreamError(e2);
151400
151769
  }
151401
151770
  }
151402
151771
  }
151403
151772
  function writeFromReadableStream(stream2, writable) {
151404
- if (stream2.locked) {
151773
+ if (stream2.locked)
151405
151774
  throw new TypeError("ReadableStream is locked.");
151406
- } else if (writable.destroyed) {
151775
+ else if (writable.destroyed)
151407
151776
  return;
151408
- }
151409
151777
  return writeFromReadableStreamDefaultReader(stream2.getReader(), writable);
151410
151778
  }
151411
- var buildOutgoingHttpHeaders = (headers) => {
151779
+ var buildOutgoingHttpHeaders = (headers, defaultContentType2) => {
151412
151780
  const res = {};
151413
- if (!(headers instanceof Headers)) {
151781
+ if (!(headers instanceof Headers))
151414
151782
  headers = new Headers(headers ?? undefined);
151415
- }
151416
- const cookies = [];
151417
- for (const [k, v] of headers) {
151418
- if (k === "set-cookie") {
151419
- cookies.push(v);
151420
- } else {
151783
+ if (headers.has("set-cookie")) {
151784
+ const cookies = [];
151785
+ for (const [k, v] of headers)
151786
+ if (k === "set-cookie")
151787
+ cookies.push(v);
151788
+ else
151789
+ res[k] = v;
151790
+ if (cookies.length > 0)
151791
+ res["set-cookie"] = cookies;
151792
+ } else
151793
+ for (const [k, v] of headers)
151421
151794
  res[k] = v;
151422
- }
151423
- }
151424
- if (cookies.length > 0) {
151425
- res["set-cookie"] = cookies;
151426
- }
151427
- res["content-type"] ??= "text/plain; charset=UTF-8";
151795
+ if (defaultContentType2)
151796
+ res["content-type"] ??= defaultContentType2;
151428
151797
  return res;
151429
151798
  };
151430
- var X_ALREADY_SENT = "x-hono-already-sent";
151431
- if (typeof global.crypto === "undefined") {
151432
- global.crypto = crypto3;
151433
- }
151434
151799
  var outgoingEnded = Symbol("outgoingEnded");
151435
151800
  var incomingDraining = Symbol("incomingDraining");
151436
151801
  var DRAIN_TIMEOUT_MS = 500;
151437
151802
  var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
151438
151803
  var drainIncoming = (incoming) => {
151439
151804
  const incomingWithDrainState = incoming;
151440
- if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
151805
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining])
151441
151806
  return;
151442
- }
151443
151807
  incomingWithDrainState[incomingDraining] = true;
151444
- if (incoming instanceof Http2ServerRequest2) {
151808
+ if (incoming instanceof Http2ServerRequest) {
151445
151809
  try {
151446
- incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
151810
+ incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
151447
151811
  } catch {}
151448
151812
  return;
151449
151813
  }
@@ -151457,82 +151821,120 @@ var drainIncoming = (incoming) => {
151457
151821
  const forceClose = () => {
151458
151822
  cleanup();
151459
151823
  const socket = incoming.socket;
151460
- if (socket && !socket.destroyed) {
151824
+ if (socket && !socket.destroyed)
151461
151825
  socket.destroySoon();
151462
- }
151463
151826
  };
151464
151827
  const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
151465
151828
  timer.unref?.();
151466
151829
  const onData = (chunk) => {
151467
151830
  bytesRead += chunk.length;
151468
- if (bytesRead > MAX_DRAIN_BYTES) {
151831
+ if (bytesRead > MAX_DRAIN_BYTES)
151469
151832
  forceClose();
151470
- }
151471
151833
  };
151472
151834
  incoming.on("data", onData);
151473
151835
  incoming.on("end", cleanup);
151474
151836
  incoming.on("error", cleanup);
151475
151837
  incoming.resume();
151476
151838
  };
151477
- var handleRequestError = () => new Response(null, {
151478
- status: 400
151479
- });
151480
- var handleFetchError = (e2) => new Response(null, {
151481
- status: e2 instanceof Error && (e2.name === "TimeoutError" || e2.constructor.name === "TimeoutError") ? 504 : 500
151482
- });
151839
+ var makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
151840
+ if (incoming.errored)
151841
+ req[abortRequest](incoming.errored.toString());
151842
+ else if (!outgoing.writableFinished)
151843
+ req[abortRequest]("Client connection prematurely closed.");
151844
+ if (needsBodyCleanup && !incoming.readableEnded)
151845
+ setTimeout(() => {
151846
+ if (!incoming.readableEnded)
151847
+ setTimeout(() => {
151848
+ drainIncoming(incoming);
151849
+ });
151850
+ });
151851
+ };
151852
+ var isImmediateCacheableResponse = (res) => {
151853
+ if (!(cacheKey in res))
151854
+ return false;
151855
+ const body = res[cacheKey][1];
151856
+ return body === null || typeof body === "string" || body instanceof Uint8Array;
151857
+ };
151858
+ var handleRequestError = () => new Response(null, { status: 400 });
151859
+ var handleFetchError = (e2) => new Response(null, { status: e2 instanceof Error && (e2.name === "TimeoutError" || e2.constructor.name === "TimeoutError") ? 504 : 500 });
151483
151860
  var handleResponseError = (e2, outgoing) => {
151484
151861
  const err = e2 instanceof Error ? e2 : new Error("unknown error", { cause: e2 });
151485
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
151862
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE")
151486
151863
  console.info("The user aborted a request.");
151487
- } else {
151864
+ else {
151488
151865
  console.error(e2);
151489
- if (!outgoing.headersSent) {
151866
+ if (!outgoing.headersSent)
151490
151867
  outgoing.writeHead(500, { "Content-Type": "text/plain" });
151491
- }
151492
151868
  outgoing.end(`Error: ${err.message}`);
151493
151869
  outgoing.destroy(err);
151494
151870
  }
151495
151871
  };
151496
151872
  var flushHeaders = (outgoing) => {
151497
- if ("flushHeaders" in outgoing && outgoing.writable) {
151873
+ if ("flushHeaders" in outgoing && outgoing.writable)
151498
151874
  outgoing.flushHeaders();
151499
- }
151500
151875
  };
151501
151876
  var responseViaCache = async (res, outgoing) => {
151502
151877
  let [status, body, header] = res[cacheKey];
151503
- let hasContentLength = false;
151504
151878
  if (!header) {
151505
- header = { "content-type": "text/plain; charset=UTF-8" };
151506
- } else if (header instanceof Headers) {
151879
+ if (body === null) {
151880
+ outgoing.writeHead(status);
151881
+ outgoing.end();
151882
+ } else if (typeof body === "string") {
151883
+ outgoing.writeHead(status, {
151884
+ "Content-Type": defaultContentType,
151885
+ "Content-Length": Buffer.byteLength(body)
151886
+ });
151887
+ outgoing.end(body);
151888
+ } else if (body instanceof Uint8Array) {
151889
+ outgoing.writeHead(status, {
151890
+ "Content-Type": defaultContentType,
151891
+ "Content-Length": body.byteLength
151892
+ });
151893
+ outgoing.end(body);
151894
+ } else if (body instanceof Blob) {
151895
+ outgoing.writeHead(status, {
151896
+ "Content-Type": defaultContentType,
151897
+ "Content-Length": body.size
151898
+ });
151899
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
151900
+ } else {
151901
+ outgoing.writeHead(status, { "Content-Type": defaultContentType });
151902
+ flushHeaders(outgoing);
151903
+ await writeFromReadableStream(body, outgoing)?.catch((e2) => handleResponseError(e2, outgoing));
151904
+ }
151905
+ outgoing[outgoingEnded]?.();
151906
+ return;
151907
+ }
151908
+ let hasContentLength = false;
151909
+ if (header instanceof Headers) {
151507
151910
  hasContentLength = header.has("content-length");
151508
- header = buildOutgoingHttpHeaders(header);
151911
+ header = buildOutgoingHttpHeaders(header, body === null ? undefined : defaultContentType);
151509
151912
  } else if (Array.isArray(header)) {
151510
151913
  const headerObj = new Headers(header);
151511
151914
  hasContentLength = headerObj.has("content-length");
151512
- header = buildOutgoingHttpHeaders(headerObj);
151513
- } else {
151514
- for (const key in header) {
151915
+ header = buildOutgoingHttpHeaders(headerObj, body === null ? undefined : defaultContentType);
151916
+ } else
151917
+ for (const key in header)
151515
151918
  if (key.length === 14 && key.toLowerCase() === "content-length") {
151516
151919
  hasContentLength = true;
151517
151920
  break;
151518
151921
  }
151519
- }
151520
- }
151521
151922
  if (!hasContentLength) {
151522
- if (typeof body === "string") {
151923
+ if (typeof body === "string")
151523
151924
  header["Content-Length"] = Buffer.byteLength(body);
151524
- } else if (body instanceof Uint8Array) {
151925
+ else if (body instanceof Uint8Array)
151525
151926
  header["Content-Length"] = body.byteLength;
151526
- } else if (body instanceof Blob) {
151927
+ else if (body instanceof Blob)
151527
151928
  header["Content-Length"] = body.size;
151528
- }
151529
151929
  }
151530
151930
  outgoing.writeHead(status, header);
151531
- if (typeof body === "string" || body instanceof Uint8Array) {
151931
+ if (body == null)
151932
+ outgoing.end();
151933
+ else if (typeof body === "string" || body instanceof Uint8Array)
151532
151934
  outgoing.end(body);
151533
- } else if (body instanceof Blob) {
151935
+ else if (body instanceof Blob)
151534
151936
  outgoing.end(new Uint8Array(await body.arrayBuffer()));
151535
- } else {
151937
+ else {
151536
151938
  flushHeaders(outgoing);
151537
151939
  await writeFromReadableStream(body, outgoing)?.catch((e2) => handleResponseError(e2, outgoing));
151538
151940
  }
@@ -151540,25 +151942,21 @@ var responseViaCache = async (res, outgoing) => {
151540
151942
  };
151541
151943
  var isPromise = (res) => typeof res.then === "function";
151542
151944
  var responseViaResponseObject = async (res, outgoing, options = {}) => {
151543
- if (isPromise(res)) {
151544
- if (options.errorHandler) {
151945
+ if (isPromise(res))
151946
+ if (options.errorHandler)
151545
151947
  try {
151546
151948
  res = await res;
151547
151949
  } catch (err) {
151548
151950
  const errRes = await options.errorHandler(err);
151549
- if (!errRes) {
151951
+ if (!errRes)
151550
151952
  return;
151551
- }
151552
151953
  res = errRes;
151553
151954
  }
151554
- } else {
151955
+ else
151555
151956
  res = await res.catch(handleFetchError);
151556
- }
151557
- }
151558
- if (cacheKey in res) {
151957
+ if (cacheKey in res)
151559
151958
  return responseViaCache(res, outgoing);
151560
- }
151561
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
151959
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? undefined : defaultContentType);
151562
151960
  if (res.body) {
151563
151961
  const reader = res.body.getReader();
151564
151962
  const values = [];
@@ -151581,28 +151979,25 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
151581
151979
  break;
151582
151980
  }
151583
151981
  currentReadPromise = undefined;
151584
- if (chunk.value) {
151982
+ if (chunk.value)
151585
151983
  values.push(chunk.value);
151586
- }
151587
151984
  if (chunk.done) {
151588
151985
  done = true;
151589
151986
  break;
151590
151987
  }
151591
151988
  }
151592
- if (done && !("content-length" in resHeaderRecord)) {
151989
+ if (done && !("content-length" in resHeaderRecord))
151593
151990
  resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
151594
- }
151595
151991
  }
151596
151992
  outgoing.writeHead(res.status, resHeaderRecord);
151597
151993
  values.forEach((value) => {
151598
151994
  outgoing.write(value);
151599
151995
  });
151600
- if (done) {
151996
+ if (done)
151601
151997
  outgoing.end();
151602
- } else {
151603
- if (values.length === 0) {
151998
+ else {
151999
+ if (values.length === 0)
151604
152000
  flushHeaders(outgoing);
151605
- }
151606
152001
  await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
151607
152002
  }
151608
152003
  } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
@@ -151613,81 +152008,63 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
151613
152008
  };
151614
152009
  var getRequestListener = (fetchCallback, options = {}) => {
151615
152010
  const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
151616
- if (options.overrideGlobalObjects !== false && global.Request !== Request3) {
151617
- Object.defineProperty(global, "Request", {
151618
- value: Request3
151619
- });
151620
- Object.defineProperty(global, "Response", {
151621
- value: Response22
151622
- });
152011
+ if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
152012
+ Object.defineProperty(global, "Request", { value: Request$1 });
152013
+ Object.defineProperty(global, "Response", { value: Response$1 });
151623
152014
  }
151624
152015
  return async (incoming, outgoing) => {
151625
152016
  let res, req;
152017
+ let needsBodyCleanup = false;
152018
+ let closeHandlerAttached = false;
152019
+ const ensureCloseHandler = () => {
152020
+ if (!req || closeHandlerAttached)
152021
+ return;
152022
+ closeHandlerAttached = true;
152023
+ outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
152024
+ };
151626
152025
  try {
151627
152026
  req = newRequest(incoming, options.hostname);
151628
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
151629
- if (!incomingEnded) {
152027
+ needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
152028
+ if (needsBodyCleanup) {
151630
152029
  incoming[wrapBodyStream] = true;
151631
- incoming.on("end", () => {
151632
- incomingEnded = true;
151633
- });
151634
- if (incoming instanceof Http2ServerRequest2) {
152030
+ if (incoming instanceof Http2ServerRequest)
151635
152031
  outgoing[outgoingEnded] = () => {
151636
- if (!incomingEnded) {
152032
+ if (!incoming.readableEnded)
151637
152033
  setTimeout(() => {
151638
- if (!incomingEnded) {
152034
+ if (!incoming.readableEnded)
151639
152035
  setTimeout(() => {
151640
- drainIncoming(incoming);
152036
+ incoming.destroy();
152037
+ outgoing.destroy();
151641
152038
  });
151642
- }
151643
152039
  });
151644
- }
151645
152040
  };
151646
- }
151647
- outgoing.on("finish", () => {
151648
- if (!incomingEnded) {
151649
- drainIncoming(incoming);
151650
- }
151651
- });
151652
152041
  }
151653
- outgoing.on("close", () => {
151654
- const abortController = req[abortControllerKey];
151655
- if (abortController) {
151656
- if (incoming.errored) {
151657
- req[abortControllerKey].abort(incoming.errored.toString());
151658
- } else if (!outgoing.writableFinished) {
151659
- req[abortControllerKey].abort("Client connection prematurely closed.");
151660
- }
151661
- }
151662
- if (!incomingEnded) {
151663
- setTimeout(() => {
151664
- if (!incomingEnded) {
151665
- setTimeout(() => {
151666
- drainIncoming(incoming);
151667
- });
151668
- }
151669
- });
151670
- }
152042
+ res = fetchCallback(req, {
152043
+ incoming,
152044
+ outgoing
151671
152045
  });
151672
- res = fetchCallback(req, { incoming, outgoing });
151673
- if (cacheKey in res) {
152046
+ if (!isPromise(res) && isImmediateCacheableResponse(res)) {
152047
+ if (needsBodyCleanup && !incoming.readableEnded)
152048
+ outgoing.once("finish", () => {
152049
+ if (!incoming.readableEnded)
152050
+ drainIncoming(incoming);
152051
+ });
151674
152052
  return responseViaCache(res, outgoing);
151675
152053
  }
152054
+ ensureCloseHandler();
151676
152055
  } catch (e2) {
151677
- if (!res) {
152056
+ if (!res)
151678
152057
  if (options.errorHandler) {
152058
+ ensureCloseHandler();
151679
152059
  res = await options.errorHandler(req ? e2 : toRequestError(e2));
151680
- if (!res) {
152060
+ if (!res)
151681
152061
  return;
151682
- }
151683
- } else if (!req) {
152062
+ } else if (!req)
151684
152063
  res = handleRequestError();
151685
- } else {
152064
+ else
151686
152065
  res = handleFetchError(e2);
151687
- }
151688
- } else {
152066
+ else
151689
152067
  return handleResponseError(e2, outgoing);
151690
- }
151691
152068
  }
151692
152069
  try {
151693
152070
  return await responseViaResponseObject(res, outgoing, options);
@@ -151696,6 +152073,167 @@ var getRequestListener = (fetchCallback, options = {}) => {
151696
152073
  }
151697
152074
  };
151698
152075
  };
152076
+ var CloseEvent2 = globalThis.CloseEvent ?? class extends Event {
152077
+ #eventInitDict;
152078
+ constructor(type, eventInitDict = {}) {
152079
+ super(type, eventInitDict);
152080
+ this.#eventInitDict = eventInitDict;
152081
+ }
152082
+ get wasClean() {
152083
+ return this.#eventInitDict.wasClean ?? false;
152084
+ }
152085
+ get code() {
152086
+ return this.#eventInitDict.code ?? 0;
152087
+ }
152088
+ get reason() {
152089
+ return this.#eventInitDict.reason ?? "";
152090
+ }
152091
+ };
152092
+ var generateConnectionSymbol = () => Symbol("connection");
152093
+ var CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
152094
+ var WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
152095
+ var rejectUpgradeRequest = (socket, status) => {
152096
+ socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r
152097
+ Connection: close\r
152098
+ Content-Length: 0\r
152099
+ \r
152100
+ `);
152101
+ };
152102
+ var createUpgradeRequest = (request) => {
152103
+ const protocol = request.socket.encrypted ? "https" : "http";
152104
+ const url2 = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
152105
+ const headers = new Headers;
152106
+ for (const key in request.headers) {
152107
+ const value = request.headers[key];
152108
+ if (!value)
152109
+ continue;
152110
+ headers.append(key, Array.isArray(value) ? value[0] : value);
152111
+ }
152112
+ return new Request(url2, { headers });
152113
+ };
152114
+ var setupWebSocket = (options) => {
152115
+ const { server, fetchCallback, wss } = options;
152116
+ const waiterMap = /* @__PURE__ */ new Map;
152117
+ wss.on("connection", (ws, request) => {
152118
+ const waiter = waiterMap.get(request);
152119
+ if (waiter) {
152120
+ waiter.resolve(ws);
152121
+ waiterMap.delete(request);
152122
+ }
152123
+ });
152124
+ const waitForWebSocket = (request, connectionSymbol) => {
152125
+ return new Promise((resolve2) => {
152126
+ waiterMap.set(request, {
152127
+ resolve: resolve2,
152128
+ connectionSymbol
152129
+ });
152130
+ });
152131
+ };
152132
+ server.on("upgrade", async (request, socket, head2) => {
152133
+ if (request.headers.upgrade?.toLowerCase() !== "websocket")
152134
+ return;
152135
+ const env = {
152136
+ incoming: request,
152137
+ outgoing: undefined,
152138
+ wss,
152139
+ [WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
152140
+ };
152141
+ let status = 400;
152142
+ try {
152143
+ const response = await fetchCallback(createUpgradeRequest(request), env);
152144
+ if (response instanceof Response)
152145
+ status = response.status;
152146
+ } catch {
152147
+ if (server.listenerCount("upgrade") === 1)
152148
+ rejectUpgradeRequest(socket, 500);
152149
+ return;
152150
+ }
152151
+ const waiter = waiterMap.get(request);
152152
+ if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
152153
+ waiterMap.delete(request);
152154
+ if (server.listenerCount("upgrade") === 1)
152155
+ rejectUpgradeRequest(socket, status);
152156
+ return;
152157
+ }
152158
+ wss.handleUpgrade(request, socket, head2, (ws) => {
152159
+ wss.emit("connection", ws, request);
152160
+ });
152161
+ });
152162
+ server.on("close", () => {
152163
+ wss.close();
152164
+ });
152165
+ };
152166
+ var upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
152167
+ if (c.req.header("upgrade")?.toLowerCase() !== "websocket")
152168
+ return;
152169
+ const env = c.env;
152170
+ const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
152171
+ if (!waitForWebSocket || !env.incoming)
152172
+ return new Response(null, { status: 500 });
152173
+ const connectionSymbol = generateConnectionSymbol();
152174
+ env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
152175
+ (async () => {
152176
+ const ws = await waitForWebSocket(env.incoming, connectionSymbol);
152177
+ const messagesReceivedInStarting = [];
152178
+ const bufferMessage = (data, isBinary) => {
152179
+ messagesReceivedInStarting.push([data, isBinary]);
152180
+ };
152181
+ ws.on("message", bufferMessage);
152182
+ const ctx = {
152183
+ binaryType: "arraybuffer",
152184
+ close(code, reason) {
152185
+ ws.close(code, reason);
152186
+ },
152187
+ protocol: ws.protocol,
152188
+ raw: ws,
152189
+ get readyState() {
152190
+ return ws.readyState;
152191
+ },
152192
+ send(source, opts) {
152193
+ ws.send(source, { compress: opts?.compress });
152194
+ },
152195
+ url: new URL(c.req.url)
152196
+ };
152197
+ try {
152198
+ events?.onOpen?.(new Event("open"), ctx);
152199
+ } catch (e2) {
152200
+ (options?.onError ?? console.error)(e2);
152201
+ }
152202
+ const handleMessage = (data, isBinary) => {
152203
+ const datas = Array.isArray(data) ? data : [data];
152204
+ for (const data2 of datas)
152205
+ try {
152206
+ events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data2 instanceof ArrayBuffer ? data2 : data2.buffer.slice(data2.byteOffset, data2.byteOffset + data2.byteLength) : data2.toString("utf-8") }), ctx);
152207
+ } catch (e2) {
152208
+ (options?.onError ?? console.error)(e2);
152209
+ }
152210
+ };
152211
+ ws.off("message", bufferMessage);
152212
+ for (const message of messagesReceivedInStarting)
152213
+ handleMessage(...message);
152214
+ ws.on("message", (data, isBinary) => {
152215
+ handleMessage(data, isBinary);
152216
+ });
152217
+ ws.on("close", (code, reason) => {
152218
+ try {
152219
+ events?.onClose?.(new CloseEvent2("close", {
152220
+ code,
152221
+ reason: reason.toString()
152222
+ }), ctx);
152223
+ } catch (e2) {
152224
+ (options?.onError ?? console.error)(e2);
152225
+ }
152226
+ });
152227
+ ws.on("error", (error48) => {
152228
+ try {
152229
+ events?.onError?.(new ErrorEvent("error", { error: error48 }), ctx);
152230
+ } catch (e2) {
152231
+ (options?.onError ?? console.error)(e2);
152232
+ }
152233
+ });
152234
+ })();
152235
+ return new Response;
152236
+ });
151699
152237
  var createAdaptorServer = (options) => {
151700
152238
  const fetchCallback = options.fetch;
151701
152239
  const requestListener = getRequestListener(fetchCallback, {
@@ -151703,8 +152241,16 @@ var createAdaptorServer = (options) => {
151703
152241
  overrideGlobalObjects: options.overrideGlobalObjects,
151704
152242
  autoCleanupIncoming: options.autoCleanupIncoming
151705
152243
  });
151706
- const createServer = options.createServer || createServerHTTP;
151707
- const server = createServer(options.serverOptions || {}, requestListener);
152244
+ const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
152245
+ if (options.websocket && options.websocket.server) {
152246
+ if (options.websocket.server.options.noServer !== true)
152247
+ throw new Error("WebSocket server must be created with { noServer: true } option");
152248
+ setupWebSocket({
152249
+ server,
152250
+ fetchCallback,
152251
+ wss: options.websocket.server
152252
+ });
152253
+ }
151708
152254
  return server;
151709
152255
  };
151710
152256
  var serve = (options, listeningListener) => {
@@ -153162,11 +153708,11 @@ class RemoteJWKSet {
153162
153708
  if (this.#pendingFetch && isCloudflareWorkers()) {
153163
153709
  this.#pendingFetch = undefined;
153164
153710
  }
153165
- this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json2) => {
153166
- this.#local = createLocalJWKSet(json2);
153711
+ this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch).then((json3) => {
153712
+ this.#local = createLocalJWKSet(json3);
153167
153713
  if (this.#cache) {
153168
153714
  this.#cache.uat = Date.now();
153169
- this.#cache.jwks = json2;
153715
+ this.#cache.jwks = json3;
153170
153716
  }
153171
153717
  this.#jwksTimestamp = Date.now();
153172
153718
  this.#pendingFetch = undefined;
@@ -154143,8 +154689,8 @@ class StdioServerTransport {
154143
154689
  }
154144
154690
  send(message2) {
154145
154691
  return new Promise((resolve2) => {
154146
- const json2 = serializeMessage(message2);
154147
- if (this._stdout.write(json2)) {
154692
+ const json3 = serializeMessage(message2);
154693
+ if (this._stdout.write(json3)) {
154148
154694
  resolve2();
154149
154695
  } else {
154150
154696
  this._stdout.once("drain", resolve2);