@casys/mcp-erpnext 3.1.0-beta.9 → 3.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mcp-erpnext.mjs CHANGED
@@ -396,7 +396,7 @@ var require_codegen2 = __commonJS({
396
396
  AND: new code_1._Code("&&"),
397
397
  ADD: new code_1._Code("+")
398
398
  };
399
- var Node3 = class {
399
+ var Node5 = class {
400
400
  optimizeNodes() {
401
401
  return this;
402
402
  }
@@ -404,7 +404,7 @@ var require_codegen2 = __commonJS({
404
404
  return this;
405
405
  }
406
406
  };
407
- var Def = class extends Node3 {
407
+ var Def = class extends Node5 {
408
408
  constructor(varKind, name, rhs) {
409
409
  super();
410
410
  this.varKind = varKind;
@@ -427,7 +427,7 @@ var require_codegen2 = __commonJS({
427
427
  return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
428
428
  }
429
429
  };
430
- var Assign = class extends Node3 {
430
+ var Assign = class extends Node5 {
431
431
  constructor(lhs, rhs, sideEffects) {
432
432
  super();
433
433
  this.lhs = lhs;
@@ -457,7 +457,7 @@ var require_codegen2 = __commonJS({
457
457
  return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
458
458
  }
459
459
  };
460
- var Label = class extends Node3 {
460
+ var Label = class extends Node5 {
461
461
  constructor(label) {
462
462
  super();
463
463
  this.label = label;
@@ -467,7 +467,7 @@ var require_codegen2 = __commonJS({
467
467
  return `${this.label}:` + _n;
468
468
  }
469
469
  };
470
- var Break = class extends Node3 {
470
+ var Break = class extends Node5 {
471
471
  constructor(label) {
472
472
  super();
473
473
  this.label = label;
@@ -478,7 +478,7 @@ var require_codegen2 = __commonJS({
478
478
  return `break${label};` + _n;
479
479
  }
480
480
  };
481
- var Throw = class extends Node3 {
481
+ var Throw = class extends Node5 {
482
482
  constructor(error2) {
483
483
  super();
484
484
  this.error = error2;
@@ -490,7 +490,7 @@ var require_codegen2 = __commonJS({
490
490
  return this.error.names;
491
491
  }
492
492
  };
493
- var AnyCode = class extends Node3 {
493
+ var AnyCode = class extends Node5 {
494
494
  constructor(code) {
495
495
  super();
496
496
  this.code = code;
@@ -509,7 +509,7 @@ var require_codegen2 = __commonJS({
509
509
  return this.code instanceof code_1._CodeOrName ? this.code.names : {};
510
510
  }
511
511
  };
512
- var ParentNode = class extends Node3 {
512
+ var ParentNode = class extends Node5 {
513
513
  constructor(nodes = []) {
514
514
  super();
515
515
  this.nodes = nodes;
@@ -4154,13 +4154,14 @@ var require_fast_uri2 = __commonJS({
4154
4154
  if (!malformedIPLiteral) {
4155
4155
  malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP);
4156
4156
  }
4157
- if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4158
- if (uri.indexOf("%") !== -1) {
4159
- if (parsed.host !== void 0 && !malformedIPLiteral) {
4160
- const host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
4161
- parsed.host = reescapeHostDelimiters(host, isIP);
4162
- }
4157
+ if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
4158
+ let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true);
4159
+ if (!isIP) {
4160
+ host = normalizePercentEncoding(host.toLowerCase());
4163
4161
  }
4162
+ parsed.host = reescapeHostDelimiters(host, isIP);
4163
+ }
4164
+ if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4164
4165
  if (parsed.path) {
4165
4166
  parsed.path = normalizePathEncoding(parsed.path);
4166
4167
  }
@@ -8362,9 +8363,9 @@ var require_Alias = __commonJS({
8362
8363
  var anchors = require_anchors();
8363
8364
  var visit = require_visit();
8364
8365
  var identity = require_identity();
8365
- var Node3 = require_Node();
8366
+ var Node5 = require_Node();
8366
8367
  var toJS = require_toJS();
8367
- var Alias = class extends Node3.NodeBase {
8368
+ var Alias = class extends Node5.NodeBase {
8368
8369
  constructor(source) {
8369
8370
  super(identity.ALIAS);
8370
8371
  this.source = source;
@@ -8478,10 +8479,10 @@ var require_Scalar = __commonJS({
8478
8479
  "node_modules/yaml/dist/nodes/Scalar.js"(exports) {
8479
8480
  "use strict";
8480
8481
  var identity = require_identity();
8481
- var Node3 = require_Node();
8482
+ var Node5 = require_Node();
8482
8483
  var toJS = require_toJS();
8483
8484
  var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
8484
- var Scalar = class extends Node3.NodeBase {
8485
+ var Scalar = class extends Node5.NodeBase {
8485
8486
  constructor(value) {
8486
8487
  super(identity.SCALAR);
8487
8488
  this.value = value;
@@ -8584,7 +8585,7 @@ var require_Collection = __commonJS({
8584
8585
  "use strict";
8585
8586
  var createNode = require_createNode();
8586
8587
  var identity = require_identity();
8587
- var Node3 = require_Node();
8588
+ var Node5 = require_Node();
8588
8589
  function collectionFromPath(schema, path, value) {
8589
8590
  let v = value;
8590
8591
  for (let i = path.length - 1; i >= 0; --i) {
@@ -8608,7 +8609,7 @@ var require_Collection = __commonJS({
8608
8609
  });
8609
8610
  }
8610
8611
  var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
8611
- var Collection = class extends Node3.NodeBase {
8612
+ var Collection = class extends Node5.NodeBase {
8612
8613
  constructor(type, schema) {
8613
8614
  super(type);
8614
8615
  Object.defineProperty(this, "schema", {
@@ -15114,6 +15115,7 @@ __export(runtime_deno_exports2, {
15114
15115
  env: () => env4,
15115
15116
  exit: () => exit,
15116
15117
  getArgs: () => getArgs,
15118
+ netPermission: () => netPermission,
15117
15119
  onSignal: () => onSignal,
15118
15120
  readDirSync: () => readDirSync,
15119
15121
  readTextFile: () => readTextFile4,
@@ -15151,6 +15153,13 @@ function exit(code) {
15151
15153
  function onSignal(signal, handler) {
15152
15154
  Deno.addSignalListener(signal, handler);
15153
15155
  }
15156
+ function netPermission(host) {
15157
+ try {
15158
+ return Deno.permissions.querySync({ name: "net", host }).state;
15159
+ } catch {
15160
+ return "granted";
15161
+ }
15162
+ }
15154
15163
  var init_runtime_deno2 = __esm({
15155
15164
  "src/runtime.deno.ts"() {
15156
15165
  }
@@ -15162,6 +15171,7 @@ __export(runtime_node_exports2, {
15162
15171
  env: () => env5,
15163
15172
  exit: () => exit2,
15164
15173
  getArgs: () => getArgs2,
15174
+ netPermission: () => netPermission2,
15165
15175
  onSignal: () => onSignal2,
15166
15176
  readDirSync: () => readDirSync2,
15167
15177
  readTextFile: () => readTextFile5,
@@ -15201,6 +15211,9 @@ function exit2(code) {
15201
15211
  function onSignal2(signal, handler) {
15202
15212
  process.on(signal, handler);
15203
15213
  }
15214
+ function netPermission2(_host) {
15215
+ return "granted";
15216
+ }
15204
15217
  var init_runtime_node2 = __esm({
15205
15218
  "src/runtime.node.ts"() {
15206
15219
  }
@@ -15334,6 +15347,7 @@ __export(util_exports, {
15334
15347
  required: () => required,
15335
15348
  safeExtend: () => safeExtend,
15336
15349
  shallowClone: () => shallowClone,
15350
+ sizeCaps: () => sizeCaps,
15337
15351
  slugify: () => slugify,
15338
15352
  stringifyPrimitive: () => stringifyPrimitive,
15339
15353
  toZod: () => toZod,
@@ -15853,6 +15867,18 @@ function prefixIssues(path, issues) {
15853
15867
  function unwrapMessage(message2) {
15854
15868
  return typeof message2 === "string" ? message2 : message2?.message;
15855
15869
  }
15870
+ function sizeCaps(defChecks) {
15871
+ const caps = [];
15872
+ for (const ch of defChecks ?? []) {
15873
+ const d = ch._zod.def;
15874
+ if (!/_(length|size)$|_equals$/.test(d.check))
15875
+ break;
15876
+ const max = d.maximum ?? d.length ?? d.size;
15877
+ if (max >= 0)
15878
+ caps.push([max, ch]);
15879
+ }
15880
+ return caps;
15881
+ }
15856
15882
  function attachSchema(issues, start, inst) {
15857
15883
  var _a3;
15858
15884
  for (let i = start; i < issues.length; i++) {
@@ -16000,9 +16026,6 @@ function members(proto, table2) {
16000
16026
  else
16001
16027
  defineBound(proto, key, desc.value);
16002
16028
  }
16003
- for (const sym of Object.getOwnPropertySymbols(table2)) {
16004
- defineBound(proto, sym, table2[sym]);
16005
- }
16006
16029
  }
16007
16030
  function own(inst, key, value, enumerable = true) {
16008
16031
  Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });
@@ -16155,8 +16178,7 @@ function $constructor(name, initializer3, proto, params) {
16155
16178
  } finally {
16156
16179
  _zodDesc.value = void 0;
16157
16180
  }
16158
- }
16159
- if (inst._zod.traits.has(name)) {
16181
+ } else if (inst._zod.traits.has(name)) {
16160
16182
  return;
16161
16183
  }
16162
16184
  inst._zod.traits.add(name);
@@ -16919,7 +16941,7 @@ ${content.join("\n")}
16919
16941
  var version = {
16920
16942
  major: 4,
16921
16943
  minor: 6,
16922
- patch: 2
16944
+ patch: 7
16923
16945
  };
16924
16946
 
16925
16947
  // node_modules/zod/v4/core/schemas.js
@@ -17107,11 +17129,32 @@ var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
17107
17129
  });
17108
17130
  var URL_BAD_FORMAT = 1;
17109
17131
  var URL_UNPARSEABLE = 2;
17132
+ function canParseURL(input) {
17133
+ try {
17134
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function")
17135
+ return URL.canParse(input);
17136
+ new URL(input);
17137
+ return true;
17138
+ } catch {
17139
+ return false;
17140
+ }
17141
+ }
17142
+ function validateURL(trimmed, def) {
17143
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) {
17144
+ return canParseURL(trimmed) || URL_UNPARSEABLE;
17145
+ }
17146
+ return parseURLObject(trimmed, def);
17147
+ }
17110
17148
  function parseURLObject(trimmed, def) {
17111
17149
  if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) {
17112
17150
  return URL_BAD_FORMAT;
17113
17151
  }
17114
17152
  try {
17153
+ if (typeof URL !== "undefined") {
17154
+ const URLStatic = URL;
17155
+ if (typeof URLStatic.parse === "function")
17156
+ return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;
17157
+ }
17115
17158
  return new URL(trimmed);
17116
17159
  } catch {
17117
17160
  return URL_UNPARSEABLE;
@@ -17134,7 +17177,7 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
17134
17177
  inst._zod.check = (payload) => {
17135
17178
  try {
17136
17179
  const trimmed = payload.value.trim();
17137
- const url2 = parseURLObject(trimmed, def);
17180
+ const url2 = validateURL(trimmed, def);
17138
17181
  if (url2 === URL_BAD_FORMAT) {
17139
17182
  payload.issues.push({
17140
17183
  code: "invalid_format",
@@ -17156,6 +17199,10 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
17156
17199
  });
17157
17200
  return;
17158
17201
  }
17202
+ if (url2 === true) {
17203
+ payload.value = stripTabAndNewline(trimmed);
17204
+ return;
17205
+ }
17159
17206
  if (def.hostname && !urlHostnameOk(url2, def.hostname)) {
17160
17207
  payload.issues.push({
17161
17208
  code: "invalid_format",
@@ -17245,12 +17292,7 @@ var ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
17245
17292
  function isValidIPv6(value) {
17246
17293
  if (!ipv6Alphabet.test(value))
17247
17294
  return false;
17248
- try {
17249
- new URL(`http://[${value}]`);
17250
- return true;
17251
- } catch {
17252
- return false;
17253
- }
17295
+ return canParseURL(`http://[${value}]`);
17254
17296
  }
17255
17297
  var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
17256
17298
  def.pattern ?? (def.pattern = ipv6);
@@ -17521,6 +17563,29 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
17521
17563
  return payload;
17522
17564
  };
17523
17565
  });
17566
+ function capSize(inst, size) {
17567
+ const caps = sizeCaps(inst._zod.def.checks);
17568
+ if (!caps.length)
17569
+ return;
17570
+ const cap = Math.min(...caps.map((c) => c[0]));
17571
+ const parse2 = inst._zod.parse;
17572
+ inst._zod.parse = (payload, ctx) => {
17573
+ const n = size(payload.value);
17574
+ if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
17575
+ for (const [max, ch] of sizeCaps(inst._zod.def.checks)) {
17576
+ if (n > max && ch._zod.def.when(payload)) {
17577
+ const start = payload.issues.length;
17578
+ ch._zod.check(payload);
17579
+ payload.issues[start].continue = false;
17580
+ attachSchema(payload.issues, start, inst);
17581
+ return payload;
17582
+ }
17583
+ }
17584
+ }
17585
+ return parse2(payload, ctx);
17586
+ };
17587
+ }
17588
+ var arraySize = (input) => Array.isArray(input) ? input.length : -1;
17524
17589
  function handleArrayResult(result, final, index) {
17525
17590
  if (result.issues.length) {
17526
17591
  final.issues.push(...prefixIssues(index, result.issues));
@@ -17564,6 +17629,7 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
17564
17629
  }
17565
17630
  return payload;
17566
17631
  };
17632
+ capSize(inst, arraySize);
17567
17633
  });
17568
17634
  function handlePropertyResult(result, final, key, input, optin, optout) {
17569
17635
  const isPresent = key in input;
@@ -18620,7 +18686,7 @@ var $ZodCyclicError = class extends Error {
18620
18686
  var STATE = "~memo";
18621
18687
  var NO_ISSUES = [];
18622
18688
  function isRef(value) {
18623
- return value !== null && (typeof value === "object" || typeof value === "function");
18689
+ return value !== null && typeof value === "object";
18624
18690
  }
18625
18691
  function cloneIssues(issues) {
18626
18692
  return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
@@ -18669,9 +18735,6 @@ function isRecursive(inst, stack, resolve) {
18669
18735
  check(def.catchall);
18670
18736
  break;
18671
18737
  }
18672
- case "properties":
18673
- merge2(shape(def.shape, false));
18674
- break;
18675
18738
  case "array":
18676
18739
  check(def.element);
18677
18740
  break;
@@ -18927,6 +18990,7 @@ var error = () => {
18927
18990
  base64url: "base64url-encoded string",
18928
18991
  json_string: "JSON string",
18929
18992
  e164: "E.164 number",
18993
+ currency_code: "currency code",
18930
18994
  credit_card: "credit card number",
18931
18995
  iban: "IBAN",
18932
18996
  jwt: "JWT",
@@ -19060,20 +19124,18 @@ function registry() {
19060
19124
  var globalRegistry = globalThis.__zod_globalRegistry;
19061
19125
 
19062
19126
  // node_modules/zod/v4/core/api.js
19127
+ function snapshotChecks(def) {
19128
+ if (def.checks)
19129
+ def.checks = [...def.checks];
19130
+ return def;
19131
+ }
19063
19132
  // @__NO_SIDE_EFFECTS__
19064
19133
  function _string(Class2, params) {
19065
- return new Class2({
19066
- type: "string",
19067
- ...normalizeParams(params)
19068
- });
19134
+ return new Class2(snapshotChecks({ type: "string", ...normalizeParams(params) }));
19069
19135
  }
19070
19136
  // @__NO_SIDE_EFFECTS__
19071
19137
  function _coercedString(Class2, params) {
19072
- return new Class2({
19073
- type: "string",
19074
- coerce: true,
19075
- ...normalizeParams(params)
19076
- });
19138
+ return new Class2(snapshotChecks({ type: "string", coerce: true, ...normalizeParams(params) }));
19077
19139
  }
19078
19140
  // @__NO_SIDE_EFFECTS__
19079
19141
  function _email(Class2, params) {
@@ -19340,20 +19402,11 @@ function _isoDuration(Class2, params) {
19340
19402
  }
19341
19403
  // @__NO_SIDE_EFFECTS__
19342
19404
  function _number(Class2, params) {
19343
- return new Class2({
19344
- type: "number",
19345
- checks: [],
19346
- ...normalizeParams(params)
19347
- });
19405
+ return new Class2(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) }));
19348
19406
  }
19349
19407
  // @__NO_SIDE_EFFECTS__
19350
19408
  function _coercedNumber(Class2, params) {
19351
- return new Class2({
19352
- type: "number",
19353
- coerce: true,
19354
- checks: [],
19355
- ...normalizeParams(params)
19356
- });
19409
+ return new Class2(snapshotChecks({ type: "number", coerce: true, checks: [], ...normalizeParams(params) }));
19357
19410
  }
19358
19411
  // @__NO_SIDE_EFFECTS__
19359
19412
  function _int(Class2, params) {
@@ -20516,17 +20569,15 @@ var objectProcessor = (schema, ctx, _json, params) => {
20516
20569
  path: [...params.path, "properties", key]
20517
20570
  }));
20518
20571
  }
20519
- const allKeys = new Set(Object.keys(shape));
20520
- const requiredKeys = new Set([...allKeys].filter((key) => {
20572
+ const requiredKeys = [];
20573
+ for (const key of Object.keys(shape)) {
20521
20574
  const field = def.shape[key];
20522
- if (ctx.io === "input") {
20523
- return inputOptin(field) === void 0;
20524
- } else {
20525
- return field._zod.optout === void 0;
20575
+ if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) {
20576
+ requiredKeys.push(key);
20526
20577
  }
20527
- }));
20528
- if (requiredKeys.size > 0) {
20529
- json.required = Array.from(requiredKeys);
20578
+ }
20579
+ if (requiredKeys.length > 0) {
20580
+ json.required = requiredKeys;
20530
20581
  }
20531
20582
  if (def.catchall?._zod.def.type === "never") {
20532
20583
  json.additionalProperties = false;
@@ -20540,31 +20591,6 @@ var objectProcessor = (schema, ctx, _json, params) => {
20540
20591
  });
20541
20592
  }
20542
20593
  };
20543
- var propertiesProcessor = (schema, ctx, _json, params) => {
20544
- const json = _json;
20545
- const def = schema._zod.def;
20546
- if (Object.getOwnPropertySymbols(def.shape).length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) {
20547
- return;
20548
- }
20549
- if (ctx.io === "output") {
20550
- for (const key in def.shape) {
20551
- if (isTransforming(def.shape[key]) && handleUnrepresentable(schema, ctx, json, params, `z.properties() returns its input, so the output of a transforming schema at key "${key}" cannot be represented in JSON Schema`)) {
20552
- return;
20553
- }
20554
- }
20555
- }
20556
- json.type = "object";
20557
- json.properties = {};
20558
- for (const key in def.shape) {
20559
- assignProp(json.properties, key, processSchema(def.shape[key], ctx, {
20560
- ...params,
20561
- path: [...params.path, "properties", key]
20562
- }));
20563
- }
20564
- const required2 = Object.keys(def.shape).filter((key) => inputOptin(def.shape[key]) === void 0);
20565
- if (required2.length > 0)
20566
- json.required = required2;
20567
- };
20568
20594
  var unionProcessor = (schema, ctx, json, params) => {
20569
20595
  const def = schema._zod.def;
20570
20596
  const isExclusive = def.inclusive === false;
@@ -20884,7 +20910,6 @@ var allProcessors = {
20884
20910
  file: fileProcessor,
20885
20911
  success: successProcessor,
20886
20912
  custom: customProcessor,
20887
- properties: propertiesProcessor,
20888
20913
  function: functionProcessor,
20889
20914
  transform: transformProcessor,
20890
20915
  map: mapProcessor,
@@ -22105,7 +22130,7 @@ function date3(params) {
22105
22130
  return _coercedDate(ZodDate, params);
22106
22131
  }
22107
22132
 
22108
- // node_modules/@modelcontextprotocol/core/dist/auth-CUe6YdwF.mjs
22133
+ // node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs
22109
22134
  var LATEST_PROTOCOL_VERSION = "2025-11-25";
22110
22135
  var SUPPORTED_PROTOCOL_VERSIONS = [
22111
22136
  LATEST_PROTOCOL_VERSION,
@@ -22942,7 +22967,8 @@ var OAuthMetadataSchema = looseObject({
22942
22967
  introspection_endpoint_auth_signing_alg_values_supported: array(string2()).optional(),
22943
22968
  code_challenge_methods_supported: array(string2()).optional(),
22944
22969
  client_id_metadata_document_supported: boolean2().optional(),
22945
- authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0)
22970
+ authorization_response_iss_parameter_supported: boolean2().optional().catch(void 0),
22971
+ dpop_signing_alg_values_supported: array(string2()).optional()
22946
22972
  });
22947
22973
  var OpenIdProviderMetadataSchema = looseObject({
22948
22974
  issuer: string2(),
@@ -22993,7 +23019,8 @@ var OAuthTokensSchema = object({
22993
23019
  token_type: string2(),
22994
23020
  expires_in: coerce_exports.number().optional(),
22995
23021
  scope: string2().optional(),
22996
- refresh_token: string2().optional()
23022
+ refresh_token: string2().optional(),
23023
+ issuer: string2().optional().catch(void 0)
22997
23024
  }).strip();
22998
23025
  var IdJagTokenExchangeResponseSchema = object({
22999
23026
  issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"),
@@ -23031,7 +23058,8 @@ var OAuthClientInformationSchema = object({
23031
23058
  client_id: string2(),
23032
23059
  client_secret: string2().optional(),
23033
23060
  client_id_issued_at: number2().optional(),
23034
- client_secret_expires_at: number2().optional()
23061
+ client_secret_expires_at: number2().optional(),
23062
+ issuer: string2().optional().catch(void 0)
23035
23063
  }).strip();
23036
23064
  var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
23037
23065
  var OAuthClientRegistrationErrorSchema = object({
@@ -23043,7 +23071,7 @@ var OAuthTokenRevocationRequestSchema = object({
23043
23071
  token_type_hint: string2().optional()
23044
23072
  }).strip();
23045
23073
 
23046
- // node_modules/@modelcontextprotocol/server/dist/src-CX2iR2pK.mjs
23074
+ // node_modules/@modelcontextprotocol/server/dist/src-Cqbh3MYc.mjs
23047
23075
  var BRANDS = Symbol.for("mcp.sdk.errorBrands");
23048
23076
  function stampErrorBrands(instance, ctor) {
23049
23077
  const brands = /* @__PURE__ */ new Set();
@@ -23157,8 +23185,18 @@ var SdkError = class extends Error {
23157
23185
  if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");
23158
23186
  return brandedHasInstance(this, value);
23159
23187
  }
23160
- constructor(code, message2, data) {
23161
- super(message2);
23188
+ /**
23189
+ * @param code - Stable string code identifying the failure ({@linkcode SdkErrorCode}).
23190
+ * @param message - Human-readable description.
23191
+ * @param data - Optional structured payload (for example the HTTP status carried by
23192
+ * {@linkcode SdkHttpError}). Opaque to the SDK: a `cause` key inside `data` is not
23193
+ * promoted to `Error.cause`.
23194
+ * @param options - Standard `ErrorOptions`, forwarded to `Error`. Pass the underlying
23195
+ * failure as `{ cause }` so it is reachable through the `Error.cause` chain that
23196
+ * loggers and error trackers walk.
23197
+ */
23198
+ constructor(code, message2, data, options) {
23199
+ super(message2, options);
23162
23200
  this.code = code;
23163
23201
  this.data = data;
23164
23202
  this.name = "SdkError";
@@ -23169,8 +23207,11 @@ var SdkHttpError = class extends SdkError {
23169
23207
  static {
23170
23208
  Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" });
23171
23209
  }
23172
- constructor(code, message2, data) {
23173
- super(code, message2, data);
23210
+ /**
23211
+ * @param options - Standard `ErrorOptions`, forwarded to `Error` (see {@linkcode SdkError}).
23212
+ */
23213
+ constructor(code, message2, data, options) {
23214
+ super(code, message2, data, options);
23174
23215
  this.name = "SdkHttpError";
23175
23216
  }
23176
23217
  get status() {
@@ -25273,7 +25314,8 @@ function build() {
25273
25314
  ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1),
25274
25315
  ReadResourceResultResponseSchema: wireResultResponse(union([ReadResourceResultSchema$1, InputRequiredResultSchema])),
25275
25316
  CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1),
25276
- DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1)
25317
+ DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1),
25318
+ SubscriptionsListenResultResponseSchema: wireResultResponse(SubscriptionsListenResultSchema$1)
25277
25319
  };
25278
25320
  }
25279
25321
  var memo2;
@@ -25701,6 +25743,8 @@ var rev2026Codec = {
25701
25743
  const rawInputRequests = raw2["inputRequests"];
25702
25744
  const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {};
25703
25745
  const requestState = raw2["requestState"];
25746
+ const metaParse = raw2["_meta"] === void 0 ? void 0 : buildSchemas2026().ResultMetaSchema.safeParse(raw2["_meta"]);
25747
+ const meta2 = metaParse?.success ? metaParse.data : void 0;
25704
25748
  if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return {
25705
25749
  kind: "invalid",
25706
25750
  error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, {
@@ -25711,7 +25755,8 @@ var rev2026Codec = {
25711
25755
  return {
25712
25756
  kind: "input_required",
25713
25757
  inputRequests,
25714
- ...typeof requestState === "string" && { requestState }
25758
+ ...typeof requestState === "string" && { requestState },
25759
+ ...meta2 !== void 0 && { _meta: meta2 }
25715
25760
  };
25716
25761
  }
25717
25762
  if (rawResultType !== "complete") return {
@@ -25778,6 +25823,9 @@ function isSpecRequestMethod(method) {
25778
25823
  function isSpecNotificationMethod(method) {
25779
25824
  return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method));
25780
25825
  }
25826
+ function isExtensionReusedRequestMethod(method) {
25827
+ return method === "tasks/get" || method === "tasks/cancel";
25828
+ }
25781
25829
  var ALL_CODECS = [rev2025Codec, rev2026Codec];
25782
25830
  function isPlainObject$3(value) {
25783
25831
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -26121,7 +26169,7 @@ var INBOUND_VALIDATION_LADDER = [
26121
26169
  evaluatedAt: "pre-dispatch",
26122
26170
  codes: [HEADER_MISMATCH_ERROR_CODE],
26123
26171
  conformance: ["http-header-validation"],
26124
- rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."
26172
+ rationale: "SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half \u2014 including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."
26125
26173
  },
26126
26174
  {
26127
26175
  rung: "client-capabilities",
@@ -26755,6 +26803,8 @@ var Protocol = class {
26755
26803
  _transport;
26756
26804
  _requestMessageId = 0;
26757
26805
  _requestHandlers = /* @__PURE__ */ new Map();
26806
+ /** Methods registered with an explicit schema; the era gate in `_onrequest` reads it for the Tasks extension names. */
26807
+ _customSchemaRequestMethods = /* @__PURE__ */ new Set();
26758
26808
  _requestHandlerAbortControllers = /* @__PURE__ */ new Map();
26759
26809
  _notificationHandlers = /* @__PURE__ */ new Map();
26760
26810
  _responseHandlers = /* @__PURE__ */ new Map();
@@ -26891,7 +26941,7 @@ var Protocol = class {
26891
26941
  return this._requestHandlers.get(method);
26892
26942
  }
26893
26943
  async _oncancel(notification) {
26894
- if (!notification.params.requestId) return;
26944
+ if (notification.params.requestId === void 0) return;
26895
26945
  this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason);
26896
26946
  }
26897
26947
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
@@ -27038,7 +27088,7 @@ var Protocol = class {
27038
27088
  return;
27039
27089
  }
27040
27090
  }
27041
- if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) {
27091
+ if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method) && !(isExtensionReusedRequestMethod(request.method) && this._customSchemaRequestMethods.has(request.method))) {
27042
27092
  sendErrorResponse(ProtocolErrorCode.MethodNotFound, "Method not found");
27043
27093
  return;
27044
27094
  }
@@ -27171,8 +27221,11 @@ var Protocol = class {
27171
27221
  }
27172
27222
  request(request, schemaOrOptions, maybeOptions) {
27173
27223
  const codec = this._resolveOutboundCodec(request.method);
27224
+ if (isStandardSchema(schemaOrOptions)) {
27225
+ if (!isExtensionReusedRequestMethod(request.method)) this._assertOutboundRequestInEra(codec, request.method);
27226
+ return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);
27227
+ }
27174
27228
  this._assertOutboundRequestInEra(codec, request.method);
27175
- if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);
27176
27229
  const validate2 = codecResultValidator(codec, request.method);
27177
27230
  if (validate2 === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);
27178
27231
  return this._requestWithSchemaViaCodec(codec, request, validate2, schemaOrOptions);
@@ -27290,19 +27343,20 @@ var Protocol = class {
27290
27343
  const cancel = (reason) => {
27291
27344
  if (responseReceived) return;
27292
27345
  this._progressHandlers.delete(messageId);
27293
- if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({
27294
- jsonrpc: "2.0",
27295
- method: "notifications/cancelled",
27296
- params: {
27297
- requestId: messageId,
27298
- reason: String(reason)
27299
- }
27300
- }), {
27301
- relatedRequestId,
27302
- resumptionToken,
27303
- onresumptiontoken
27304
- }).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error2}`)));
27305
- else requestAbort.abort();
27346
+ if (requestAbort === void 0) {
27347
+ if (request.method !== "initialize") this._transport?.send(this._envelopeOutbound({
27348
+ jsonrpc: "2.0",
27349
+ method: "notifications/cancelled",
27350
+ params: {
27351
+ requestId: messageId,
27352
+ reason: String(reason)
27353
+ }
27354
+ }), {
27355
+ relatedRequestId,
27356
+ resumptionToken,
27357
+ onresumptiontoken
27358
+ }).catch((error2) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error2}`)));
27359
+ } else requestAbort.abort();
27306
27360
  reject(reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason)));
27307
27361
  };
27308
27362
  this._responseHandlers.set(messageId, (response) => {
@@ -27364,7 +27418,7 @@ var Protocol = class {
27364
27418
  * Emits a notification, which is a one-way message that does not expect a response.
27365
27419
  */
27366
27420
  async notification(notification, options) {
27367
- return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);
27421
+ return await this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);
27368
27422
  }
27369
27423
  /**
27370
27424
  * The notification funnel proper, keyed by the resolved era codec —
@@ -27382,7 +27436,7 @@ var Protocol = class {
27382
27436
  jsonrpc: "2.0",
27383
27437
  ...notification
27384
27438
  });
27385
- if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) {
27439
+ if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && options?.relatedRequestId === void 0) {
27386
27440
  if (this._pendingDebouncedNotifications.has(notification.method)) return;
27387
27441
  this._pendingDebouncedNotifications.add(notification.method);
27388
27442
  Promise.resolve().then(() => {
@@ -27415,6 +27469,8 @@ var Protocol = class {
27415
27469
  return maybeHandler(parsed.data, ctx);
27416
27470
  };
27417
27471
  else throw new TypeError("setRequestHandler: handler is required");
27472
+ if (typeof schemasOrHandler === "function") this._customSchemaRequestMethods.delete(method);
27473
+ else this._customSchemaRequestMethods.add(method);
27418
27474
  this._requestHandlers.set(method, this._wrapHandler(method, stored));
27419
27475
  }
27420
27476
  /**
@@ -27444,6 +27500,7 @@ var Protocol = class {
27444
27500
  */
27445
27501
  removeRequestHandler(method) {
27446
27502
  this._requestHandlers.delete(method);
27503
+ this._customSchemaRequestMethods.delete(method);
27447
27504
  }
27448
27505
  /**
27449
27506
  * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
@@ -27521,7 +27578,8 @@ function manualInputRequiredValue(decoded) {
27521
27578
  return {
27522
27579
  resultType: "input_required",
27523
27580
  inputRequests: decoded.inputRequests,
27524
- ...decoded.requestState !== void 0 && { requestState: decoded.requestState }
27581
+ ...decoded.requestState !== void 0 && { requestState: decoded.requestState },
27582
+ ...decoded._meta !== void 0 && { _meta: decoded._meta }
27525
27583
  };
27526
27584
  }
27527
27585
  var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => {
@@ -28033,7 +28091,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28033
28091
  AND: new code_1._Code("&&"),
28034
28092
  ADD: new code_1._Code("+")
28035
28093
  };
28036
- var Node3 = class {
28094
+ var Node5 = class {
28037
28095
  optimizeNodes() {
28038
28096
  return this;
28039
28097
  }
@@ -28041,7 +28099,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28041
28099
  return this;
28042
28100
  }
28043
28101
  };
28044
- var Def = class extends Node3 {
28102
+ var Def = class extends Node5 {
28045
28103
  constructor(varKind, name, rhs) {
28046
28104
  super();
28047
28105
  this.varKind = varKind;
@@ -28062,7 +28120,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28062
28120
  return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
28063
28121
  }
28064
28122
  };
28065
- var Assign = class extends Node3 {
28123
+ var Assign = class extends Node5 {
28066
28124
  constructor(lhs, rhs, sideEffects) {
28067
28125
  super();
28068
28126
  this.lhs = lhs;
@@ -28090,7 +28148,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28090
28148
  return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
28091
28149
  }
28092
28150
  };
28093
- var Label = class extends Node3 {
28151
+ var Label = class extends Node5 {
28094
28152
  constructor(label) {
28095
28153
  super();
28096
28154
  this.label = label;
@@ -28100,7 +28158,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28100
28158
  return `${this.label}:` + _n;
28101
28159
  }
28102
28160
  };
28103
- var Break = class extends Node3 {
28161
+ var Break = class extends Node5 {
28104
28162
  constructor(label) {
28105
28163
  super();
28106
28164
  this.label = label;
@@ -28110,7 +28168,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28110
28168
  return `break${this.label ? ` ${this.label}` : ""};` + _n;
28111
28169
  }
28112
28170
  };
28113
- var Throw = class extends Node3 {
28171
+ var Throw = class extends Node5 {
28114
28172
  constructor(error2) {
28115
28173
  super();
28116
28174
  this.error = error2;
@@ -28122,7 +28180,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28122
28180
  return this.error.names;
28123
28181
  }
28124
28182
  };
28125
- var AnyCode = class extends Node3 {
28183
+ var AnyCode = class extends Node5 {
28126
28184
  constructor(code) {
28127
28185
  super();
28128
28186
  this.code = code;
@@ -28141,7 +28199,7 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
28141
28199
  return this.code instanceof code_1._CodeOrName ? this.code.names : {};
28142
28200
  }
28143
28201
  };
28144
- var ParentNode = class extends Node3 {
28202
+ var ParentNode = class extends Node5 {
28145
28203
  constructor(nodes = []) {
28146
28204
  super();
28147
28205
  this.nodes = nodes;
@@ -34685,7 +34743,7 @@ var Ajv = import_ajv.Ajv;
34685
34743
  // node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs
34686
34744
  import process2 from "node:process";
34687
34745
 
34688
- // node_modules/@modelcontextprotocol/server/dist/mcp-DXXb3Vv3.mjs
34746
+ // node_modules/@modelcontextprotocol/server/dist/mcp-DIH4cS6P.mjs
34689
34747
  var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
34690
34748
  function isCompletable(schema) {
34691
34749
  return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
@@ -34750,7 +34808,7 @@ var StdioListenRouter = class {
34750
34808
  _serverCapabilities;
34751
34809
  /**
34752
34810
  * The serving instance's identity, stamped onto the graceful-close
34753
- * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends
34811
+ * results' `_meta` (the spec's `SubscriptionsListenResultMetaObject` extends
34754
34812
  * `ResultMetaObject`). Handed over together with the capabilities.
34755
34813
  */
34756
34814
  _serverInfo;
@@ -34878,6 +34936,9 @@ function notificationToServerEvent(method, uri) {
34878
34936
  };
34879
34937
  }
34880
34938
  }
34939
+ function supportsScopeChallengeResolver(transport) {
34940
+ return typeof transport === "object" && transport !== null && "setScopeChallengeResolver" in transport && typeof transport.setScopeChallengeResolver === "function";
34941
+ }
34881
34942
  var DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8;
34882
34943
  var DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5;
34883
34944
  function resolveLegacyShimOptions(options) {
@@ -35079,6 +35140,11 @@ var Server = class extends Protocol {
35079
35140
  if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover());
35080
35141
  if (this._capabilities.logging) this._registerLoggingHandler();
35081
35142
  }
35143
+ /** Attaches to the given transport; rejects while this instance is connected to another one. */
35144
+ async connect(transport) {
35145
+ if (this.transport !== void 0) throw new SdkError(SdkErrorCode.AlreadyConnected, "Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");
35146
+ await super.connect(transport);
35147
+ }
35082
35148
  /**
35083
35149
  * Registers the built-in `logging/setLevel` request handler.
35084
35150
  *
@@ -35632,21 +35698,41 @@ var Server = class extends Protocol {
35632
35698
  function discoverAdvertisedCapabilities(capabilities) {
35633
35699
  return { ...capabilities };
35634
35700
  }
35701
+ function toolInputElementCount(value, max) {
35702
+ let count = 0;
35703
+ const stack = [value];
35704
+ while (stack.length > 0) {
35705
+ const node2 = stack.pop();
35706
+ if (node2 === null || typeof node2 !== "object") continue;
35707
+ if (Array.isArray(node2)) for (const child of node2) {
35708
+ if (++count > max) return count;
35709
+ if (child !== null && typeof child === "object") stack.push(child);
35710
+ }
35711
+ else for (const key in node2) {
35712
+ if (!Object.prototype.hasOwnProperty.call(node2, key)) continue;
35713
+ if (++count > max) return count;
35714
+ const child = node2[key];
35715
+ if (child !== null && typeof child === "object") stack.push(child);
35716
+ }
35717
+ }
35718
+ return count;
35719
+ }
35720
+ function resolveMaxToolInputElements(value) {
35721
+ if (value === void 0 || value === Infinity) return void 0;
35722
+ if (typeof value !== "number" || Number.isNaN(value) || value < 1) throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
35723
+ return value;
35724
+ }
35635
35725
  var McpServer = class {
35636
35726
  /**
35637
35727
  * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.
35638
35728
  */
35639
35729
  server;
35730
+ _maxToolInputElements;
35640
35731
  _registeredResources = {};
35641
35732
  _registeredResourceTemplates = {};
35642
35733
  _registeredTools = {};
35643
35734
  _registeredPrompts = {};
35644
- /**
35645
- * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243
35646
- * registration-time scan and the pre-dispatch validation step share one
35647
- * conversion instead of paying it twice per request under the
35648
- * per-request-factory `createMcpHandler` model.
35649
- */
35735
+ /** Per-tool JSON-converted `inputSchema`, filled on first use by `toolInputSchemaJson()`. */
35650
35736
  _toolInputSchemaJson = {};
35651
35737
  /**
35652
35738
  * The JSON-serialized `inputSchema` of a registered tool, or `undefined`
@@ -35671,6 +35757,7 @@ var McpServer = class {
35671
35757
  }
35672
35758
  constructor(serverInfo, options) {
35673
35759
  this.server = new Server(serverInfo, options);
35760
+ this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
35674
35761
  if (options?.capabilities?.tools) this.setToolRequestHandlers();
35675
35762
  if (options?.capabilities?.resources) this.setResourceRequestHandlers();
35676
35763
  if (options?.capabilities?.prompts) this.setPromptRequestHandlers();
@@ -35688,6 +35775,7 @@ var McpServer = class {
35688
35775
  * ```
35689
35776
  */
35690
35777
  async connect(transport) {
35778
+ if (supportsScopeChallengeResolver(transport)) transport.setScopeChallengeResolver((context2) => this.resolveScopeChallenge(context2));
35691
35779
  return await this.server.connect(transport);
35692
35780
  }
35693
35781
  /**
@@ -35696,6 +35784,41 @@ var McpServer = class {
35696
35784
  async close() {
35697
35785
  await this.server.close();
35698
35786
  }
35787
+ /** @internal */
35788
+ resolveScopeChallenge = (context2) => {
35789
+ switch (context2.request.method) {
35790
+ case "tools/call": {
35791
+ const toolName = context2.request.params?.name;
35792
+ if (typeof toolName !== "string") return;
35793
+ const tool = this._registeredTools[toolName];
35794
+ if (tool === void 0 || !tool.enabled) return;
35795
+ return tool.scopeChallenge?.(context2);
35796
+ }
35797
+ case "resources/read": {
35798
+ const resourceUri = context2.request.params?.uri;
35799
+ if (typeof resourceUri !== "string") return;
35800
+ let uri;
35801
+ try {
35802
+ uri = new URL(resourceUri);
35803
+ } catch {
35804
+ return;
35805
+ }
35806
+ const resource = this._registeredResources[uri.toString()];
35807
+ if (resource !== void 0) return resource.enabled ? resource.scopeChallenge?.(context2) : void 0;
35808
+ for (const template of Object.values(this._registeredResourceTemplates)) if (template.resourceTemplate.uriTemplate.match(uri.toString())) return template.enabled ? template.scopeChallenge?.(context2) : void 0;
35809
+ return;
35810
+ }
35811
+ case "prompts/get": {
35812
+ const promptName = context2.request.params?.name;
35813
+ if (typeof promptName !== "string") return;
35814
+ const prompt = this._registeredPrompts[promptName];
35815
+ if (prompt === void 0 || !prompt.enabled) return;
35816
+ return prompt.scopeChallenge?.(context2);
35817
+ }
35818
+ default:
35819
+ return;
35820
+ }
35821
+ };
35699
35822
  _toolHandlersInitialized = false;
35700
35823
  setToolRequestHandlers() {
35701
35824
  if (this._toolHandlersInitialized) return;
@@ -35707,7 +35830,7 @@ var McpServer = class {
35707
35830
  name,
35708
35831
  title: tool.title,
35709
35832
  description: tool.description,
35710
- inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA,
35833
+ inputSchema: tool.inputSchema ? convertListedInputSchema(name, tool.inputSchema) : EMPTY_OBJECT_JSON_SCHEMA,
35711
35834
  annotations: tool.annotations,
35712
35835
  icons: tool.icons,
35713
35836
  execution: tool.execution,
@@ -35752,6 +35875,7 @@ var McpServer = class {
35752
35875
  * Validates tool input arguments against the tool's input schema.
35753
35876
  */
35754
35877
  async validateToolInput(tool, args, toolName) {
35878
+ if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
35755
35879
  if (!tool.inputSchema) return;
35756
35880
  const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});
35757
35881
  if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`);
@@ -35862,7 +35986,10 @@ var McpServer = class {
35862
35986
  }
35863
35987
  for (const template of Object.values(this._registeredResourceTemplates)) {
35864
35988
  const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
35865
- if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
35989
+ if (variables) {
35990
+ if (!template.enabled) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${template.resourceTemplate.uriTemplate} disabled`);
35991
+ return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);
35992
+ }
35866
35993
  }
35867
35994
  throw new ResourceNotFoundError(request.params.uri);
35868
35995
  });
@@ -35893,36 +36020,32 @@ var McpServer = class {
35893
36020
  this._promptHandlersInitialized = true;
35894
36021
  }
35895
36022
  registerResource(name, uriOrTemplate, config2, readCallback) {
35896
- const cacheHint = config2.cacheHint;
35897
- let metadata = config2;
35898
- if (cacheHint !== void 0) {
35899
- assertValidCacheHint(cacheHint, `resource ${name}`);
35900
- const rest = { ...config2 };
35901
- delete rest.cacheHint;
35902
- metadata = rest;
35903
- }
36023
+ const { cacheHint, scopeChallenge, ...resourceMetadata } = config2;
36024
+ const metadata = resourceMetadata;
36025
+ if (cacheHint !== void 0) assertValidCacheHint(cacheHint, `resource ${name}`);
35904
36026
  if (typeof uriOrTemplate === "string") {
35905
36027
  if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
35906
- const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, metadata, readCallback);
36028
+ const registeredResource = this._createRegisteredResource(name, config2.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
35907
36029
  if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint;
35908
36030
  this.setResourceRequestHandlers();
35909
36031
  this.sendResourceListChanged();
35910
36032
  return registeredResource;
35911
36033
  } else {
35912
36034
  if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
35913
- const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, metadata, readCallback);
36035
+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config2.title, uriOrTemplate, metadata, scopeChallenge, readCallback);
35914
36036
  if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint;
35915
36037
  this.setResourceRequestHandlers();
35916
36038
  this.sendResourceListChanged();
35917
36039
  return registeredResourceTemplate;
35918
36040
  }
35919
36041
  }
35920
- _createRegisteredResource(name, title, uri, metadata, readCallback) {
36042
+ _createRegisteredResource(name, title, uri, metadata, scopeChallenge, readCallback) {
35921
36043
  const registeredResource = {
35922
36044
  name,
35923
36045
  title,
35924
36046
  metadata,
35925
36047
  readCallback,
36048
+ scopeChallenge,
35926
36049
  enabled: true,
35927
36050
  disable: () => registeredResource.update({ enabled: false }),
35928
36051
  enable: () => registeredResource.update({ enabled: true }),
@@ -35936,6 +36059,7 @@ var McpServer = class {
35936
36059
  if (updates.title !== void 0) registeredResource.title = updates.title;
35937
36060
  if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata;
35938
36061
  if (updates.callback !== void 0) registeredResource.readCallback = updates.callback;
36062
+ if (updates.scopeChallenge !== void 0) registeredResource.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
35939
36063
  if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled;
35940
36064
  this.sendResourceListChanged();
35941
36065
  }
@@ -35943,12 +36067,13 @@ var McpServer = class {
35943
36067
  this._registeredResources[uri] = registeredResource;
35944
36068
  return registeredResource;
35945
36069
  }
35946
- _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
36070
+ _createRegisteredResourceTemplate(name, title, template, metadata, scopeChallenge, readCallback) {
35947
36071
  const registeredResourceTemplate = {
35948
36072
  resourceTemplate: template,
35949
36073
  title,
35950
36074
  metadata,
35951
36075
  readCallback,
36076
+ scopeChallenge,
35952
36077
  enabled: true,
35953
36078
  disable: () => registeredResourceTemplate.update({ enabled: false }),
35954
36079
  enable: () => registeredResourceTemplate.update({ enabled: true }),
@@ -35962,6 +36087,7 @@ var McpServer = class {
35962
36087
  if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template;
35963
36088
  if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata;
35964
36089
  if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback;
36090
+ if (updates.scopeChallenge !== void 0) registeredResourceTemplate.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
35965
36091
  if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled;
35966
36092
  this.sendResourceListChanged();
35967
36093
  }
@@ -35971,7 +36097,7 @@ var McpServer = class {
35971
36097
  if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler();
35972
36098
  return registeredResourceTemplate;
35973
36099
  }
35974
- _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) {
36100
+ _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, scopeChallenge, _meta) {
35975
36101
  let currentArgsSchema = argsSchema;
35976
36102
  let currentCallback = callback;
35977
36103
  const registeredPrompt = {
@@ -35979,6 +36105,7 @@ var McpServer = class {
35979
36105
  description,
35980
36106
  argsSchema,
35981
36107
  icons,
36108
+ scopeChallenge,
35982
36109
  _meta,
35983
36110
  handler: createPromptHandler(name, argsSchema, callback),
35984
36111
  enabled: true,
@@ -35993,6 +36120,7 @@ var McpServer = class {
35993
36120
  if (updates.title !== void 0) registeredPrompt.title = updates.title;
35994
36121
  if (updates.description !== void 0) registeredPrompt.description = updates.description;
35995
36122
  if (updates.icons !== void 0) registeredPrompt.icons = updates.icons;
36123
+ if (updates.scopeChallenge !== void 0) registeredPrompt.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
35996
36124
  if (updates._meta !== void 0) registeredPrompt._meta = updates._meta;
35997
36125
  let needsHandlerRegen = false;
35998
36126
  if (updates.argsSchema !== void 0) {
@@ -36020,25 +36148,25 @@ var McpServer = class {
36020
36148
  }
36021
36149
  return registeredPrompt;
36022
36150
  }
36023
- _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) {
36151
+ _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, scopeChallenge, _meta, handler) {
36024
36152
  validateAndWarnToolName(name);
36025
- if (inputSchema !== void 0) try {
36026
- const json = standardSchemaToJsonSchema(inputSchema, "input");
36027
- this._toolInputSchemaJson[name] = json;
36028
- const scan = scanXMcpHeaderDeclarations(json);
36029
- if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`);
36030
- } catch {
36031
- }
36032
36153
  let currentHandler = handler;
36154
+ let outputSchemaJson;
36033
36155
  const registeredTool = {
36034
36156
  title,
36035
36157
  description,
36036
36158
  inputSchema,
36037
36159
  outputSchema,
36038
- outputSchemaJson: convertOutputSchemaJson(outputSchema),
36160
+ get outputSchemaJson() {
36161
+ return outputSchemaJson ??= convertOutputSchemaJson(registeredTool.outputSchema);
36162
+ },
36163
+ set outputSchemaJson(value) {
36164
+ outputSchemaJson = value;
36165
+ },
36039
36166
  annotations,
36040
36167
  icons,
36041
36168
  execution,
36169
+ scopeChallenge,
36042
36170
  _meta,
36043
36171
  handler,
36044
36172
  executor: createToolExecutor(inputSchema, handler),
@@ -36077,6 +36205,7 @@ var McpServer = class {
36077
36205
  }
36078
36206
  if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations;
36079
36207
  if (updates.icons !== void 0) registeredTool.icons = updates.icons;
36208
+ if (updates.scopeChallenge !== void 0) registeredTool.scopeChallenge = updates.scopeChallenge === null ? void 0 : updates.scopeChallenge;
36080
36209
  if (updates._meta !== void 0) registeredTool._meta = updates._meta;
36081
36210
  if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled;
36082
36211
  this.sendToolListChanged();
@@ -36089,13 +36218,13 @@ var McpServer = class {
36089
36218
  }
36090
36219
  registerTool(name, config2, cb) {
36091
36220
  if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
36092
- const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config2;
36093
- return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb);
36221
+ const { title, description, inputSchema, outputSchema, annotations, icons, scopeChallenge, _meta } = config2;
36222
+ return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, scopeChallenge, _meta, cb);
36094
36223
  }
36095
36224
  registerPrompt(name, config2, cb) {
36096
36225
  if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
36097
- const { title, description, argsSchema, icons, _meta } = config2;
36098
- const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta);
36226
+ const { title, description, argsSchema, icons, scopeChallenge, _meta } = config2;
36227
+ const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, scopeChallenge, _meta);
36099
36228
  this.setPromptRequestHandlers();
36100
36229
  this.sendPromptListChanged();
36101
36230
  return registeredPrompt;
@@ -36160,6 +36289,12 @@ var EMPTY_OBJECT_JSON_SCHEMA = {
36160
36289
  type: "object",
36161
36290
  properties: {}
36162
36291
  };
36292
+ function convertListedInputSchema(name, inputSchema) {
36293
+ const json = standardSchemaToJsonSchema(inputSchema, "input");
36294
+ const scan = scanXMcpHeaderDeclarations(json);
36295
+ if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`);
36296
+ return json;
36297
+ }
36163
36298
  function convertOutputSchemaJson(outputSchema) {
36164
36299
  if (outputSchema === void 0) return void 0;
36165
36300
  try {
@@ -36172,7 +36307,7 @@ function createPromptHandler(name, argsSchema, callback) {
36172
36307
  if (argsSchema) {
36173
36308
  const typedCallback = callback;
36174
36309
  return async (args, ctx) => {
36175
- const parseResult = await validateStandardSchema(argsSchema, args);
36310
+ const parseResult = await validateStandardSchema(argsSchema, args ?? {});
36176
36311
  if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`);
36177
36312
  return typedCallback(parseResult.data, ctx);
36178
36313
  };
@@ -36206,7 +36341,11 @@ function unwrapOptionalSchema(schema) {
36206
36341
  return schema.def?.innerType ?? schema;
36207
36342
  }
36208
36343
 
36344
+ // node_modules/@modelcontextprotocol/server/dist/index.mjs
36345
+ var DEFAULT_MAX_REQUEST_BODY_SIZE = 4 * 1024 * 1024;
36346
+
36209
36347
  // node_modules/@modelcontextprotocol/server/dist/stdio.mjs
36348
+ var swallowsErrorsAfterClose = Symbol("swallowsErrorsAfterClose");
36210
36349
  var StdioServerTransport = class {
36211
36350
  _readBuffer;
36212
36351
  _started = false;
@@ -36233,18 +36372,27 @@ var StdioServerTransport = class {
36233
36372
  this.onerror?.(error2);
36234
36373
  };
36235
36374
  _onstdouterror = (error2) => {
36375
+ if (this._closed) return;
36236
36376
  this.onerror?.(error2);
36237
36377
  this.close().catch(() => {
36238
36378
  });
36239
36379
  };
36380
+ _onstdinclose = () => {
36381
+ this.close().catch(() => {
36382
+ });
36383
+ };
36240
36384
  /**
36241
36385
  * Starts listening for messages on `stdin`.
36242
36386
  */
36243
36387
  async start() {
36244
36388
  if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
36245
36389
  this._started = true;
36390
+ for (const listener of this._stdout.listeners("error")) if (listener[swallowsErrorsAfterClose]) this._stdout.off("error", listener);
36391
+ if (this._stdin.readableEnded || this._stdin.destroyed) setImmediate(this._onstdinclose);
36246
36392
  this._stdin.on("data", this._ondata);
36247
36393
  this._stdin.on("error", this._onerror);
36394
+ this._stdin.on("end", this._onstdinclose);
36395
+ this._stdin.on("close", this._onstdinclose);
36248
36396
  this._stdout.on("error", this._onstdouterror);
36249
36397
  }
36250
36398
  processReadBuffer() {
@@ -36261,7 +36409,9 @@ var StdioServerTransport = class {
36261
36409
  this._closed = true;
36262
36410
  this._stdin.off("data", this._ondata);
36263
36411
  this._stdin.off("error", this._onerror);
36264
- this._stdout.off("error", this._onstdouterror);
36412
+ this._stdin.off("end", this._onstdinclose);
36413
+ this._stdin.off("close", this._onstdinclose);
36414
+ this._onstdouterror[swallowsErrorsAfterClose] = true;
36265
36415
  if (this._stdin.listenerCount("data") === 0) this._stdin.pause();
36266
36416
  this._readBuffer.clear();
36267
36417
  this.onclose?.();
@@ -36538,6 +36688,7 @@ function serveStdio(factory, options = {}) {
36538
36688
  return;
36539
36689
  }
36540
36690
  if (state.era === "modern" && await tryServeListen(message2)) return;
36691
+ if (isTornDown()) return;
36541
36692
  state.instance.channel.deliver(message2);
36542
36693
  return;
36543
36694
  }
@@ -36604,6 +36755,7 @@ function serveStdio(factory, options = {}) {
36604
36755
  };
36605
36756
  }
36606
36757
  if (await tryServeListen(message2)) return;
36758
+ if (isTornDown()) return;
36607
36759
  state.instance.channel.deliver(message2, { classification: opening.classification });
36608
36760
  return;
36609
36761
  case "legacy": {
@@ -38172,152 +38324,68 @@ var ServerResultSchema2 = union([
38172
38324
  CreateTaskResultSchema2
38173
38325
  ]);
38174
38326
 
38175
- // node_modules/hono/dist/compose.js
38176
- var compose = (middleware, onError, onNotFound) => {
38177
- return (context2, next) => {
38178
- let index = -1;
38179
- return dispatch(0);
38180
- async function dispatch(i) {
38181
- if (i <= index) {
38182
- throw new Error("next() called multiple times");
38183
- }
38184
- index = i;
38185
- let res;
38186
- let isError = false;
38187
- let handler;
38188
- if (middleware[i]) {
38189
- handler = middleware[i][0][0];
38190
- context2.req.routeIndex = i;
38191
- } else {
38192
- handler = i === middleware.length && next || void 0;
38193
- }
38194
- if (handler) {
38195
- try {
38196
- res = await handler(context2, () => dispatch(i + 1));
38197
- } catch (err) {
38198
- if (err instanceof Error && onError) {
38199
- context2.error = err;
38200
- res = await onError(err, context2);
38201
- isError = true;
38202
- } else {
38203
- throw err;
38204
- }
38205
- }
38206
- } else {
38207
- if (context2.finalized === false && onNotFound) {
38208
- res = await onNotFound(context2);
38209
- }
38210
- }
38211
- if (res && (context2.finalized === false || isError)) {
38212
- context2.res = res;
38213
- }
38214
- return context2;
38215
- }
38216
- };
38217
- };
38218
-
38219
38327
  // node_modules/hono/dist/request/constants.js
38220
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
38328
+ var GET_MATCH_RESULT = Symbol();
38221
38329
 
38222
38330
  // node_modules/hono/dist/utils/buffer.js
38223
38331
  var bufferToFormData = (arrayBuffer, contentType) => {
38224
- const response = new Response(arrayBuffer, {
38225
- headers: {
38226
- // Normalize the media type (case-insensitive) while keeping parameters like the boundary
38227
- "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase())
38228
- }
38229
- });
38230
- return response.formData();
38332
+ return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
38231
38333
  };
38232
38334
 
38233
38335
  // node_modules/hono/dist/utils/body.js
38234
- var MAX_NESTING_DEPTH = 32;
38235
38336
  var MAX_NESTED_OBJECTS = 1e4;
38236
38337
  var isRawRequest = (request) => "headers" in request;
38237
38338
  var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
38238
38339
  const { all = false, dot = false } = options;
38239
- const headers = isRawRequest(request) ? request.headers : request.raw.headers;
38240
- const contentType = headers.get("Content-Type");
38241
- const mediaType = contentType?.split(";")[0].trim().toLowerCase();
38242
- if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") {
38243
- return parseFormData(request, { all, dot });
38244
- }
38340
+ const mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
38341
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded") return parseFormData(request, {
38342
+ all,
38343
+ dot
38344
+ });
38245
38345
  return {};
38246
38346
  };
38247
38347
  async function parseFormData(request, options) {
38248
- if (!isRawRequest(request) && request.bodyCache.formData) {
38249
- return convertFormDataToBodyData(
38250
- await request.bodyCache.formData,
38251
- options
38252
- );
38253
- }
38348
+ if (!isRawRequest(request) && request.bodyCache.formData) return convertFormDataToBodyData(await request.bodyCache.formData, options);
38254
38349
  const headers = isRawRequest(request) ? request.headers : request.raw.headers;
38255
38350
  const arrayBuffer = await request.arrayBuffer();
38256
38351
  const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
38257
- if (!isRawRequest(request)) {
38258
- request.bodyCache.formData = formDataPromise;
38259
- }
38352
+ if (!isRawRequest(request)) request.bodyCache.formData = formDataPromise;
38260
38353
  const formData = await formDataPromise;
38261
- if (formData) {
38262
- return convertFormDataToBodyData(formData, options);
38263
- }
38354
+ if (formData) return convertFormDataToBodyData(formData, options);
38264
38355
  return {};
38265
38356
  }
38266
38357
  function convertFormDataToBodyData(formData, options) {
38267
38358
  const form = /* @__PURE__ */ Object.create(null);
38268
38359
  const nestingState = { count: 0 };
38269
38360
  formData.forEach((value, key) => {
38270
- const shouldParseAllValues = options.all || key.endsWith("[]");
38271
- if (!shouldParseAllValues) {
38272
- form[key] = value;
38273
- } else {
38274
- handleParsingAllValues(form, key, value);
38361
+ if (!(options.all || key.endsWith("[]"))) form[key] = value;
38362
+ else handleParsingAllValues(form, key, value);
38363
+ });
38364
+ if (options.dot) Object.entries(form).forEach(([key, value]) => {
38365
+ if (key.includes(".")) {
38366
+ handleParsingNestedValues(form, key, value, nestingState);
38367
+ delete form[key];
38275
38368
  }
38276
38369
  });
38277
- if (options.dot) {
38278
- Object.entries(form).forEach(([key, value]) => {
38279
- const shouldParseDotValues = key.includes(".");
38280
- if (shouldParseDotValues) {
38281
- handleParsingNestedValues(form, key, value, nestingState);
38282
- delete form[key];
38283
- }
38284
- });
38285
- }
38286
38370
  return form;
38287
38371
  }
38288
38372
  var handleParsingAllValues = (form, key, value) => {
38289
38373
  if (form[key] !== void 0) {
38290
- if (Array.isArray(form[key])) {
38291
- ;
38292
- form[key].push(value);
38293
- } else {
38294
- form[key] = [form[key], value];
38295
- }
38296
- } else {
38297
- if (!key.endsWith("[]")) {
38298
- form[key] = value;
38299
- } else {
38300
- form[key] = [value];
38301
- }
38302
- }
38374
+ if (Array.isArray(form[key])) form[key].push(value);
38375
+ else form[key] = [form[key], value];
38376
+ } else if (!key.endsWith("[]")) form[key] = value;
38377
+ else form[key] = [value];
38303
38378
  };
38304
38379
  var handleParsingNestedValues = (form, key, value, state) => {
38305
- if (/(?:^|\.)__proto__\./.test(key)) {
38306
- return;
38307
- }
38380
+ if (/(?:^|\.)__proto__\./.test(key)) return;
38308
38381
  let nestedForm = form;
38309
- const keys = key.split(".", MAX_NESTING_DEPTH + 2);
38310
- if (keys.length > MAX_NESTING_DEPTH + 1) {
38311
- throwNestingLimitExceeded();
38312
- }
38382
+ const keys = key.split(".", 34);
38383
+ if (keys.length > 33) throwNestingLimitExceeded();
38313
38384
  keys.forEach((key2, index) => {
38314
- if (index === keys.length - 1) {
38315
- nestedForm[key2] = value;
38316
- } else {
38385
+ if (index === keys.length - 1) nestedForm[key2] = value;
38386
+ else {
38317
38387
  if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
38318
- if (state.count++ >= MAX_NESTED_OBJECTS) {
38319
- throwNestingLimitExceeded();
38320
- }
38388
+ if (state.count++ >= MAX_NESTED_OBJECTS) throwNestingLimitExceeded();
38321
38389
  nestedForm[key2] = /* @__PURE__ */ Object.create(null);
38322
38390
  }
38323
38391
  nestedForm = nestedForm[key2];
@@ -38331,9 +38399,7 @@ var throwNestingLimitExceeded = () => {
38331
38399
  // node_modules/hono/dist/utils/url.js
38332
38400
  var splitPath = (path) => {
38333
38401
  const paths = path.split("/");
38334
- if (paths[0] === "") {
38335
- paths.shift();
38336
- }
38402
+ if (paths[0] === "") paths.shift();
38337
38403
  return paths;
38338
38404
  };
38339
38405
  var splitRoutingPath = (routePath) => {
@@ -38348,34 +38414,42 @@ var extractGroupsFromPath = (path) => {
38348
38414
  groups.push([mark, match2]);
38349
38415
  return mark;
38350
38416
  });
38351
- return { groups, path };
38417
+ return {
38418
+ groups,
38419
+ path
38420
+ };
38352
38421
  };
38353
38422
  var replaceGroupMarks = (paths, groups) => {
38354
38423
  for (let i = groups.length - 1; i >= 0; i--) {
38355
38424
  const [mark] = groups[i];
38356
- for (let j = paths.length - 1; j >= 0; j--) {
38357
- if (paths[j].includes(mark)) {
38358
- paths[j] = paths[j].replace(mark, groups[i][1]);
38359
- break;
38360
- }
38425
+ for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
38426
+ paths[j] = paths[j].replace(mark, groups[i][1]);
38427
+ break;
38361
38428
  }
38362
38429
  }
38363
38430
  return paths;
38364
38431
  };
38365
38432
  var patternCache = {};
38366
38433
  var getPattern = (label, next) => {
38367
- if (label === "*") {
38368
- return "*";
38369
- }
38434
+ if (label === "*") return "*";
38370
38435
  const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
38371
38436
  if (match2) {
38372
38437
  const cacheKey = `${label}#${next}`;
38373
38438
  if (!patternCache[cacheKey]) {
38374
- if (match2[2]) {
38375
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
38376
- } else {
38377
- patternCache[cacheKey] = [label, match2[1], true];
38378
- }
38439
+ if (match2[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
38440
+ cacheKey,
38441
+ match2[1],
38442
+ new RegExp(`^${match2[2]}(?=/${next})`)
38443
+ ] : [
38444
+ label,
38445
+ match2[1],
38446
+ new RegExp(`^${match2[2]}$`)
38447
+ ];
38448
+ else patternCache[cacheKey] = [
38449
+ label,
38450
+ match2[1],
38451
+ true
38452
+ ];
38379
38453
  }
38380
38454
  return patternCache[cacheKey];
38381
38455
  }
@@ -38407,9 +38481,7 @@ var getPath = (request) => {
38407
38481
  const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
38408
38482
  const path = url2.slice(start, end);
38409
38483
  return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
38410
- } else if (charCode === 63 || charCode === 35) {
38411
- break;
38412
- }
38484
+ } else if (charCode === 63 || charCode === 35) break;
38413
38485
  }
38414
38486
  return url2.slice(start, i);
38415
38487
  };
@@ -38418,74 +38490,52 @@ var getPathNoStrict = (request) => {
38418
38490
  return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
38419
38491
  };
38420
38492
  var mergePath = (base, sub, ...rest) => {
38421
- if (rest.length) {
38422
- sub = mergePath(sub, ...rest);
38423
- }
38493
+ if (rest.length) sub = mergePath(sub, ...rest);
38424
38494
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
38425
38495
  };
38426
38496
  var checkOptionalParameter = (path) => {
38427
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
38428
- return null;
38429
- }
38497
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) return null;
38430
38498
  const segments = path.split("/");
38431
38499
  const results = [];
38432
38500
  let basePath = "";
38433
38501
  segments.forEach((segment) => {
38434
- if (segment !== "" && !/\:/.test(segment)) {
38435
- basePath += "/" + segment;
38436
- } else if (/\:/.test(segment)) {
38502
+ if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
38503
+ else if (/\:/.test(segment)) {
38437
38504
  if (segment.charCodeAt(segment.length - 1) === 63) {
38438
- if (results.length === 0 && basePath === "") {
38439
- results.push("/");
38440
- } else {
38441
- results.push(basePath);
38442
- }
38505
+ if (results.length === 0 && basePath === "") results.push("/");
38506
+ else results.push(basePath);
38443
38507
  const optionalSegment = segment.slice(0, -1);
38444
38508
  basePath += "/" + optionalSegment;
38445
38509
  results.push(basePath);
38446
- } else {
38447
- basePath += "/" + segment;
38448
- }
38510
+ } else basePath += "/" + segment;
38449
38511
  }
38450
38512
  });
38451
38513
  return results.filter((v, i, a) => a.indexOf(v) === i);
38452
38514
  };
38453
38515
  var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
38454
38516
  var _decodeURI = (value) => {
38455
- if (value.indexOf("+") !== -1) {
38456
- value = value.replace(/\+/g, " ");
38457
- }
38517
+ if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
38458
38518
  return tryDecodeURIComponent(value);
38459
38519
  };
38460
38520
  var _getQueryParam = (url2, key, multiple) => {
38461
38521
  const hashIndex = url2.indexOf("#", 8);
38462
- if (hashIndex !== -1) {
38463
- url2 = url2.slice(0, hashIndex);
38464
- }
38522
+ if (hashIndex !== -1) url2 = url2.slice(0, hashIndex);
38465
38523
  let encoded;
38466
38524
  if (!multiple && key && key.indexOf("%") === -1 && key.indexOf("+") === -1) {
38467
38525
  let keyIndex2 = url2.indexOf("?", 8);
38468
- if (keyIndex2 === -1) {
38469
- return void 0;
38470
- }
38471
- if (!url2.startsWith(key, keyIndex2 + 1)) {
38472
- keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1);
38473
- }
38526
+ if (keyIndex2 === -1) return;
38527
+ if (!url2.startsWith(key, keyIndex2 + 1)) keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1);
38474
38528
  while (keyIndex2 !== -1) {
38475
38529
  const trailingKeyCode = url2.charCodeAt(keyIndex2 + key.length + 1);
38476
38530
  if (trailingKeyCode === 61) {
38477
38531
  const valueIndex = keyIndex2 + key.length + 2;
38478
38532
  const endIndex = url2.indexOf("&", valueIndex);
38479
38533
  return _decodeURI(url2.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
38480
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
38481
- return "";
38482
- }
38534
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) return "";
38483
38535
  keyIndex2 = url2.indexOf(`&${key}`, keyIndex2 + 1);
38484
38536
  }
38485
38537
  encoded = /[%+]/.test(url2);
38486
- if (!encoded) {
38487
- return void 0;
38488
- }
38538
+ if (!encoded) return;
38489
38539
  }
38490
38540
  const results = /* @__PURE__ */ Object.create(null);
38491
38541
  encoded ??= /[%+]/.test(url2);
@@ -38493,38 +38543,21 @@ var _getQueryParam = (url2, key, multiple) => {
38493
38543
  while (keyIndex !== -1) {
38494
38544
  const nextKeyIndex = url2.indexOf("&", keyIndex + 1);
38495
38545
  let valueIndex = url2.indexOf("=", keyIndex);
38496
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
38497
- valueIndex = -1;
38498
- }
38499
- let name = url2.slice(
38500
- keyIndex + 1,
38501
- valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
38502
- );
38503
- if (encoded) {
38504
- name = _decodeURI(name);
38505
- }
38546
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
38547
+ let name = url2.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
38548
+ if (encoded) name = _decodeURI(name);
38506
38549
  keyIndex = nextKeyIndex;
38507
- if (name === "") {
38508
- continue;
38509
- }
38550
+ if (name === "") continue;
38510
38551
  let value;
38511
- if (valueIndex === -1) {
38512
- value = "";
38513
- } else {
38552
+ if (valueIndex === -1) value = "";
38553
+ else {
38514
38554
  value = url2.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
38515
- if (encoded) {
38516
- value = _decodeURI(value);
38517
- }
38555
+ if (encoded) value = _decodeURI(value);
38518
38556
  }
38519
38557
  if (multiple) {
38520
- if (!(results[name] && Array.isArray(results[name]))) {
38521
- results[name] = [];
38522
- }
38523
- ;
38558
+ if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
38524
38559
  results[name].push(value);
38525
- } else {
38526
- results[name] ??= value;
38527
- }
38560
+ } else results[name] ??= value;
38528
38561
  }
38529
38562
  return key ? results[key] : results;
38530
38563
  };
@@ -38537,36 +38570,35 @@ var decodeURIComponent_ = decodeURIComponent;
38537
38570
  // node_modules/hono/dist/request.js
38538
38571
  var HonoRequest = class {
38539
38572
  /**
38540
- * `.raw` can get the raw Request object.
38541
- *
38542
- * @see {@link https://hono.dev/docs/api/request#raw}
38543
- *
38544
- * @example
38545
- * ```ts
38546
- * // For Cloudflare Workers
38547
- * app.post('/', async (c) => {
38548
- * const metadata = c.req.raw.cf?.hostMetadata?
38549
- * ...
38550
- * })
38551
- * ```
38552
- */
38573
+ * `.raw` can get the raw Request object.
38574
+ *
38575
+ * @see {@link https://hono.dev/docs/api/request#raw}
38576
+ *
38577
+ * @example
38578
+ * ```ts
38579
+ * // For Cloudflare Workers
38580
+ * app.post('/', async (c) => {
38581
+ * const metadata = c.req.raw.cf?.hostMetadata?
38582
+ * ...
38583
+ * })
38584
+ * ```
38585
+ */
38553
38586
  raw;
38554
38587
  #validatedData;
38555
- // Short name of validatedData
38556
38588
  #matchResult;
38557
38589
  routeIndex = 0;
38558
38590
  /**
38559
- * `.path` can get the pathname of the request.
38560
- *
38561
- * @see {@link https://hono.dev/docs/api/request#path}
38562
- *
38563
- * @example
38564
- * ```ts
38565
- * app.get('/about/me', (c) => {
38566
- * const pathname = c.req.path // `/about/me`
38567
- * })
38568
- * ```
38569
- */
38591
+ * `.path` can get the pathname of the request.
38592
+ *
38593
+ * @see {@link https://hono.dev/docs/api/request#path}
38594
+ *
38595
+ * @example
38596
+ * ```ts
38597
+ * app.get('/about/me', (c) => {
38598
+ * const pathname = c.req.path // `/about/me`
38599
+ * })
38600
+ * ```
38601
+ */
38570
38602
  path;
38571
38603
  bodyCache = {};
38572
38604
  constructor(request, path = "/", matchResult = [[]]) {
@@ -38587,9 +38619,7 @@ var HonoRequest = class {
38587
38619
  const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
38588
38620
  for (const key of keys) {
38589
38621
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
38590
- if (value !== void 0) {
38591
- decoded[key] = tryDecodeURIComponent(value);
38592
- }
38622
+ if (value !== void 0) decoded[key] = tryDecodeURIComponent(value);
38593
38623
  }
38594
38624
  return decoded;
38595
38625
  }
@@ -38603,9 +38633,7 @@ var HonoRequest = class {
38603
38633
  return getQueryParams(this.url, key);
38604
38634
  }
38605
38635
  header(name) {
38606
- if (name) {
38607
- return this.raw.headers.get(name) ?? void 0;
38608
- }
38636
+ if (name) return this.raw.headers.get(name) ?? void 0;
38609
38637
  const headerData = /* @__PURE__ */ Object.create(null);
38610
38638
  this.raw.headers.forEach((value, key) => {
38611
38639
  headerData[key] = value;
@@ -38618,146 +38646,140 @@ var HonoRequest = class {
38618
38646
  #cachedBody = (key) => {
38619
38647
  const { bodyCache, raw: raw2 } = this;
38620
38648
  const cachedBody = bodyCache[key];
38621
- if (cachedBody) {
38622
- return cachedBody;
38623
- }
38624
- for (const anyCachedKey in bodyCache) {
38625
- return bodyCache[anyCachedKey].then((body) => {
38626
- if (anyCachedKey === "json") {
38627
- body = JSON.stringify(body);
38628
- }
38629
- return new Response(body)[key]();
38630
- });
38631
- }
38649
+ if (cachedBody) return cachedBody;
38650
+ for (const anyCachedKey in bodyCache) return bodyCache[anyCachedKey].then((body) => {
38651
+ if (anyCachedKey === "json") body = JSON.stringify(body);
38652
+ const contentType = anyCachedKey === "formData" ? void 0 : raw2.headers.get("content-type");
38653
+ return new Response(body, { headers: contentType ? { "Content-Type": contentType } : void 0 })[key]();
38654
+ });
38632
38655
  return bodyCache[key] = raw2[key]();
38633
38656
  };
38634
38657
  /**
38635
- * `.json()` can parse Request body of type `application/json`
38636
- *
38637
- * @see {@link https://hono.dev/docs/api/request#json}
38638
- *
38639
- * @example
38640
- * ```ts
38641
- * app.post('/entry', async (c) => {
38642
- * const body = await c.req.json()
38643
- * })
38644
- * ```
38645
- */
38658
+ * `.json()` can parse Request body of type `application/json`
38659
+ *
38660
+ * @see {@link https://hono.dev/docs/api/request#json}
38661
+ *
38662
+ * @example
38663
+ * ```ts
38664
+ * app.post('/entry', async (c) => {
38665
+ * const body = await c.req.json()
38666
+ * })
38667
+ * ```
38668
+ */
38646
38669
  json() {
38647
38670
  return this.#cachedBody("text").then((text) => JSON.parse(text));
38648
38671
  }
38649
38672
  /**
38650
- * `.text()` can parse Request body of type `text/plain`
38651
- *
38652
- * @see {@link https://hono.dev/docs/api/request#text}
38653
- *
38654
- * @example
38655
- * ```ts
38656
- * app.post('/entry', async (c) => {
38657
- * const body = await c.req.text()
38658
- * })
38659
- * ```
38660
- */
38673
+ * `.text()` can parse Request body of type `text/plain`
38674
+ *
38675
+ * @see {@link https://hono.dev/docs/api/request#text}
38676
+ *
38677
+ * @example
38678
+ * ```ts
38679
+ * app.post('/entry', async (c) => {
38680
+ * const body = await c.req.text()
38681
+ * })
38682
+ * ```
38683
+ */
38661
38684
  text() {
38662
38685
  return this.#cachedBody("text");
38663
38686
  }
38664
38687
  /**
38665
- * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
38666
- *
38667
- * @see {@link https://hono.dev/docs/api/request#arraybuffer}
38668
- *
38669
- * @example
38670
- * ```ts
38671
- * app.post('/entry', async (c) => {
38672
- * const body = await c.req.arrayBuffer()
38673
- * })
38674
- * ```
38675
- */
38688
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
38689
+ *
38690
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
38691
+ *
38692
+ * @example
38693
+ * ```ts
38694
+ * app.post('/entry', async (c) => {
38695
+ * const body = await c.req.arrayBuffer()
38696
+ * })
38697
+ * ```
38698
+ */
38676
38699
  arrayBuffer() {
38677
38700
  return this.#cachedBody("arrayBuffer");
38678
38701
  }
38679
38702
  /**
38680
- * `.bytes()` parses the request body as a `Uint8Array`.
38681
- *
38682
- * @see {@link https://hono.dev/docs/api/request#bytes}
38683
- *
38684
- * @example
38685
- * ```ts
38686
- * app.post('/entry', async (c) => {
38687
- * const body = await c.req.bytes()
38688
- * })
38689
- * ```
38690
- */
38703
+ * `.bytes()` parses the request body as a `Uint8Array`.
38704
+ *
38705
+ * @see {@link https://hono.dev/docs/api/request#bytes}
38706
+ *
38707
+ * @example
38708
+ * ```ts
38709
+ * app.post('/entry', async (c) => {
38710
+ * const body = await c.req.bytes()
38711
+ * })
38712
+ * ```
38713
+ */
38691
38714
  bytes() {
38692
38715
  return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
38693
38716
  }
38694
38717
  /**
38695
- * Parses the request body as a `Blob`.
38696
- * @example
38697
- * ```ts
38698
- * app.post('/entry', async (c) => {
38699
- * const body = await c.req.blob();
38700
- * });
38701
- * ```
38702
- * @see https://hono.dev/docs/api/request#blob
38703
- */
38718
+ * Parses the request body as a `Blob`.
38719
+ * @example
38720
+ * ```ts
38721
+ * app.post('/entry', async (c) => {
38722
+ * const body = await c.req.blob();
38723
+ * });
38724
+ * ```
38725
+ * @see https://hono.dev/docs/api/request#blob
38726
+ */
38704
38727
  blob() {
38705
38728
  return this.#cachedBody("blob");
38706
38729
  }
38707
38730
  /**
38708
- * Parses the request body as `FormData`.
38709
- * @example
38710
- * ```ts
38711
- * app.post('/entry', async (c) => {
38712
- * const body = await c.req.formData();
38713
- * });
38714
- * ```
38715
- * @see https://hono.dev/docs/api/request#formdata
38716
- */
38731
+ * Parses the request body as `FormData`.
38732
+ * @example
38733
+ * ```ts
38734
+ * app.post('/entry', async (c) => {
38735
+ * const body = await c.req.formData();
38736
+ * });
38737
+ * ```
38738
+ * @see https://hono.dev/docs/api/request#formdata
38739
+ */
38717
38740
  formData() {
38718
38741
  return this.#cachedBody("formData");
38719
38742
  }
38720
38743
  /**
38721
- * Adds validated data to the request.
38722
- *
38723
- * @param target - The target of the validation.
38724
- * @param data - The validated data to add.
38725
- */
38744
+ * Adds validated data to the request.
38745
+ *
38746
+ * @param target - The target of the validation.
38747
+ * @param data - The validated data to add.
38748
+ */
38726
38749
  addValidatedData(target, data) {
38727
- ;
38728
38750
  (this.#validatedData ??= {})[target] = data;
38729
38751
  }
38730
38752
  valid(target) {
38731
38753
  return this.#validatedData?.[target];
38732
38754
  }
38733
38755
  /**
38734
- * `.url()` can get the request url strings.
38735
- *
38736
- * @see {@link https://hono.dev/docs/api/request#url}
38737
- *
38738
- * @example
38739
- * ```ts
38740
- * app.get('/about/me', (c) => {
38741
- * const url = c.req.url // `http://localhost:8787/about/me`
38742
- * ...
38743
- * })
38744
- * ```
38745
- */
38756
+ * `.url` can get the request url strings.
38757
+ *
38758
+ * @see {@link https://hono.dev/docs/api/request#url}
38759
+ *
38760
+ * @example
38761
+ * ```ts
38762
+ * app.get('/about/me', (c) => {
38763
+ * const url = c.req.url // `http://localhost:8787/about/me`
38764
+ * ...
38765
+ * })
38766
+ * ```
38767
+ */
38746
38768
  get url() {
38747
38769
  return this.raw.url;
38748
38770
  }
38749
38771
  /**
38750
- * `.method()` can get the method name of the request.
38751
- *
38752
- * @see {@link https://hono.dev/docs/api/request#method}
38753
- *
38754
- * @example
38755
- * ```ts
38756
- * app.get('/about/me', (c) => {
38757
- * const method = c.req.method // `GET`
38758
- * })
38759
- * ```
38760
- */
38772
+ * `.method` can get the method name of the request.
38773
+ *
38774
+ * @see {@link https://hono.dev/docs/api/request#method}
38775
+ *
38776
+ * @example
38777
+ * ```ts
38778
+ * app.get('/about/me', (c) => {
38779
+ * const method = c.req.method // `GET`
38780
+ * })
38781
+ * ```
38782
+ */
38761
38783
  get method() {
38762
38784
  return this.raw.method;
38763
38785
  }
@@ -38765,51 +38787,51 @@ var HonoRequest = class {
38765
38787
  return this.#matchResult;
38766
38788
  }
38767
38789
  /**
38768
- * `.matchedRoutes()` can return a matched route in the handler
38769
- *
38770
- * @deprecated
38771
- *
38772
- * Use matchedRoutes helper defined in "hono/route" instead.
38773
- *
38774
- * @see {@link https://hono.dev/docs/api/request#matchedroutes}
38775
- *
38776
- * @example
38777
- * ```ts
38778
- * app.use('*', async function logger(c, next) {
38779
- * await next()
38780
- * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
38781
- * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
38782
- * console.log(
38783
- * method,
38784
- * ' ',
38785
- * path,
38786
- * ' '.repeat(Math.max(10 - path.length, 0)),
38787
- * name,
38788
- * i === c.req.routeIndex ? '<- respond from here' : ''
38789
- * )
38790
- * })
38791
- * })
38792
- * ```
38793
- */
38790
+ * `.matchedRoutes` can return a matched route in the handler
38791
+ *
38792
+ * @deprecated
38793
+ *
38794
+ * Use matchedRoutes helper defined in "hono/route" instead.
38795
+ *
38796
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
38797
+ *
38798
+ * @example
38799
+ * ```ts
38800
+ * app.use('*', async function logger(c, next) {
38801
+ * await next()
38802
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
38803
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
38804
+ * console.log(
38805
+ * method,
38806
+ * ' ',
38807
+ * path,
38808
+ * ' '.repeat(Math.max(10 - path.length, 0)),
38809
+ * name,
38810
+ * i === c.req.routeIndex ? '<- respond from here' : ''
38811
+ * )
38812
+ * })
38813
+ * })
38814
+ * ```
38815
+ */
38794
38816
  get matchedRoutes() {
38795
38817
  return this.#matchResult[0].map(([[, route]]) => route);
38796
38818
  }
38797
38819
  /**
38798
- * `routePath()` can retrieve the path registered within the handler
38799
- *
38800
- * @deprecated
38801
- *
38802
- * Use routePath helper defined in "hono/route" instead.
38803
- *
38804
- * @see {@link https://hono.dev/docs/api/request#routepath}
38805
- *
38806
- * @example
38807
- * ```ts
38808
- * app.get('/posts/:id', (c) => {
38809
- * return c.json({ path: c.req.routePath })
38810
- * })
38811
- * ```
38812
- */
38820
+ * `.routePath` can retrieve the path registered within the handler
38821
+ *
38822
+ * @deprecated
38823
+ *
38824
+ * Use routePath helper defined in "hono/route" instead.
38825
+ *
38826
+ * @see {@link https://hono.dev/docs/api/request#routepath}
38827
+ *
38828
+ * @example
38829
+ * ```ts
38830
+ * app.get('/posts/:id', (c) => {
38831
+ * return c.json({ path: c.req.routePath })
38832
+ * })
38833
+ * ```
38834
+ */
38813
38835
  get routePath() {
38814
38836
  return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
38815
38837
  }
@@ -38829,32 +38851,20 @@ var raw = (value, callbacks) => {
38829
38851
  };
38830
38852
  var resolveCallback = async (str, phase, preserveCallbacks, context2, buffer) => {
38831
38853
  if (typeof str === "object" && !(str instanceof String)) {
38832
- if (!(str instanceof Promise)) {
38833
- str = str.toString();
38834
- }
38835
- if (str instanceof Promise) {
38836
- str = await str;
38837
- }
38854
+ if (!(str instanceof Promise)) str = str.toString();
38855
+ if (str instanceof Promise) str = await str;
38838
38856
  }
38839
38857
  const callbacks = str.callbacks;
38840
- if (!callbacks?.length) {
38841
- return Promise.resolve(str);
38842
- }
38843
- if (buffer) {
38844
- buffer[0] += str;
38845
- } else {
38846
- buffer = [str];
38847
- }
38848
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context: context2 }))).then(
38849
- (res) => Promise.all(
38850
- res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context2, buffer))
38851
- ).then(() => buffer[0])
38852
- );
38853
- if (preserveCallbacks) {
38854
- return raw(await resStr, callbacks);
38855
- } else {
38856
- return resStr;
38857
- }
38858
+ if (!callbacks?.length) return Promise.resolve(str);
38859
+ if (buffer) buffer[0] += str;
38860
+ else buffer = [str];
38861
+ const resStr = Promise.all(callbacks.map((c) => c({
38862
+ phase,
38863
+ buffer,
38864
+ context: context2
38865
+ }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context2, buffer))).then(() => buffer[0]));
38866
+ if (preserveCallbacks) return raw(await resStr, callbacks);
38867
+ else return resStr;
38858
38868
  };
38859
38869
 
38860
38870
  // node_modules/hono/dist/context.js
@@ -38870,36 +38880,36 @@ var Context = class {
38870
38880
  #rawRequest;
38871
38881
  #req;
38872
38882
  /**
38873
- * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
38874
- *
38875
- * @see {@link https://hono.dev/docs/api/context#env}
38876
- *
38877
- * @example
38878
- * ```ts
38879
- * // Environment object for Cloudflare Workers
38880
- * app.get('*', async c => {
38881
- * const counter = c.env.COUNTER
38882
- * })
38883
- * ```
38884
- */
38883
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
38884
+ *
38885
+ * @see {@link https://hono.dev/docs/api/context#env}
38886
+ *
38887
+ * @example
38888
+ * ```ts
38889
+ * // Environment object for Cloudflare Workers
38890
+ * app.get('*', async c => {
38891
+ * const counter = c.env.COUNTER
38892
+ * })
38893
+ * ```
38894
+ */
38885
38895
  env = {};
38886
38896
  #var;
38887
38897
  finalized = false;
38888
38898
  /**
38889
- * `.error` can get the error object from the middleware if the Handler throws an error.
38890
- *
38891
- * @see {@link https://hono.dev/docs/api/context#error}
38892
- *
38893
- * @example
38894
- * ```ts
38895
- * app.use('*', async (c, next) => {
38896
- * await next()
38897
- * if (c.error) {
38898
- * // do something...
38899
- * }
38900
- * })
38901
- * ```
38902
- */
38899
+ * `.error` can get the error object from the middleware if the Handler throws an error.
38900
+ *
38901
+ * @see {@link https://hono.dev/docs/api/context#error}
38902
+ *
38903
+ * @example
38904
+ * ```ts
38905
+ * app.use('*', async (c, next) => {
38906
+ * await next()
38907
+ * if (c.error) {
38908
+ * // do something...
38909
+ * }
38910
+ * })
38911
+ * ```
38912
+ */
38903
38913
  error;
38904
38914
  #status;
38905
38915
  #executionCtx;
@@ -38911,11 +38921,11 @@ var Context = class {
38911
38921
  #matchResult;
38912
38922
  #path;
38913
38923
  /**
38914
- * Creates an instance of the Context class.
38915
- *
38916
- * @param req - The Request object.
38917
- * @param options - Optional configuration options for the context.
38918
- */
38924
+ * Creates an instance of the Context class.
38925
+ *
38926
+ * @param req - The Request object.
38927
+ * @param options - Optional configuration options for the context.
38928
+ */
38919
38929
  constructor(req, options) {
38920
38930
  this.#rawRequest = req;
38921
38931
  if (options) {
@@ -38927,245 +38937,210 @@ var Context = class {
38927
38937
  }
38928
38938
  }
38929
38939
  /**
38930
- * `.req` is the instance of {@link HonoRequest}.
38931
- */
38940
+ * `.req` is the instance of {@link HonoRequest}.
38941
+ */
38932
38942
  get req() {
38933
38943
  this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
38934
38944
  return this.#req;
38935
38945
  }
38936
38946
  /**
38937
- * @see {@link https://hono.dev/docs/api/context#event}
38938
- * The FetchEvent associated with the current request.
38939
- *
38940
- * @throws Will throw an error if the context does not have a FetchEvent.
38941
- */
38947
+ * @see {@link https://hono.dev/docs/api/context#event}
38948
+ * The FetchEvent associated with the current request.
38949
+ *
38950
+ * @throws Will throw an error if the context does not have a FetchEvent.
38951
+ */
38942
38952
  get event() {
38943
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
38944
- return this.#executionCtx;
38945
- } else {
38946
- throw Error("This context has no FetchEvent");
38947
- }
38953
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) return this.#executionCtx;
38954
+ else throw Error("This context has no FetchEvent");
38948
38955
  }
38949
38956
  /**
38950
- * @see {@link https://hono.dev/docs/api/context#executionctx}
38951
- * The ExecutionContext associated with the current request.
38952
- *
38953
- * @throws Will throw an error if the context does not have an ExecutionContext.
38954
- */
38957
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
38958
+ * The ExecutionContext associated with the current request.
38959
+ *
38960
+ * @throws Will throw an error if the context does not have an ExecutionContext.
38961
+ */
38955
38962
  get executionCtx() {
38956
- if (this.#executionCtx) {
38957
- return this.#executionCtx;
38958
- } else {
38959
- throw Error("This context has no ExecutionContext");
38960
- }
38963
+ if (this.#executionCtx) return this.#executionCtx;
38964
+ else throw Error("This context has no ExecutionContext");
38961
38965
  }
38962
38966
  /**
38963
- * @see {@link https://hono.dev/docs/api/context#res}
38964
- * The Response object for the current request.
38965
- */
38967
+ * @see {@link https://hono.dev/docs/api/context#res}
38968
+ * The Response object for the current request.
38969
+ */
38966
38970
  get res() {
38967
- return this.#res ||= createResponseInstance(null, {
38968
- headers: this.#preparedHeaders ??= new Headers()
38969
- });
38971
+ return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers() });
38970
38972
  }
38971
38973
  /**
38972
- * Sets the Response object for the current request.
38973
- *
38974
- * @param _res - The Response object to set.
38975
- */
38974
+ * Sets the Response object for the current request.
38975
+ *
38976
+ * @param _res - The Response object to set.
38977
+ */
38976
38978
  set res(_res) {
38977
38979
  if (this.#res && _res) {
38978
38980
  _res = createResponseInstance(_res.body, _res);
38979
38981
  for (const [k, v] of this.#res.headers.entries()) {
38980
- if (k === "content-type") {
38981
- continue;
38982
- }
38982
+ if (k === "content-type") continue;
38983
38983
  if (k === "set-cookie") {
38984
38984
  const cookies = this.#res.headers.getSetCookie();
38985
38985
  _res.headers.delete("set-cookie");
38986
- for (const cookie of cookies) {
38987
- _res.headers.append("set-cookie", cookie);
38988
- }
38989
- } else {
38990
- _res.headers.set(k, v);
38991
- }
38986
+ for (const cookie of cookies) _res.headers.append("set-cookie", cookie);
38987
+ } else _res.headers.set(k, v);
38992
38988
  }
38993
38989
  }
38994
38990
  this.#res = _res;
38995
38991
  this.finalized = true;
38996
38992
  }
38997
38993
  /**
38998
- * `.render()` can create a response within a layout.
38999
- *
39000
- * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
39001
- *
39002
- * @example
39003
- * ```ts
39004
- * app.get('/', (c) => {
39005
- * return c.render('Hello!')
39006
- * })
39007
- * ```
39008
- */
38994
+ * `.render()` can create a response within a layout.
38995
+ *
38996
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
38997
+ *
38998
+ * @example
38999
+ * ```ts
39000
+ * app.get('/', (c) => {
39001
+ * return c.render('Hello!')
39002
+ * })
39003
+ * ```
39004
+ */
39009
39005
  render = (...args) => {
39010
39006
  this.#renderer ??= (content) => this.html(content);
39011
39007
  return this.#renderer(...args);
39012
39008
  };
39013
39009
  /**
39014
- * Sets the layout for the response.
39015
- *
39016
- * @param layout - The layout to set.
39017
- * @returns The layout function.
39018
- */
39010
+ * Sets the layout for the response.
39011
+ *
39012
+ * @param layout - The layout to set.
39013
+ * @returns The layout function.
39014
+ */
39019
39015
  setLayout = (layout) => this.#layout = layout;
39020
39016
  /**
39021
- * Gets the current layout for the response.
39022
- *
39023
- * @returns The current layout function.
39024
- */
39017
+ * Gets the current layout for the response.
39018
+ *
39019
+ * @returns The current layout function.
39020
+ */
39025
39021
  getLayout = () => this.#layout;
39026
39022
  /**
39027
- * `.setRenderer()` can set the layout in the custom middleware.
39028
- *
39029
- * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
39030
- *
39031
- * @example
39032
- * ```tsx
39033
- * app.use('*', async (c, next) => {
39034
- * c.setRenderer((content) => {
39035
- * return c.html(
39036
- * <html>
39037
- * <body>
39038
- * <p>{content}</p>
39039
- * </body>
39040
- * </html>
39041
- * )
39042
- * })
39043
- * await next()
39044
- * })
39045
- * ```
39046
- */
39023
+ * `.setRenderer()` can set the layout in the custom middleware.
39024
+ *
39025
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
39026
+ *
39027
+ * @example
39028
+ * ```tsx
39029
+ * app.use('*', async (c, next) => {
39030
+ * c.setRenderer((content) => {
39031
+ * return c.html(
39032
+ * <html>
39033
+ * <body>
39034
+ * <p>{content}</p>
39035
+ * </body>
39036
+ * </html>
39037
+ * )
39038
+ * })
39039
+ * await next()
39040
+ * })
39041
+ * ```
39042
+ */
39047
39043
  setRenderer = (renderer) => {
39048
39044
  this.#renderer = renderer;
39049
39045
  };
39050
39046
  /**
39051
- * `.header()` can set headers.
39052
- *
39053
- * @see {@link https://hono.dev/docs/api/context#header}
39054
- *
39055
- * @example
39056
- * ```ts
39057
- * app.get('/welcome', (c) => {
39058
- * // Set headers
39059
- * c.header('X-Message', 'Hello!')
39060
- * c.header('Content-Type', 'text/plain')
39061
- *
39062
- * // Append multiple headers using the append option (e.g. Vary)
39063
- * c.header('Vary', 'Accept-Encoding', { append: true })
39064
- * c.header('Vary', 'User-Agent', { append: true })
39065
- *
39066
- * return c.body('Thank you for coming')
39067
- * })
39068
- * ```
39069
- */
39047
+ * `.header()` can set headers.
39048
+ *
39049
+ * @see {@link https://hono.dev/docs/api/context#header}
39050
+ *
39051
+ * @example
39052
+ * ```ts
39053
+ * app.get('/welcome', (c) => {
39054
+ * // Set headers
39055
+ * c.header('X-Message', 'Hello!')
39056
+ * c.header('Content-Type', 'text/plain')
39057
+ *
39058
+ * // Append multiple headers using the append option (e.g. Vary)
39059
+ * c.header('Vary', 'Accept-Encoding', { append: true })
39060
+ * c.header('Vary', 'User-Agent', { append: true })
39061
+ *
39062
+ * return c.body('Thank you for coming')
39063
+ * })
39064
+ * ```
39065
+ */
39070
39066
  header = (name, value, options) => {
39071
- if (this.finalized) {
39072
- this.#res = createResponseInstance(this.#res.body, this.#res);
39073
- }
39067
+ if (this.finalized) this.#res = createResponseInstance(this.#res.body, this.#res);
39074
39068
  const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
39075
- if (value === void 0) {
39076
- headers.delete(name);
39077
- } else if (options?.append) {
39078
- headers.append(name, value);
39079
- } else {
39080
- headers.set(name, value);
39081
- }
39069
+ if (value === void 0) headers.delete(name);
39070
+ else if (options?.append) headers.append(name, value);
39071
+ else headers.set(name, value);
39082
39072
  };
39083
39073
  status = (status) => {
39084
39074
  this.#status = status;
39085
39075
  };
39086
39076
  /**
39087
- * `.set()` can set the value specified by the key.
39088
- *
39089
- * @see {@link https://hono.dev/docs/api/context#set-get}
39090
- *
39091
- * @example
39092
- * ```ts
39093
- * app.use('*', async (c, next) => {
39094
- * c.set('message', 'Hono is hot!!')
39095
- * await next()
39096
- * })
39097
- * ```
39098
- */
39077
+ * `.set()` can set the value specified by the key.
39078
+ *
39079
+ * @see {@link https://hono.dev/docs/api/context#set-get}
39080
+ *
39081
+ * @example
39082
+ * ```ts
39083
+ * app.use('*', async (c, next) => {
39084
+ * c.set('message', 'Hono is hot!!')
39085
+ * await next()
39086
+ * })
39087
+ * ```
39088
+ */
39099
39089
  set = (key, value) => {
39100
39090
  this.#var ??= /* @__PURE__ */ new Map();
39101
39091
  this.#var.set(key, value);
39102
39092
  };
39103
39093
  /**
39104
- * `.get()` can use the value specified by the key.
39105
- *
39106
- * @see {@link https://hono.dev/docs/api/context#set-get}
39107
- *
39108
- * @example
39109
- * ```ts
39110
- * app.get('/', (c) => {
39111
- * const message = c.get('message')
39112
- * return c.text(`The message is "${message}"`)
39113
- * })
39114
- * ```
39115
- */
39094
+ * `.get()` can use the value specified by the key.
39095
+ *
39096
+ * @see {@link https://hono.dev/docs/api/context#set-get}
39097
+ *
39098
+ * @example
39099
+ * ```ts
39100
+ * app.get('/', (c) => {
39101
+ * const message = c.get('message')
39102
+ * return c.text(`The message is "${message}"`)
39103
+ * })
39104
+ * ```
39105
+ */
39116
39106
  get = (key) => {
39117
39107
  return this.#var ? this.#var.get(key) : void 0;
39118
39108
  };
39119
39109
  /**
39120
- * `.var` can access the value of a variable.
39121
- *
39122
- * @see {@link https://hono.dev/docs/api/context#var}
39123
- *
39124
- * @example
39125
- * ```ts
39126
- * const result = c.var.client.oneMethod()
39127
- * ```
39128
- */
39129
- // c.var.propName is a read-only
39110
+ * `.var` can access the value of a variable.
39111
+ *
39112
+ * @see {@link https://hono.dev/docs/api/context#var}
39113
+ *
39114
+ * @example
39115
+ * ```ts
39116
+ * const result = c.var.client.oneMethod()
39117
+ * ```
39118
+ */
39130
39119
  get var() {
39131
- if (!this.#var) {
39132
- return {};
39133
- }
39120
+ if (!this.#var) return {};
39134
39121
  return Object.fromEntries(this.#var);
39135
39122
  }
39136
39123
  #newResponse(data, arg, headers) {
39137
39124
  let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
39138
39125
  if (typeof arg === "object" && arg.headers) {
39139
39126
  responseHeaders ??= new Headers();
39140
- for (const [key, value] of new Headers(arg.headers)) {
39141
- if (key === "set-cookie") {
39142
- responseHeaders.append(key, value);
39143
- } else {
39144
- responseHeaders.set(key, value);
39145
- }
39146
- }
39127
+ for (const [key, value] of new Headers(arg.headers)) if (key === "set-cookie") responseHeaders.append(key, value);
39128
+ else responseHeaders.set(key, value);
39147
39129
  }
39148
39130
  if (headers) {
39149
39131
  if (!responseHeaders) {
39150
39132
  let count = 0;
39151
- for (const k in headers) {
39152
- if (++count > 1 || typeof headers[k] !== "string") {
39153
- responseHeaders = new Headers();
39154
- break;
39155
- }
39133
+ for (const k in headers) if (++count > 1 || typeof headers[k] !== "string") {
39134
+ responseHeaders = new Headers();
39135
+ break;
39156
39136
  }
39157
39137
  }
39158
- if (responseHeaders) {
39159
- for (const k in headers) {
39160
- const v = headers[k];
39161
- if (typeof v === "string") {
39162
- responseHeaders.set(k, v);
39163
- } else {
39164
- responseHeaders.delete(k);
39165
- for (const v2 of v) {
39166
- responseHeaders.append(k, v2);
39167
- }
39168
- }
39138
+ if (responseHeaders) for (const k in headers) {
39139
+ const v = headers[k];
39140
+ if (typeof v === "string") responseHeaders.set(k, v);
39141
+ else {
39142
+ responseHeaders.delete(k);
39143
+ for (const v2 of v) responseHeaders.append(k, v2);
39169
39144
  }
39170
39145
  }
39171
39146
  }
@@ -39177,116 +39152,140 @@ var Context = class {
39177
39152
  }
39178
39153
  newResponse = (...args) => this.#newResponse(...args);
39179
39154
  /**
39180
- * `.body()` can return the HTTP response.
39181
- * You can set headers with `.header()` and set HTTP status code with `.status`.
39182
- * This can also be set in `.text()`, `.json()` and so on.
39183
- *
39184
- * @see {@link https://hono.dev/docs/api/context#body}
39185
- *
39186
- * @example
39187
- * ```ts
39188
- * app.get('/welcome', (c) => {
39189
- * // Set headers
39190
- * c.header('X-Message', 'Hello!')
39191
- * c.header('Content-Type', 'text/plain')
39192
- * // Set HTTP status code
39193
- * c.status(201)
39194
- *
39195
- * // Return the response body
39196
- * return c.body('Thank you for coming')
39197
- * })
39198
- * ```
39199
- */
39155
+ * `.body()` can return the HTTP response.
39156
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
39157
+ * This can also be set in `.text()`, `.json()` and so on.
39158
+ *
39159
+ * @see {@link https://hono.dev/docs/api/context#body}
39160
+ *
39161
+ * @example
39162
+ * ```ts
39163
+ * app.get('/welcome', (c) => {
39164
+ * // Set headers
39165
+ * c.header('X-Message', 'Hello!')
39166
+ * c.header('Content-Type', 'text/plain')
39167
+ * // Set HTTP status code
39168
+ * c.status(201)
39169
+ *
39170
+ * // Return the response body
39171
+ * return c.body('Thank you for coming')
39172
+ * })
39173
+ * ```
39174
+ */
39200
39175
  body = (data, arg, headers) => this.#newResponse(data, arg, headers);
39201
39176
  /**
39202
- * `.text()` can render text as `Content-Type:text/plain`.
39203
- *
39204
- * @see {@link https://hono.dev/docs/api/context#text}
39205
- *
39206
- * @example
39207
- * ```ts
39208
- * app.get('/say', (c) => {
39209
- * return c.text('Hello!')
39210
- * })
39211
- * ```
39212
- */
39177
+ * `.text()` can render text as `Content-Type:text/plain`.
39178
+ *
39179
+ * @see {@link https://hono.dev/docs/api/context#text}
39180
+ *
39181
+ * @example
39182
+ * ```ts
39183
+ * app.get('/say', (c) => {
39184
+ * return c.text('Hello!')
39185
+ * })
39186
+ * ```
39187
+ */
39213
39188
  text = (text, arg, headers) => {
39214
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
39215
- text,
39216
- arg,
39217
- setDefaultContentType(TEXT_PLAIN, headers)
39218
- );
39189
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
39219
39190
  };
39220
39191
  /**
39221
- * `.json()` can render JSON as `Content-Type:application/json`.
39222
- *
39223
- * @see {@link https://hono.dev/docs/api/context#json}
39224
- *
39225
- * @example
39226
- * ```ts
39227
- * app.get('/api', (c) => {
39228
- * return c.json({ message: 'Hello!' })
39229
- * })
39230
- * ```
39231
- */
39192
+ * `.json()` can render JSON as `Content-Type:application/json`.
39193
+ *
39194
+ * @see {@link https://hono.dev/docs/api/context#json}
39195
+ *
39196
+ * @example
39197
+ * ```ts
39198
+ * app.get('/api', (c) => {
39199
+ * return c.json({ message: 'Hello!' })
39200
+ * })
39201
+ * ```
39202
+ */
39232
39203
  json = (object2, arg, headers) => {
39233
- return this.#newResponse(
39234
- JSON.stringify(object2),
39235
- arg,
39236
- setDefaultContentType("application/json", headers)
39237
- );
39204
+ return this.#newResponse(JSON.stringify(object2), arg, setDefaultContentType("application/json", headers));
39238
39205
  };
39239
39206
  html = (html, arg, headers) => {
39240
39207
  const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
39241
39208
  return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
39242
39209
  };
39243
39210
  /**
39244
- * `.redirect()` can Redirect, default status code is 302.
39245
- *
39246
- * @see {@link https://hono.dev/docs/api/context#redirect}
39247
- *
39248
- * @example
39249
- * ```ts
39250
- * app.get('/redirect', (c) => {
39251
- * return c.redirect('/')
39252
- * })
39253
- * app.get('/redirect-permanently', (c) => {
39254
- * return c.redirect('/', 301)
39255
- * })
39256
- * ```
39257
- */
39211
+ * `.redirect()` can Redirect, default status code is 302.
39212
+ *
39213
+ * @see {@link https://hono.dev/docs/api/context#redirect}
39214
+ *
39215
+ * @example
39216
+ * ```ts
39217
+ * app.get('/redirect', (c) => {
39218
+ * return c.redirect('/')
39219
+ * })
39220
+ * app.get('/redirect-permanently', (c) => {
39221
+ * return c.redirect('/', 301)
39222
+ * })
39223
+ * ```
39224
+ */
39258
39225
  redirect = (location, status) => {
39259
39226
  const locationString = String(location);
39260
- this.header(
39261
- "Location",
39262
- // Multibyes should be encoded
39263
- // eslint-disable-next-line no-control-regex
39264
- !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
39265
- );
39227
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
39266
39228
  return this.newResponse(null, status ?? 302);
39267
39229
  };
39268
39230
  /**
39269
- * `.notFound()` can return the Not Found Response.
39270
- *
39271
- * @see {@link https://hono.dev/docs/api/context#notfound}
39272
- *
39273
- * @example
39274
- * ```ts
39275
- * app.get('/notfound', (c) => {
39276
- * return c.notFound()
39277
- * })
39278
- * ```
39279
- */
39231
+ * `.notFound()` can return the Not Found Response.
39232
+ *
39233
+ * @see {@link https://hono.dev/docs/api/context#notfound}
39234
+ *
39235
+ * @example
39236
+ * ```ts
39237
+ * app.get('/notfound', (c) => {
39238
+ * return c.notFound()
39239
+ * })
39240
+ * ```
39241
+ */
39280
39242
  notFound = () => {
39281
39243
  this.#notFoundHandler ??= () => createResponseInstance();
39282
39244
  return this.#notFoundHandler(this);
39283
39245
  };
39284
39246
  };
39285
39247
 
39248
+ // node_modules/hono/dist/compose.js
39249
+ var compose = (middleware, onError, onNotFound) => {
39250
+ return (context2, next) => {
39251
+ let index = -1;
39252
+ return dispatch(0);
39253
+ async function dispatch(i) {
39254
+ if (i <= index) throw new Error("next() called multiple times");
39255
+ index = i;
39256
+ let res;
39257
+ let isError = false;
39258
+ let handler;
39259
+ if (middleware[i]) {
39260
+ handler = middleware[i][0][0];
39261
+ context2.req.routeIndex = i;
39262
+ } else handler = i === middleware.length && next || void 0;
39263
+ if (handler) try {
39264
+ res = await handler(context2, () => dispatch(i + 1));
39265
+ } catch (err) {
39266
+ if (err instanceof Error && onError) {
39267
+ context2.error = err;
39268
+ res = await onError(err, context2);
39269
+ isError = true;
39270
+ } else throw err;
39271
+ }
39272
+ else if (context2.finalized === false && onNotFound) res = await onNotFound(context2);
39273
+ if (res && (context2.finalized === false || isError)) context2.res = res;
39274
+ return context2;
39275
+ }
39276
+ };
39277
+ };
39278
+
39286
39279
  // node_modules/hono/dist/router.js
39287
- var METHOD_NAME_ALL = "ALL";
39288
- var METHOD_NAME_ALL_LOWERCASE = "all";
39289
- var METHODS = ["get", "post", "put", "delete", "options", "patch", "query"];
39280
+ var METHODS = [
39281
+ "get",
39282
+ "post",
39283
+ "put",
39284
+ "delete",
39285
+ "options",
39286
+ "patch",
39287
+ "query"
39288
+ ];
39290
39289
  var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
39291
39290
  var UnsupportedPathError = class extends Error {
39292
39291
  };
@@ -39306,7 +39305,7 @@ var errorHandler = (err, c) => {
39306
39305
  console.error(err);
39307
39306
  return c.text("Internal Server Error", 500);
39308
39307
  };
39309
- var Hono = class _Hono {
39308
+ var Hono = class Hono2 {
39310
39309
  get;
39311
39310
  post;
39312
39311
  put;
@@ -39317,26 +39316,17 @@ var Hono = class _Hono {
39317
39316
  all;
39318
39317
  on;
39319
39318
  use;
39320
- /*
39321
- This class is like an abstract class and does not have a router.
39322
- To use it, inherit the class and implement router in the constructor.
39323
- */
39324
39319
  router;
39325
39320
  getPath;
39326
- // Cannot use `#` because it requires visibility at JavaScript runtime.
39327
39321
  _basePath = "/";
39328
39322
  #path = "/";
39329
39323
  routes = [];
39330
39324
  constructor(options = {}) {
39331
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
39332
- allMethods.forEach((method) => {
39325
+ [...METHODS, "all"].forEach((method) => {
39333
39326
  this[method] = (args1, ...args) => {
39334
39327
  const methodName = method.toUpperCase();
39335
- if (typeof args1 === "string") {
39336
- this.#path = args1;
39337
- } else {
39338
- this.#addRoute(methodName, this.#path, args1);
39339
- }
39328
+ if (typeof args1 === "string") this.#path = args1;
39329
+ else this.#addRoute(methodName, this.#path, args1);
39340
39330
  args.forEach((handler) => {
39341
39331
  this.#addRoute(methodName, this.#path, handler);
39342
39332
  });
@@ -39348,22 +39338,19 @@ var Hono = class _Hono {
39348
39338
  this.#path = p;
39349
39339
  for (const m of [method].flat()) {
39350
39340
  const methodName = m.toUpperCase();
39351
- for (const handler of handlers) {
39352
- this.#addRoute(methodName, this.#path, handler);
39353
- }
39341
+ for (const handler of handlers) this.#addRoute(methodName, this.#path, handler);
39354
39342
  }
39355
39343
  }
39356
39344
  return this;
39357
39345
  };
39358
39346
  this.use = (arg1, ...handlers) => {
39359
- if (typeof arg1 === "string") {
39360
- this.#path = arg1;
39361
- } else {
39347
+ if (typeof arg1 === "string") this.#path = arg1;
39348
+ else {
39362
39349
  this.#path = "*";
39363
39350
  handlers.unshift(arg1);
39364
39351
  }
39365
39352
  handlers.forEach((handler) => {
39366
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
39353
+ this.#addRoute("ALL", this.#path, handler);
39367
39354
  });
39368
39355
  return this;
39369
39356
  };
@@ -39372,7 +39359,7 @@ var Hono = class _Hono {
39372
39359
  this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
39373
39360
  }
39374
39361
  #clone() {
39375
- const clone2 = new _Hono({
39362
+ const clone2 = new Hono2({
39376
39363
  router: this.router,
39377
39364
  getPath: this.getPath
39378
39365
  });
@@ -39382,33 +39369,31 @@ var Hono = class _Hono {
39382
39369
  return clone2;
39383
39370
  }
39384
39371
  #notFoundHandler = notFoundHandler;
39385
- // Cannot use `#` because it requires visibility at JavaScript runtime.
39386
39372
  errorHandler = errorHandler;
39387
39373
  /**
39388
- * `.route()` allows grouping other Hono instance in routes.
39389
- *
39390
- * @see {@link https://hono.dev/docs/api/routing#grouping}
39391
- *
39392
- * @param {string} path - base Path
39393
- * @param {Hono} app - other Hono instance
39394
- * @returns {Hono} routed Hono instance
39395
- *
39396
- * @example
39397
- * ```ts
39398
- * const app = new Hono()
39399
- * const app2 = new Hono()
39400
- *
39401
- * app2.get("/user", (c) => c.text("user"))
39402
- * app.route("/api", app2) // GET /api/user
39403
- * ```
39404
- */
39374
+ * `.route()` allows grouping other Hono instance in routes.
39375
+ *
39376
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
39377
+ *
39378
+ * @param {string} path - base Path
39379
+ * @param {Hono} app - other Hono instance
39380
+ * @returns {Hono} routed Hono instance
39381
+ *
39382
+ * @example
39383
+ * ```ts
39384
+ * const app = new Hono()
39385
+ * const app2 = new Hono()
39386
+ *
39387
+ * app2.get("/user", (c) => c.text("user"))
39388
+ * app.route("/api", app2) // GET /api/user
39389
+ * ```
39390
+ */
39405
39391
  route(path, app) {
39406
39392
  const subApp = this.basePath(path);
39407
39393
  app.routes.map((r) => {
39408
39394
  let handler;
39409
- if (app.errorHandler === errorHandler) {
39410
- handler = r.handler;
39411
- } else {
39395
+ if (app.errorHandler === errorHandler) handler = r.handler;
39396
+ else {
39412
39397
  handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
39413
39398
  handler[COMPOSED_HANDLER] = r.handler;
39414
39399
  }
@@ -39417,107 +39402,105 @@ var Hono = class _Hono {
39417
39402
  return this;
39418
39403
  }
39419
39404
  /**
39420
- * `.basePath()` allows base paths to be specified.
39421
- *
39422
- * @see {@link https://hono.dev/docs/api/routing#base-path}
39423
- *
39424
- * @param {string} path - base Path
39425
- * @returns {Hono} changed Hono instance
39426
- *
39427
- * @example
39428
- * ```ts
39429
- * const api = new Hono().basePath('/api')
39430
- * ```
39431
- */
39405
+ * `.basePath()` allows base paths to be specified.
39406
+ *
39407
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
39408
+ *
39409
+ * @param {string} path - base Path
39410
+ * @returns {Hono} changed Hono instance
39411
+ *
39412
+ * @example
39413
+ * ```ts
39414
+ * const api = new Hono().basePath('/api')
39415
+ * ```
39416
+ */
39432
39417
  basePath(path) {
39433
39418
  const subApp = this.#clone();
39434
39419
  subApp._basePath = mergePath(this._basePath, path);
39435
39420
  return subApp;
39436
39421
  }
39437
39422
  /**
39438
- * `.onError()` handles an error and returns a customized Response.
39439
- *
39440
- * @see {@link https://hono.dev/docs/api/hono#error-handling}
39441
- *
39442
- * @param {ErrorHandler} handler - request Handler for error
39443
- * @returns {Hono} changed Hono instance
39444
- *
39445
- * @example
39446
- * ```ts
39447
- * app.onError((err, c) => {
39448
- * console.error(`${err}`)
39449
- * return c.text('Custom Error Message', 500)
39450
- * })
39451
- * ```
39452
- */
39423
+ * `.onError()` handles an error and returns a customized Response.
39424
+ *
39425
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
39426
+ *
39427
+ * @param {ErrorHandler} handler - request Handler for error
39428
+ * @returns {Hono} changed Hono instance
39429
+ *
39430
+ * @example
39431
+ * ```ts
39432
+ * app.onError((err, c) => {
39433
+ * console.error(`${err}`)
39434
+ * return c.text('Custom Error Message', 500)
39435
+ * })
39436
+ * ```
39437
+ */
39453
39438
  onError = (handler) => {
39454
39439
  this.errorHandler = handler;
39455
39440
  return this;
39456
39441
  };
39457
39442
  /**
39458
- * `.notFound()` allows you to customize a Not Found Response.
39459
- *
39460
- * @see {@link https://hono.dev/docs/api/hono#not-found}
39461
- *
39462
- * @param {NotFoundHandler} handler - request handler for not-found
39463
- * @returns {Hono} changed Hono instance
39464
- *
39465
- * @example
39466
- * ```ts
39467
- * app.notFound((c) => {
39468
- * return c.text('Custom 404 Message', 404)
39469
- * })
39470
- * ```
39471
- */
39443
+ * `.notFound()` allows you to customize a Not Found Response.
39444
+ *
39445
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
39446
+ *
39447
+ * @param {NotFoundHandler} handler - request handler for not-found
39448
+ * @returns {Hono} changed Hono instance
39449
+ *
39450
+ * @example
39451
+ * ```ts
39452
+ * app.notFound((c) => {
39453
+ * return c.text('Custom 404 Message', 404)
39454
+ * })
39455
+ * ```
39456
+ */
39472
39457
  notFound = (handler) => {
39473
39458
  this.#notFoundHandler = handler;
39474
39459
  return this;
39475
39460
  };
39476
39461
  /**
39477
- * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
39478
- *
39479
- * @see {@link https://hono.dev/docs/api/hono#mount}
39480
- *
39481
- * @param {string} path - base Path
39482
- * @param {Function} applicationHandler - other Request Handler
39483
- * @param {MountOptions} [options] - options of `.mount()`
39484
- * @returns {Hono} mounted Hono instance
39485
- *
39486
- * @example
39487
- * ```ts
39488
- * import { Router as IttyRouter } from 'itty-router'
39489
- * import { Hono } from 'hono'
39490
- * // Create itty-router application
39491
- * const ittyRouter = IttyRouter()
39492
- * // GET /itty-router/hello
39493
- * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
39494
- *
39495
- * const app = new Hono()
39496
- * app.mount('/itty-router', ittyRouter.handle)
39497
- * ```
39498
- *
39499
- * @example
39500
- * ```ts
39501
- * const app = new Hono()
39502
- * // Send the request to another application without modification.
39503
- * app.mount('/app', anotherApp, {
39504
- * replaceRequest: (req) => req,
39505
- * })
39506
- * ```
39507
- */
39462
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
39463
+ *
39464
+ * @deprecated Use `mount()` from `hono/mount` instead. `.mount()` will be removed in v5.
39465
+ *
39466
+ * @see {@link https://hono.dev/docs/api/hono#mount}
39467
+ *
39468
+ * @param {string} path - base Path
39469
+ * @param {Function} applicationHandler - other Request Handler
39470
+ * @param {MountOptions} [options] - options of `.mount()`
39471
+ * @returns {Hono} mounted Hono instance
39472
+ *
39473
+ * @example
39474
+ * ```ts
39475
+ * import { Router as IttyRouter } from 'itty-router'
39476
+ * import { Hono } from 'hono'
39477
+ * // Create itty-router application
39478
+ * const ittyRouter = IttyRouter()
39479
+ * // GET /itty-router/hello
39480
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
39481
+ *
39482
+ * const app = new Hono()
39483
+ * app.mount('/itty-router', ittyRouter.handle)
39484
+ * ```
39485
+ *
39486
+ * @example
39487
+ * ```ts
39488
+ * const app = new Hono()
39489
+ * // Send the request to another application without modification.
39490
+ * app.mount('/app', anotherApp, {
39491
+ * replaceRequest: (req) => req,
39492
+ * })
39493
+ * ```
39494
+ */
39508
39495
  mount(path, applicationHandler, options) {
39509
39496
  let replaceRequest;
39510
39497
  let optionHandler;
39511
39498
  if (options) {
39512
- if (typeof options === "function") {
39513
- optionHandler = options;
39514
- } else {
39499
+ if (typeof options === "function") optionHandler = options;
39500
+ else {
39515
39501
  optionHandler = options.optionHandler;
39516
- if (options.replaceRequest === false) {
39517
- replaceRequest = (request) => request;
39518
- } else {
39519
- replaceRequest = options.replaceRequest;
39520
- }
39502
+ if (options.replaceRequest === false) replaceRequest = (request) => request;
39503
+ else replaceRequest = options.replaceRequest;
39521
39504
  }
39522
39505
  }
39523
39506
  const getOptions = optionHandler ? (c) => {
@@ -39542,12 +39525,10 @@ var Hono = class _Hono {
39542
39525
  })();
39543
39526
  const handler = async (c, next) => {
39544
39527
  const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
39545
- if (res) {
39546
- return res;
39547
- }
39528
+ if (res) return res;
39548
39529
  await next();
39549
39530
  };
39550
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
39531
+ this.#addRoute("ALL", mergePath(path, "*"), handler);
39551
39532
  return this;
39552
39533
  }
39553
39534
  #addRoute(method, path, handler, baseRoutePath) {
@@ -39562,15 +39543,11 @@ var Hono = class _Hono {
39562
39543
  this.routes.push(r);
39563
39544
  }
39564
39545
  #handleError(err, c) {
39565
- if (err instanceof Error) {
39566
- return this.errorHandler(err, c);
39567
- }
39546
+ if (err instanceof Error) return this.errorHandler(err, c);
39568
39547
  throw err;
39569
39548
  }
39570
39549
  #dispatch(request, executionCtx, env7, method) {
39571
- if (method === "HEAD") {
39572
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env7, "GET")))();
39573
- }
39550
+ if (method === "HEAD") return (async () => new Response(null, await this.#dispatch(request, executionCtx, env7, "GET")))();
39574
39551
  const path = this.getPath(request, { env: env7 });
39575
39552
  const matchResult = this.router.match(method, path);
39576
39553
  const c = new Context(request, {
@@ -39589,19 +39566,13 @@ var Hono = class _Hono {
39589
39566
  } catch (err) {
39590
39567
  return this.#handleError(err, c);
39591
39568
  }
39592
- return res instanceof Promise ? res.then(
39593
- (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
39594
- ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
39569
+ return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
39595
39570
  }
39596
39571
  const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
39597
39572
  return (async () => {
39598
39573
  try {
39599
39574
  const context2 = await composed(c);
39600
- if (!context2.finalized) {
39601
- throw new Error(
39602
- "Context is not finalized. Did you forget to return a Response object or `await next()`?"
39603
- );
39604
- }
39575
+ if (!context2.finalized) throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
39605
39576
  return context2.res;
39606
39577
  } catch (err) {
39607
39578
  return this.#handleError(err, c);
@@ -39609,62 +39580,53 @@ var Hono = class _Hono {
39609
39580
  })();
39610
39581
  }
39611
39582
  /**
39612
- * `.fetch()` will be entry point of your app.
39613
- *
39614
- * @see {@link https://hono.dev/docs/api/hono#fetch}
39615
- *
39616
- * @param {Request} request - request Object of request
39617
- * @param {Env} env - env Object
39618
- * @param {ExecutionContext} executionCtx - context of execution
39619
- * @returns {Response | Promise<Response>} response of request
39620
- *
39621
- */
39583
+ * `.fetch()` will be entry point of your app.
39584
+ *
39585
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
39586
+ *
39587
+ * @param {Request} request - request Object of request
39588
+ * @param {Env} env - env Object
39589
+ * @param {ExecutionContext} executionCtx - context of execution
39590
+ * @returns {Response | Promise<Response>} response of request
39591
+ *
39592
+ */
39622
39593
  fetch = (request, ...rest) => {
39623
39594
  return this.#dispatch(request, rest[1], rest[0], request.method);
39624
39595
  };
39625
39596
  /**
39626
- * `.request()` is a useful method for testing.
39627
- * You can pass a URL or pathname to send a GET request.
39628
- * app will return a Response object.
39629
- * ```ts
39630
- * test('GET /hello is ok', async () => {
39631
- * const res = await app.request('/hello')
39632
- * expect(res.status).toBe(200)
39633
- * })
39634
- * ```
39635
- * @see https://hono.dev/docs/api/hono#request
39636
- */
39597
+ * `.request()` is a useful method for testing.
39598
+ * You can pass a URL or pathname to send a GET request.
39599
+ * app will return a Response object.
39600
+ * ```ts
39601
+ * test('GET /hello is ok', async () => {
39602
+ * const res = await app.request('/hello')
39603
+ * expect(res.status).toBe(200)
39604
+ * })
39605
+ * ```
39606
+ * @see https://hono.dev/docs/api/hono#request
39607
+ */
39637
39608
  request = (input, requestInit, Env, executionCtx) => {
39638
- if (input instanceof Request) {
39639
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
39640
- }
39609
+ if (input instanceof Request) return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
39641
39610
  input = input.toString();
39642
- return this.fetch(
39643
- new Request(
39644
- /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
39645
- requestInit
39646
- ),
39647
- Env,
39648
- executionCtx
39649
- );
39611
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
39650
39612
  };
39651
39613
  /**
39652
- * `.fire()` automatically adds a global fetch event listener.
39653
- * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
39654
- * @deprecated
39655
- * Use `fire` from `hono/service-worker` instead.
39656
- * ```ts
39657
- * import { Hono } from 'hono'
39658
- * import { fire } from 'hono/service-worker'
39659
- *
39660
- * const app = new Hono()
39661
- * // ...
39662
- * fire(app)
39663
- * ```
39664
- * @see https://hono.dev/docs/api/hono#fire
39665
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
39666
- * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
39667
- */
39614
+ * `.fire()` automatically adds a global fetch event listener.
39615
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
39616
+ * @deprecated
39617
+ * Use `fire` from `hono/service-worker` instead.
39618
+ * ```ts
39619
+ * import { Hono } from 'hono'
39620
+ * import { fire } from 'hono/service-worker'
39621
+ *
39622
+ * const app = new Hono()
39623
+ * // ...
39624
+ * fire(app)
39625
+ * ```
39626
+ * @see https://hono.dev/docs/api/hono#fire
39627
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
39628
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
39629
+ */
39668
39630
  fire = () => {
39669
39631
  addEventListener("fetch", (event) => {
39670
39632
  event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
@@ -39680,15 +39642,11 @@ var emptyParam = [];
39680
39642
  function match(method, path) {
39681
39643
  const matchers = this.buildAllMatchers();
39682
39644
  const match2 = ((method2, path2) => {
39683
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
39645
+ const matcher = matchers[method2] || matchers["ALL"];
39684
39646
  const staticMatch = matcher[2][path2];
39685
- if (staticMatch) {
39686
- return staticMatch;
39687
- }
39647
+ if (staticMatch) return staticMatch;
39688
39648
  const match3 = path2.match(matcher[0]);
39689
- if (!match3) {
39690
- return [[], emptyParam];
39691
- }
39649
+ if (!match3) return [[], emptyParam];
39692
39650
  const index = match3.indexOf("", 1);
39693
39651
  return [matcher[1][index], match3];
39694
39652
  });
@@ -39698,31 +39656,19 @@ function match(method, path) {
39698
39656
 
39699
39657
  // node_modules/hono/dist/router/reg-exp-router/node.js
39700
39658
  var LABEL_REG_EXP_STR = "[^/]+";
39701
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
39702
39659
  var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
39703
- var PATH_ERROR = /* @__PURE__ */ Symbol();
39704
- var regExpMetaChars = new Set(".\\+*[^]$()");
39660
+ var PATH_ERROR = Symbol();
39661
+ var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
39705
39662
  function compareKey(a, b) {
39706
- if (a.length === 1) {
39707
- return b.length === 1 ? a < b ? -1 : 1 : -1;
39708
- }
39709
- if (b.length === 1) {
39710
- return 1;
39711
- }
39712
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
39713
- return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1;
39714
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
39715
- return -1;
39716
- }
39717
- if (a === LABEL_REG_EXP_STR) {
39718
- return 1;
39719
- } else if (b === LABEL_REG_EXP_STR) {
39720
- return -1;
39721
- }
39663
+ if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
39664
+ if (b.length === 1) return 1;
39665
+ if (a === ".*" || a === "(?:|/.*)") return b === "(?:|/.*)" ? -1 : 1;
39666
+ else if (b === ".*" || b === "(?:|/.*)") return -1;
39667
+ if (a === "[^/]+") return 1;
39668
+ else if (b === "[^/]+") return -1;
39722
39669
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
39723
39670
  }
39724
- var Node = class _Node {
39725
- // handler index of a dynamic path, or -1 for a static path terminal
39671
+ var Node = class Node2 {
39726
39672
  #index;
39727
39673
  #varIndex;
39728
39674
  #children = createNullObject();
@@ -39730,36 +39676,35 @@ var Node = class _Node {
39730
39676
  let node2 = this;
39731
39677
  for (let i = 0, len = tokens.length; i < len; i++) {
39732
39678
  const token = tokens[i];
39733
- const pattern2 = token.length === 1 ? token === "*" ? i === len - 1 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : null : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
39679
+ const pattern2 = token.length === 1 ? token === "*" ? i === len - 1 ? [
39680
+ "",
39681
+ "",
39682
+ ".*"
39683
+ ] : [
39684
+ "",
39685
+ "",
39686
+ LABEL_REG_EXP_STR
39687
+ ] : null : token === "/*" ? [
39688
+ "",
39689
+ "",
39690
+ TAIL_WILDCARD_REG_EXP_STR
39691
+ ] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
39734
39692
  let nextNode;
39735
39693
  if (pattern2) {
39736
39694
  const name = pattern2[1];
39737
- let regexpStr = pattern2[2] || LABEL_REG_EXP_STR;
39695
+ let regexpStr = pattern2[2] || "[^/]+";
39738
39696
  if (name && pattern2[2]) {
39739
- if (regexpStr === ".*") {
39740
- throw PATH_ERROR;
39741
- }
39697
+ if (regexpStr === ".*") throw PATH_ERROR;
39742
39698
  regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
39743
- if (/\((?!\?:)/.test(regexpStr)) {
39744
- throw PATH_ERROR;
39745
- }
39746
- if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {
39747
- throw PATH_ERROR;
39748
- }
39699
+ if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
39700
+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) throw PATH_ERROR;
39749
39701
  }
39750
39702
  nextNode = node2.#children[regexpStr];
39751
39703
  if (!nextNode) {
39752
- if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {
39753
- for (const k in node2.#children) {
39754
- if (
39755
- // a single-char pattern coexists with single-char literals as a literal does
39756
- (regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
39757
- ) {
39758
- throw PATH_ERROR;
39759
- }
39760
- }
39704
+ if (regexpStr !== ".*" && regexpStr !== "(?:|/.*)") {
39705
+ for (const k in node2.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
39761
39706
  }
39762
- nextNode = node2.#children[regexpStr] = new _Node();
39707
+ nextNode = node2.#children[regexpStr] = new Node2();
39763
39708
  }
39764
39709
  if (name !== "") {
39765
39710
  nextNode.#varIndex ??= context2.varIndex++;
@@ -39768,37 +39713,24 @@ var Node = class _Node {
39768
39713
  } else {
39769
39714
  nextNode = node2.#children[token];
39770
39715
  if (!nextNode) {
39771
- for (const k in node2.#children) {
39772
- if (k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR) {
39773
- throw PATH_ERROR;
39774
- }
39775
- }
39776
- nextNode = node2.#children[token] = new _Node();
39716
+ for (const k in node2.#children) if (k.length > 1 && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
39717
+ nextNode = node2.#children[token] = new Node2();
39777
39718
  }
39778
39719
  }
39779
39720
  node2 = nextNode;
39780
39721
  }
39781
- if (node2.#index !== void 0) {
39782
- throw PATH_ERROR;
39783
- }
39722
+ if (node2.#index !== void 0) throw PATH_ERROR;
39784
39723
  node2.#index = isStatic ? -1 : index;
39785
39724
  }
39786
39725
  buildRegExpStr() {
39787
- const childKeys = Object.keys(this.#children).sort(compareKey);
39788
- const strList = childKeys.map((k) => {
39726
+ const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
39789
39727
  const c = this.#children[k];
39790
39728
  const childStr = c.buildRegExpStr();
39791
39729
  return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
39792
39730
  }).filter(Boolean);
39793
- if (typeof this.#index === "number" && this.#index !== -1) {
39794
- strList.unshift(`#${this.#index}`);
39795
- }
39796
- if (strList.length === 0) {
39797
- return "";
39798
- }
39799
- if (strList.length === 1) {
39800
- return strList[0];
39801
- }
39731
+ if (typeof this.#index === "number" && this.#index !== -1) strList.unshift(`#${this.#index}`);
39732
+ if (strList.length === 0) return "";
39733
+ if (strList.length === 1) return strList[0];
39802
39734
  return "(?:" + strList.join("|") + ")";
39803
39735
  }
39804
39736
  };
@@ -39808,7 +39740,6 @@ var Trie = class {
39808
39740
  #context = { varIndex: 0 };
39809
39741
  #root = new Node();
39810
39742
  #index = 0;
39811
- // dynamic path -> [handler index, param assoc]; static paths are not registered
39812
39743
  paths = createNullObject();
39813
39744
  insert(path, isStatic) {
39814
39745
  if (isStatic) {
@@ -39827,18 +39758,14 @@ var Trie = class {
39827
39758
  replaced = true;
39828
39759
  return mark;
39829
39760
  });
39830
- if (!replaced) {
39831
- break;
39832
- }
39761
+ if (!replaced) break;
39833
39762
  }
39834
39763
  const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
39835
39764
  for (let i = groups.length - 1; i >= 0; i--) {
39836
39765
  const [mark] = groups[i];
39837
- for (let j = tokens.length - 1; j >= 0; j--) {
39838
- if (tokens[j].indexOf(mark) !== -1) {
39839
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
39840
- break;
39841
- }
39766
+ for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
39767
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
39768
+ break;
39842
39769
  }
39843
39770
  }
39844
39771
  this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
@@ -39846,9 +39773,11 @@ var Trie = class {
39846
39773
  }
39847
39774
  buildRegExp() {
39848
39775
  let regexp = this.#root.buildRegExpStr();
39849
- if (regexp === "") {
39850
- return [/^$/, [], []];
39851
- }
39776
+ if (regexp === "") return [
39777
+ /^$/,
39778
+ [],
39779
+ []
39780
+ ];
39852
39781
  let captureIndex = 0;
39853
39782
  const indexReplacementMap = [];
39854
39783
  const paramReplacementMap = [];
@@ -39863,27 +39792,21 @@ var Trie = class {
39863
39792
  }
39864
39793
  return "";
39865
39794
  });
39866
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
39795
+ return [
39796
+ new RegExp(`^${regexp}`),
39797
+ indexReplacementMap,
39798
+ paramReplacementMap
39799
+ ];
39867
39800
  }
39868
39801
  };
39869
39802
 
39870
39803
  // node_modules/hono/dist/router/reg-exp-router/router.js
39871
39804
  var wildcardRegExpCache = createNullObject();
39872
39805
  function buildWildcardRegExp(path) {
39873
- return wildcardRegExpCache[path] ??= new RegExp(
39874
- `^${path.replace(
39875
- /\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,
39876
- (match2, metaChar) => metaChar ? `\\${metaChar}` : match2 === "/*" ? TAIL_WILDCARD_REG_EXP_STR : match2 === "*" ? ONLY_WILDCARD_REG_EXP_STR : `/:${LABEL_REG_EXP_STR}`
39877
- )}$`
39878
- );
39806
+ return wildcardRegExpCache[path] ??= new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g, (match2, metaChar) => metaChar ? `\\${metaChar}` : match2 === "/*" ? TAIL_WILDCARD_REG_EXP_STR : match2 === "*" ? ".*" : `/:${LABEL_REG_EXP_STR}`)}$`);
39879
39807
  }
39880
39808
  function findMiddleware(middleware, path) {
39881
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
39882
- if (buildWildcardRegExp(k).test(path)) {
39883
- return [...middleware[k]];
39884
- }
39885
- }
39886
- return void 0;
39809
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path)) return [...middleware[k]];
39887
39810
  }
39888
39811
  var RegExpRouter = class {
39889
39812
  name = "RegExpRouter";
@@ -39891,9 +39814,9 @@ var RegExpRouter = class {
39891
39814
  #routes;
39892
39815
  #tries;
39893
39816
  constructor() {
39894
- this.#middleware = { [METHOD_NAME_ALL]: createNullObject() };
39895
- this.#routes = { [METHOD_NAME_ALL]: createNullObject() };
39896
- this.#tries = { [METHOD_NAME_ALL]: new Trie() };
39817
+ this.#middleware = { ["ALL"]: createNullObject() };
39818
+ this.#routes = { ["ALL"]: createNullObject() };
39819
+ this.#tries = { ["ALL"]: new Trie() };
39897
39820
  }
39898
39821
  #insertPath(method, path) {
39899
39822
  try {
@@ -39905,57 +39828,41 @@ var RegExpRouter = class {
39905
39828
  add(method, path, handler) {
39906
39829
  const middleware = this.#middleware;
39907
39830
  const routes = this.#routes;
39908
- if (!middleware) {
39909
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
39910
- }
39831
+ if (!middleware) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
39911
39832
  if (!middleware[method]) {
39912
39833
  this.#tries[method] = new Trie();
39913
39834
  for (const handlerMap of [middleware, routes]) {
39914
39835
  handlerMap[method] = createNullObject();
39915
- for (const p in handlerMap[METHOD_NAME_ALL]) {
39916
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
39836
+ for (const p in handlerMap["ALL"]) {
39837
+ handlerMap[method][p] = [...handlerMap["ALL"][p]];
39917
39838
  this.#insertPath(method, p);
39918
39839
  }
39919
39840
  }
39920
39841
  }
39921
- if (path === "/*") {
39922
- path = "*";
39923
- }
39924
- const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method];
39842
+ if (path === "/*") path = "*";
39843
+ const methods = method === "ALL" ? Object.keys(middleware) : [method];
39925
39844
  if (/\*$/.test(path)) {
39926
39845
  const re2 = buildWildcardRegExp(path);
39927
- for (const m of methods) {
39928
- if (!middleware[m][path]) {
39929
- this.#insertPath(m, path);
39930
- middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
39931
- }
39932
- }
39933
- for (const handlerMap of [middleware, routes]) {
39934
- for (const m of methods) {
39935
- for (const p in handlerMap[m]) {
39936
- re2.test(p) && handlerMap[m][p].push([handler, path]);
39937
- }
39938
- }
39846
+ for (const m of methods) if (!middleware[m][path]) {
39847
+ this.#insertPath(m, path);
39848
+ middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
39939
39849
  }
39850
+ for (const handlerMap of [middleware, routes]) for (const m of methods) for (const p in handlerMap[m]) re2.test(p) && handlerMap[m][p].push([handler, path]);
39940
39851
  return;
39941
39852
  }
39942
39853
  const paths = checkOptionalParameter(path) || [path];
39943
- for (const path2 of paths) {
39944
- for (const m of methods) {
39945
- if (!routes[m][path2]) {
39946
- this.#insertPath(m, path2);
39947
- routes[m][path2] = findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [];
39948
- }
39949
- routes[m][path2].push([handler, path2]);
39854
+ for (const path2 of paths) for (const m of methods) {
39855
+ if (!routes[m][path2]) {
39856
+ this.#insertPath(m, path2);
39857
+ routes[m][path2] = findMiddleware(middleware[m], path2) || findMiddleware(middleware["ALL"], path2) || [];
39950
39858
  }
39859
+ routes[m][path2].push([handler, path2]);
39951
39860
  }
39952
39861
  }
39953
39862
  match = match;
39954
39863
  buildAllMatchers() {
39955
39864
  const matchers = createNullObject();
39956
- for (const method of Object.keys(this.#routes)) {
39957
- matchers[method] = this.#buildMatcher(method);
39958
- }
39865
+ for (const method of Object.keys(this.#routes)) matchers[method] = this.#buildMatcher(method);
39959
39866
  this.#middleware = this.#routes = this.#tries = void 0;
39960
39867
  wildcardRegExpCache = createNullObject();
39961
39868
  return matchers;
@@ -39967,24 +39874,23 @@ var RegExpRouter = class {
39967
39874
  const staticMap = createNullObject();
39968
39875
  const handlerData = [];
39969
39876
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
39970
- for (const r of [middleware, routes]) {
39971
- for (const path in r) {
39972
- const handlers = r[path];
39973
- const pathData = trie.paths[path];
39974
- if (!pathData) {
39975
- staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];
39976
- continue;
39977
- }
39978
- handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [
39979
- h,
39980
- trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
39981
- map[key] = paramReplacementMap[pathData[1][i][1]];
39982
- return map;
39983
- }, createNullObject())
39984
- ]);
39877
+ for (const r of [middleware, routes]) for (const path in r) {
39878
+ const handlers = r[path];
39879
+ const pathData = trie.paths[path];
39880
+ if (!pathData) {
39881
+ staticMap[path] = [handlers.map(([h]) => [h, createNullObject()]), emptyParam];
39882
+ continue;
39985
39883
  }
39884
+ handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [h, trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
39885
+ map[key] = paramReplacementMap[pathData[1][i][1]];
39886
+ return map;
39887
+ }, createNullObject())]);
39986
39888
  }
39987
- return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap];
39889
+ return [
39890
+ regexp,
39891
+ indexReplacementMap.map((i) => handlerData[i]),
39892
+ staticMap
39893
+ ];
39988
39894
  }
39989
39895
  };
39990
39896
 
@@ -39997,15 +39903,15 @@ var SmartRouter = class {
39997
39903
  this.#routers = init.routers;
39998
39904
  }
39999
39905
  add(method, path, handler) {
40000
- if (!this.#routes) {
40001
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
40002
- }
40003
- this.#routes.push([method, path, handler]);
39906
+ if (!this.#routes) throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
39907
+ this.#routes.push([
39908
+ method,
39909
+ path,
39910
+ handler
39911
+ ]);
40004
39912
  }
40005
39913
  match(method, path) {
40006
- if (!this.#routes) {
40007
- throw new Error("Fatal error");
40008
- }
39914
+ if (!this.#routes) throw new Error("Fatal error");
40009
39915
  const routers = this.#routers;
40010
39916
  const routes = this.#routes;
40011
39917
  const len = routers.length;
@@ -40014,14 +39920,10 @@ var SmartRouter = class {
40014
39920
  for (; i < len; i++) {
40015
39921
  const router = routers[i];
40016
39922
  try {
40017
- for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
40018
- router.add(...routes[i2]);
40019
- }
39923
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) router.add(...routes[i2]);
40020
39924
  res = router.match(method, path);
40021
39925
  } catch (e) {
40022
- if (e instanceof UnsupportedPathError) {
40023
- continue;
40024
- }
39926
+ if (e instanceof UnsupportedPathError) continue;
40025
39927
  throw e;
40026
39928
  }
40027
39929
  this.match = router.match.bind(router);
@@ -40029,16 +39931,12 @@ var SmartRouter = class {
40029
39931
  this.#routes = void 0;
40030
39932
  break;
40031
39933
  }
40032
- if (i === len) {
40033
- throw new Error("Fatal error");
40034
- }
39934
+ if (i === len) throw new Error("Fatal error");
40035
39935
  this.name = `SmartRouter + ${this.activeRouter.name}`;
40036
39936
  return res;
40037
39937
  }
40038
39938
  get activeRouter() {
40039
- if (this.#routes || this.#routers.length !== 1) {
40040
- throw new Error("No active router has been determined yet.");
40041
- }
39939
+ if (this.#routes || this.#routers.length !== 1) throw new Error("No active router has been determined yet.");
40042
39940
  return this.#routers[0];
40043
39941
  }
40044
39942
  };
@@ -40046,7 +39944,7 @@ var SmartRouter = class {
40046
39944
  // node_modules/hono/dist/router/trie-router/node.js
40047
39945
  var emptyParams = createNullObject();
40048
39946
  var order = 0;
40049
- var Node2 = class _Node2 {
39947
+ var Node3 = class Node4 {
40050
39948
  #methods = [];
40051
39949
  #children = createNullObject();
40052
39950
  #patterns = [];
@@ -40062,28 +39960,24 @@ var Node2 = class _Node2 {
40062
39960
  const pattern2 = getPattern(p, nextP) || (nextP === void 0 && p && p.indexOf("*") === p.length - 1 ? p : null);
40063
39961
  const isParam = Array.isArray(pattern2);
40064
39962
  const key = isParam ? pattern2[0] : pattern2 || p;
40065
- const child = curNode.#children[key] ||= new _Node2();
39963
+ const child = curNode.#children[key] ||= new Node4();
40066
39964
  if (pattern2 && !child.#pattern) {
40067
39965
  child.#pattern = pattern2;
40068
39966
  curNode.#patterns.push(child);
40069
39967
  }
40070
39968
  curNode = child;
40071
- if (isParam) {
40072
- possibleKeys.add(pattern2[1]);
40073
- }
39969
+ if (isParam) possibleKeys.add(pattern2[1]);
40074
39970
  }
40075
- curNode.#methods.push({
40076
- [method]: {
40077
- handler,
40078
- possibleKeys: [...possibleKeys],
40079
- score: ++order
40080
- }
40081
- });
39971
+ curNode.#methods.push({ [method]: {
39972
+ handler,
39973
+ possibleKeys: [...possibleKeys],
39974
+ score: ++order
39975
+ } });
40082
39976
  }
40083
39977
  #pushHandlerSets(handlerSets, node2, method, nodeParams, params) {
40084
39978
  for (let i = 0, len = node2.#methods.length; i < len; i++) {
40085
39979
  const m = node2.#methods[i];
40086
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
39980
+ const handlerSet = m[method] || m["ALL"];
40087
39981
  if (handlerSet) {
40088
39982
  handlerSet.params = createNullObject();
40089
39983
  handlerSets.push(handlerSet);
@@ -40097,8 +39991,7 @@ var Node2 = class _Node2 {
40097
39991
  search(method, path) {
40098
39992
  const handlerSets = [];
40099
39993
  this.#params = emptyParams;
40100
- const curNode = this;
40101
- let curNodes = [curNode];
39994
+ let curNodes = [this];
40102
39995
  const parts = splitPath(path);
40103
39996
  const curNodesQueue = [];
40104
39997
  const len = parts.length;
@@ -40113,13 +40006,9 @@ var Node2 = class _Node2 {
40113
40006
  if (nextNode) {
40114
40007
  nextNode.#params = node2.#params;
40115
40008
  if (isLast) {
40116
- if (nextNode.#children["*"]) {
40117
- this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node2.#params);
40118
- }
40009
+ if (nextNode.#children["*"]) this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node2.#params);
40119
40010
  this.#pushHandlerSets(handlerSets, nextNode, method, node2.#params);
40120
- } else {
40121
- tempNodes.push(nextNode);
40122
- }
40011
+ } else tempNodes.push(nextNode);
40123
40012
  }
40124
40013
  for (const child of node2.#patterns) {
40125
40014
  const pattern2 = child.#pattern;
@@ -40135,9 +40024,7 @@ var Node2 = class _Node2 {
40135
40024
  continue;
40136
40025
  }
40137
40026
  const [, name, matcher] = pattern2;
40138
- if (!part && matcher === true) {
40139
- continue;
40140
- }
40027
+ if (!part && matcher === true) continue;
40141
40028
  if (matcher !== true) {
40142
40029
  if (!partOffsets) {
40143
40030
  partOffsets = [];
@@ -40152,20 +40039,11 @@ var Node2 = class _Node2 {
40152
40039
  if (m) {
40153
40040
  params[name] = m[0];
40154
40041
  this.#pushHandlerSets(handlerSets, child, method, node2.#params, params);
40155
- if (m[0].length === restPathString.length && child.#children["*"]) {
40156
- this.#pushHandlerSets(
40157
- handlerSets,
40158
- child.#children["*"],
40159
- method,
40160
- node2.#params,
40161
- params
40162
- );
40163
- }
40042
+ if (m[0].length === restPathString.length && child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, node2.#params, params);
40164
40043
  for (const _ in child.#children) {
40165
40044
  child.#params = params;
40166
40045
  const componentCount = m[0].match(/\//g)?.length ?? 0;
40167
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
40168
- targetCurNodes.push(child);
40046
+ (curNodesQueue[componentCount] ||= []).push(child);
40169
40047
  break;
40170
40048
  }
40171
40049
  continue;
@@ -40175,15 +40053,7 @@ var Node2 = class _Node2 {
40175
40053
  params[name] = part;
40176
40054
  if (isLast) {
40177
40055
  this.#pushHandlerSets(handlerSets, child, method, params, node2.#params);
40178
- if (child.#children["*"]) {
40179
- this.#pushHandlerSets(
40180
- handlerSets,
40181
- child.#children["*"],
40182
- method,
40183
- params,
40184
- node2.#params
40185
- );
40186
- }
40056
+ if (child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node2.#params);
40187
40057
  } else {
40188
40058
  child.#params = params;
40189
40059
  tempNodes.push(child);
@@ -40194,11 +40064,9 @@ var Node2 = class _Node2 {
40194
40064
  const shifted = curNodesQueue.shift();
40195
40065
  curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
40196
40066
  }
40197
- if (handlerSets[1]) {
40198
- handlerSets.sort((a, b) => {
40199
- return a.score - b.score;
40200
- });
40201
- }
40067
+ if (handlerSets[1]) handlerSets.sort((a, b) => {
40068
+ return a.score - b.score;
40069
+ });
40202
40070
  return [handlerSets.map(({ handler, params }) => [handler, params])];
40203
40071
  }
40204
40072
  };
@@ -40206,11 +40074,9 @@ var Node2 = class _Node2 {
40206
40074
  // node_modules/hono/dist/router/trie-router/router.js
40207
40075
  var TrieRouter = class {
40208
40076
  name = "TrieRouter";
40209
- #node = new Node2();
40077
+ #node = new Node3();
40210
40078
  add(method, path, handler) {
40211
- for (const result of checkOptionalParameter(path) || [path]) {
40212
- this.#node.insert(method, result, handler);
40213
- }
40079
+ for (const result of checkOptionalParameter(path) || [path]) this.#node.insert(method, result, handler);
40214
40080
  }
40215
40081
  match(method, path) {
40216
40082
  return this.#node.search(method, path);
@@ -40218,17 +40084,15 @@ var TrieRouter = class {
40218
40084
  };
40219
40085
 
40220
40086
  // node_modules/hono/dist/hono.js
40221
- var Hono2 = class extends Hono {
40087
+ var Hono3 = class extends Hono {
40222
40088
  /**
40223
- * Creates an instance of the Hono class.
40224
- *
40225
- * @param options - Optional configuration options for the Hono instance.
40226
- */
40089
+ * Creates an instance of the Hono class.
40090
+ *
40091
+ * @param options - Optional configuration options for the Hono instance.
40092
+ */
40227
40093
  constructor(options = {}) {
40228
40094
  super(options);
40229
- this.router = options.router ?? new SmartRouter({
40230
- routers: [new RegExpRouter(), new TrieRouter()]
40231
- });
40095
+ this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] });
40232
40096
  }
40233
40097
  };
40234
40098
 
@@ -40236,7 +40100,15 @@ var Hono2 = class extends Hono {
40236
40100
  var cors = (options) => {
40237
40101
  const opts = {
40238
40102
  origin: "*",
40239
- allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "QUERY"],
40103
+ allowMethods: [
40104
+ "GET",
40105
+ "HEAD",
40106
+ "PUT",
40107
+ "POST",
40108
+ "DELETE",
40109
+ "PATCH",
40110
+ "QUERY"
40111
+ ],
40240
40112
  allowHeaders: [],
40241
40113
  exposeHeaders: [],
40242
40114
  ...options
@@ -40245,58 +40117,35 @@ var cors = (options) => {
40245
40117
  const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(",") : void 0;
40246
40118
  const findAllowOrigin = ((optsOrigin) => {
40247
40119
  if (typeof optsOrigin === "string") {
40248
- if (optsOrigin === "*") {
40249
- return () => optsOrigin;
40250
- } else {
40251
- return (origin) => optsOrigin === origin ? origin : null;
40252
- }
40253
- } else if (typeof optsOrigin === "function") {
40254
- return optsOrigin;
40255
- } else {
40256
- return (origin) => optsOrigin.includes(origin) ? origin : null;
40257
- }
40120
+ if (optsOrigin === "*") return () => optsOrigin;
40121
+ else return (origin) => optsOrigin === origin ? origin : null;
40122
+ } else if (typeof optsOrigin === "function") return optsOrigin;
40123
+ else return (origin) => optsOrigin.includes(origin) ? origin : null;
40258
40124
  })(opts.origin);
40259
40125
  const findAllowMethods = ((optsAllowMethods) => {
40260
- if (typeof optsAllowMethods === "function") {
40261
- return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
40262
- } else if (Array.isArray(optsAllowMethods)) {
40126
+ if (typeof optsAllowMethods === "function") return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
40127
+ else if (Array.isArray(optsAllowMethods)) {
40263
40128
  const methodsStr = optsAllowMethods.join(",");
40264
40129
  return () => methodsStr;
40265
- } else {
40266
- return () => "";
40267
- }
40130
+ } else return () => "";
40268
40131
  })(opts.allowMethods);
40269
40132
  return async function cors2(c, next) {
40270
40133
  function set(key, value) {
40271
40134
  c.res.headers.set(key, value);
40272
40135
  }
40273
40136
  const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
40274
- if (allowOrigin) {
40275
- set("Access-Control-Allow-Origin", allowOrigin);
40276
- }
40277
- if (opts.credentials) {
40278
- set("Access-Control-Allow-Credentials", "true");
40279
- }
40280
- if (exposeHeadersStr) {
40281
- set("Access-Control-Expose-Headers", exposeHeadersStr);
40282
- }
40137
+ if (allowOrigin) set("Access-Control-Allow-Origin", allowOrigin);
40138
+ if (opts.credentials) set("Access-Control-Allow-Credentials", "true");
40139
+ if (exposeHeadersStr) set("Access-Control-Expose-Headers", exposeHeadersStr);
40283
40140
  if (c.req.method === "OPTIONS") {
40284
- if (opts.origin !== "*") {
40285
- c.res.headers.append("Vary", "Origin");
40286
- }
40287
- if (opts.maxAge != null) {
40288
- set("Access-Control-Max-Age", opts.maxAge.toString());
40289
- }
40141
+ if (opts.origin !== "*") c.res.headers.append("Vary", "Origin");
40142
+ if (opts.maxAge != null) set("Access-Control-Max-Age", opts.maxAge.toString());
40290
40143
  const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
40291
- if (allowMethods) {
40292
- set("Access-Control-Allow-Methods", allowMethods);
40293
- }
40144
+ if (allowMethods) set("Access-Control-Allow-Methods", allowMethods);
40294
40145
  let headersStr = allowHeadersStr;
40295
40146
  if (!headersStr) {
40296
40147
  const requestHeaders = c.req.header("Access-Control-Request-Headers");
40297
- if (requestHeaders) {
40298
- headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
40299
- }
40148
+ if (requestHeaders) headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
40300
40149
  }
40301
40150
  if (headersStr) {
40302
40151
  set("Access-Control-Allow-Headers", headersStr);
@@ -40311,9 +40160,7 @@ var cors = (options) => {
40311
40160
  });
40312
40161
  }
40313
40162
  await next();
40314
- if (opts.origin !== "*") {
40315
- c.header("Vary", "Origin", { append: true });
40316
- }
40163
+ if (opts.origin !== "*") c.header("Vary", "Origin", { append: true });
40317
40164
  };
40318
40165
  };
40319
40166
 
@@ -46153,7 +46000,7 @@ var McpApp = class {
46153
46000
  maxRequests: httpRateLimit.maxRequests,
46154
46001
  windowMs: httpRateLimit.windowMs
46155
46002
  }) : null;
46156
- const app = new Hono2();
46003
+ const app = new Hono3();
46157
46004
  const isWildcardCors = corsOrigins === "*" || Array.isArray(corsOrigins) && corsOrigins.includes("*");
46158
46005
  if (enableCors && isWildcardCors) {
46159
46006
  this.log(
@@ -48146,20 +47993,6 @@ async function openBrowser(url2) {
48146
47993
  });
48147
47994
  }
48148
47995
 
48149
- // src/tools/viewer-meta.ts
48150
- var viewer = (name) => ({
48151
- ui: { resourceUri: `ui://mcp-erpnext/${name}` }
48152
- });
48153
- var DOCLIST_META = viewer("doclist-viewer");
48154
- var DOC_META = viewer("doc-viewer");
48155
- var INVOICE_META = viewer("invoice-viewer");
48156
- var STOCK_META = viewer("stock-viewer");
48157
- var CHART_META = viewer("chart-viewer");
48158
- var KANBAN_META = viewer("kanban-viewer");
48159
- var KPI_META = viewer("kpi-viewer");
48160
- var FUNNEL_META = viewer("funnel-viewer");
48161
- var BUY_EVIDENCE_META = viewer("buy-evidence-viewer");
48162
-
48163
47996
  // src/runtime.ts
48164
47997
  var isDeno2 = typeof globalThis.Deno?.version?.deno === "string";
48165
47998
  var impl2 = isDeno2 ? await Promise.resolve().then(() => (init_runtime_deno2(), runtime_deno_exports2)) : await Promise.resolve().then(() => (init_runtime_node2(), runtime_node_exports2));
@@ -48170,6 +48003,7 @@ var readDirSync3 = impl2.readDirSync;
48170
48003
  var getArgs3 = impl2.getArgs;
48171
48004
  var exit3 = impl2.exit;
48172
48005
  var onSignal3 = impl2.onSignal;
48006
+ var netPermission3 = impl2.netPermission;
48173
48007
 
48174
48008
  // src/cache/memory.ts
48175
48009
  var MemoryCache = class {
@@ -49056,6 +48890,129 @@ function getFrappeClient() {
49056
48890
  return _client;
49057
48891
  }
49058
48892
 
48893
+ // src/tools/create-diagnostics.ts
48894
+ var SELLING_DOCTYPES = /* @__PURE__ */ new Set([
48895
+ "Sales Order",
48896
+ "Sales Invoice",
48897
+ "Quotation"
48898
+ ]);
48899
+ var BUYING_DOCTYPES = /* @__PURE__ */ new Set([
48900
+ "Purchase Order",
48901
+ "Purchase Invoice",
48902
+ "Purchase Receipt"
48903
+ ]);
48904
+ var WAREHOUSE_DOCTYPES = /* @__PURE__ */ new Set([
48905
+ "Sales Order",
48906
+ "Sales Invoice",
48907
+ "Purchase Order",
48908
+ "Purchase Invoice",
48909
+ "Purchase Receipt",
48910
+ "Delivery Note",
48911
+ "Stock Entry",
48912
+ "Work Order"
48913
+ ]);
48914
+ var WAREHOUSE_FIELDS = /* @__PURE__ */ new Set([
48915
+ "warehouse",
48916
+ "set_warehouse",
48917
+ "from_warehouse",
48918
+ "to_warehouse",
48919
+ "s_warehouse",
48920
+ "t_warehouse",
48921
+ "wip_warehouse",
48922
+ "fg_warehouse"
48923
+ ]);
48924
+ var RECOVERY_PREFIX = "\nRecovery: ";
48925
+ function isRecord6(value) {
48926
+ return value !== null && typeof value === "object" && !Array.isArray(value);
48927
+ }
48928
+ function mandatoryFields(body, doctype) {
48929
+ if (typeof body.exception !== "string") return [];
48930
+ const match2 = /^(?:frappe\.exceptions\.)?MandatoryError: \[([^,\[\]\r\n]+), [^\[\]\r\n]+\]: ([a-z][a-z0-9_]*(?:, [a-z][a-z0-9_]*)*)$/.exec(body.exception);
48931
+ return match2?.[1] === doctype ? match2[2].split(", ") : [];
48932
+ }
48933
+ function mandatoryRecovery(body, doctype) {
48934
+ const fields = mandatoryFields(body, doctype);
48935
+ const hints = [];
48936
+ if (doctype === "Item" && fields.includes("stock_uom")) {
48937
+ hints.push(
48938
+ "Set stock_uom to an existing UOM; erpnext_item_create exposes this field as uom."
48939
+ );
48940
+ }
48941
+ if (doctype === "Item" && fields.includes("item_group")) {
48942
+ hints.push("Set item_group to an existing Item Group.");
48943
+ }
48944
+ if (SELLING_DOCTYPES.has(doctype) && fields.includes("selling_price_list")) {
48945
+ hints.push(
48946
+ "Set selling_price_list to an enabled selling Price List and check its currency."
48947
+ );
48948
+ }
48949
+ if (doctype === "Price List" && fields.includes("currency")) {
48950
+ hints.push("Set the Price List's currency to an existing Currency.");
48951
+ }
48952
+ if (WAREHOUSE_DOCTYPES.has(doctype) && fields.some((field) => WAREHOUSE_FIELDS.has(field))) {
48953
+ hints.push(
48954
+ "Set the required warehouse fields on the document or indicated item rows, using warehouses for the document's company."
48955
+ );
48956
+ }
48957
+ const general = "Supply the required fields identified by ERPNext, including any indicated child rows; correct the creation data or its defaults.";
48958
+ return [general, ...hints].join(" ");
48959
+ }
48960
+ function hasRaisedDisabledPriceListTitle(body) {
48961
+ if (typeof body._server_messages !== "string") return false;
48962
+ try {
48963
+ const messages = JSON.parse(body._server_messages);
48964
+ if (!Array.isArray(messages)) return false;
48965
+ return messages.some((encoded) => {
48966
+ if (typeof encoded !== "string") return false;
48967
+ const message2 = JSON.parse(encoded);
48968
+ return isRecord6(message2) && message2.title === "Disabled Price List" && (message2.raise_exception === 1 || message2.raise_exception === true);
48969
+ });
48970
+ } catch {
48971
+ return false;
48972
+ }
48973
+ }
48974
+ function recoveryFor(body, doctype, data) {
48975
+ switch (body.exc_type) {
48976
+ case "LinkValidationError":
48977
+ return "Use erpnext_doc_list or erpnext_doc_get to look up the linked documents named by ERPNext, then correct the creation data with their exact existing IDs.";
48978
+ case "MandatoryError":
48979
+ return mandatoryRecovery(body, doctype);
48980
+ case "WarehouseRequired":
48981
+ return doctype === "Sales Order" ? "Set the warehouse on the affected stock item rows, or set_warehouse on the Sales Order, using a warehouse for the order's company." : void 0;
48982
+ case "WarehouseMissingError":
48983
+ return doctype === "Purchase Invoice" && (data.update_stock === 1 || data.update_stock === true) ? "With update_stock enabled, set warehouse on the affected Purchase Invoice item rows using warehouses for the invoice's company." : void 0;
48984
+ case "ValidationError":
48985
+ return (SELLING_DOCTYPES.has(doctype) || BUYING_DOCTYPES.has(doctype)) && hasRaisedDisabledPriceListTitle(body) ? "Choose an enabled Price List for this document's selling or buying side; verify the list named by ERPNext before changing defaults." : void 0;
48986
+ default:
48987
+ return void 0;
48988
+ }
48989
+ }
48990
+ async function createWithDiagnostics(client, doctype, data) {
48991
+ try {
48992
+ return await client.create(doctype, data);
48993
+ } catch (error2) {
48994
+ if (error2 instanceof FrappeAPIError && error2.status === 417 && isRecord6(error2.body) && !error2.message.includes(RECOVERY_PREFIX)) {
48995
+ const recovery = recoveryFor(error2.body, doctype, data);
48996
+ if (recovery) error2.message += `${RECOVERY_PREFIX}${recovery}`;
48997
+ }
48998
+ throw error2;
48999
+ }
49000
+ }
49001
+
49002
+ // src/tools/viewer-meta.ts
49003
+ var viewer = (name) => ({
49004
+ ui: { resourceUri: `ui://mcp-erpnext/${name}` }
49005
+ });
49006
+ var DOCLIST_META = viewer("doclist-viewer");
49007
+ var DOC_META = viewer("doc-viewer");
49008
+ var INVOICE_META = viewer("invoice-viewer");
49009
+ var STOCK_META = viewer("stock-viewer");
49010
+ var CHART_META = viewer("chart-viewer");
49011
+ var KANBAN_META = viewer("kanban-viewer");
49012
+ var KPI_META = viewer("kpi-viewer");
49013
+ var FUNNEL_META = viewer("funnel-viewer");
49014
+ var BUY_EVIDENCE_META = viewer("buy-evidence-viewer");
49015
+
49059
49016
  // src/api/resolve.ts
49060
49017
  var NEGATIVE_CACHE_TTL_MS = 15e3;
49061
49018
  var EXACT_MATCH_PROBE_LIMIT = 2;
@@ -49551,7 +49508,7 @@ var salesTools = [
49551
49508
  if (input.set_warehouse) {
49552
49509
  data.set_warehouse = input.set_warehouse;
49553
49510
  }
49554
- const doc = await ctx.client.create("Sales Order", data);
49511
+ const doc = await createWithDiagnostics(ctx.client, "Sales Order", data);
49555
49512
  return {
49556
49513
  data: viewerDocument(doc, "Sales Order"),
49557
49514
  message: `Sales Order ${doc.name} created successfully`,
@@ -49871,7 +49828,11 @@ var salesTools = [
49871
49828
  if (input.set_warehouse) {
49872
49829
  data.set_warehouse = input.set_warehouse;
49873
49830
  }
49874
- const doc = await ctx.client.create("Sales Invoice", data);
49831
+ const doc = await createWithDiagnostics(
49832
+ ctx.client,
49833
+ "Sales Invoice",
49834
+ data
49835
+ );
49875
49836
  return {
49876
49837
  data: viewerDocument(doc, "Sales Invoice"),
49877
49838
  message: `Sales Invoice ${doc.name} created successfully`,
@@ -50121,7 +50082,7 @@ var salesTools = [
50121
50082
  data.price_list_currency = input.currency;
50122
50083
  data.plc_conversion_rate = 1;
50123
50084
  }
50124
- const doc = await ctx.client.create("Quotation", data);
50085
+ const doc = await createWithDiagnostics(ctx.client, "Quotation", data);
50125
50086
  return {
50126
50087
  data: viewerDocument(doc, "Quotation"),
50127
50088
  message: `Quotation ${doc.name} created successfully`,
@@ -50263,7 +50224,7 @@ var inventoryTools = [
50263
50224
  data.standard_rate = input.standard_rate;
50264
50225
  }
50265
50226
  if (input.description) data.description = input.description;
50266
- const doc = await ctx.client.create("Item", data);
50227
+ const doc = await createWithDiagnostics(ctx.client, "Item", data);
50267
50228
  return {
50268
50229
  data: doc,
50269
50230
  message: `Item ${doc.name} created successfully`
@@ -50572,7 +50533,7 @@ var inventoryTools = [
50572
50533
  if (input.to_warehouse) data.to_warehouse = input.to_warehouse;
50573
50534
  if (input.posting_date) data.posting_date = input.posting_date;
50574
50535
  if (input.remarks) data.remarks = input.remarks;
50575
- const doc = await ctx.client.create("Stock Entry", data);
50536
+ const doc = await createWithDiagnostics(ctx.client, "Stock Entry", data);
50576
50537
  return {
50577
50538
  data: doc,
50578
50539
  message: `Stock Entry ${doc.name} created successfully`
@@ -52526,7 +52487,7 @@ var purchasingTools = [
52526
52487
  };
52527
52488
  }
52528
52489
  );
52529
- const doc = await ctx.client.create("Purchase Order", {
52490
+ const doc = await createWithDiagnostics(ctx.client, "Purchase Order", {
52530
52491
  supplier: await resolveLink(
52531
52492
  ctx.client,
52532
52493
  "Supplier",
@@ -52953,7 +52914,7 @@ var deliveryTools = [
52953
52914
  against_sales_order: item.against_sales_order ?? void 0
52954
52915
  };
52955
52916
  });
52956
- const doc = await ctx.client.create("Delivery Note", {
52917
+ const doc = await createWithDiagnostics(ctx.client, "Delivery Note", {
52957
52918
  customer: input.customer,
52958
52919
  items,
52959
52920
  posting_date: input.posting_date ?? void 0
@@ -53281,7 +53242,7 @@ var manufacturingTools = [
53281
53242
  if (input.qty == null) {
53282
53243
  throw new Error("[erpnext_work_order_create] 'qty' is required");
53283
53244
  }
53284
- const doc = await ctx.client.create("Work Order", {
53245
+ const doc = await createWithDiagnostics(ctx.client, "Work Order", {
53285
53246
  production_item: input.production_item,
53286
53247
  bom_no: input.bom_no,
53287
53248
  qty: input.qty,
@@ -54168,6 +54129,8 @@ function isEmptyPartyAccountCurrencyNone(text) {
54168
54129
  }
54169
54130
 
54170
54131
  // src/tools/operations.ts
54132
+ var DOC_LIST_MAX_LIMIT = 5e3;
54133
+ var DOC_LIST_MAX_OFFSET = 1e5;
54171
54134
  function bytesToBase64(bytes) {
54172
54135
  const chunkSize = 32 * 1024;
54173
54136
  let binary = "";
@@ -54444,7 +54407,8 @@ var operationsTools = [
54444
54407
  }
54445
54408
  const doc = await withPiAccountHintsIfNeeded(
54446
54409
  input.doctype,
54447
- () => ctx.client.create(
54410
+ () => createWithDiagnostics(
54411
+ ctx.client,
54448
54412
  input.doctype,
54449
54413
  input.data
54450
54414
  )
@@ -54675,7 +54639,7 @@ var operationsTools = [
54675
54639
  name: "erpnext_doc_list",
54676
54640
  annotations: { readOnlyHint: true },
54677
54641
  _meta: DOCLIST_META,
54678
- description: "List any ERPNext documents by DocType. Useful for DocTypes not covered by dedicated tools. Supports field selection, filters (as JSON array), and limit.",
54642
+ description: "List any ERPNext documents by DocType. Useful for DocTypes not covered by dedicated tools. Supports field selection, filters (as JSON array), bounded pagination, and an optional fresh read.",
54679
54643
  category: "operations",
54680
54644
  inputSchema: {
54681
54645
  type: "object",
@@ -54739,7 +54703,22 @@ var operationsTools = [
54739
54703
  ]
54740
54704
  }
54741
54705
  },
54742
- limit: { type: "number", description: "Max results (default 20)" },
54706
+ limit: {
54707
+ type: "integer",
54708
+ minimum: 1,
54709
+ maximum: DOC_LIST_MAX_LIMIT,
54710
+ description: "Max results (default 20, maximum 5000)"
54711
+ },
54712
+ offset: {
54713
+ type: "integer",
54714
+ minimum: 0,
54715
+ maximum: DOC_LIST_MAX_OFFSET,
54716
+ description: "Pagination offset (default 0, maximum 100000)"
54717
+ },
54718
+ skip_cache: {
54719
+ type: "boolean",
54720
+ description: "Force a fresh ERPNext read instead of using the short-lived list cache"
54721
+ },
54743
54722
  order_by: {
54744
54723
  type: "string",
54745
54724
  description: "Order by clause (e.g. 'modified desc', 'name asc')"
@@ -54751,16 +54730,34 @@ var operationsTools = [
54751
54730
  if (!input.doctype) {
54752
54731
  throw new Error("[erpnext_doc_list] 'doctype' is required");
54753
54732
  }
54733
+ if (input.limit !== void 0 && (typeof input.limit !== "number" || !Number.isInteger(input.limit) || input.limit < 1 || input.limit > DOC_LIST_MAX_LIMIT)) {
54734
+ throw new Error(
54735
+ `[erpnext_doc_list] 'limit' must be an integer between 1 and ${DOC_LIST_MAX_LIMIT}`
54736
+ );
54737
+ }
54738
+ if (input.offset !== void 0 && (typeof input.offset !== "number" || !Number.isInteger(input.offset) || input.offset < 0 || input.offset > DOC_LIST_MAX_OFFSET)) {
54739
+ throw new Error(
54740
+ `[erpnext_doc_list] 'offset' must be an integer between 0 and ${DOC_LIST_MAX_OFFSET}`
54741
+ );
54742
+ }
54743
+ if (input.skip_cache !== void 0 && typeof input.skip_cache !== "boolean") {
54744
+ throw new Error("[erpnext_doc_list] 'skip_cache' must be a boolean");
54745
+ }
54754
54746
  const limit = input.limit ?? 20;
54755
54747
  const fields = input.fields ?? ["name", "modified"];
54756
54748
  const filters = input.filters ?? [];
54757
54749
  const order_by = input.order_by ?? "modified desc";
54758
- const docs = await ctx.client.list(input.doctype, {
54750
+ const offset = input.offset;
54751
+ const listOptions = {
54759
54752
  fields,
54760
54753
  filters,
54761
54754
  limit,
54755
+ ...offset !== void 0 ? { limit_start: offset } : {},
54762
54756
  order_by
54763
- });
54757
+ };
54758
+ const docs = input.skip_cache === true ? await ctx.client.list(input.doctype, listOptions, {
54759
+ skipCache: true
54760
+ }) : await ctx.client.list(input.doctype, listOptions);
54764
54761
  return {
54765
54762
  doctype: input.doctype,
54766
54763
  count: docs.length,
@@ -55936,8 +55933,8 @@ var analyticsTools = [
55936
55933
  const thisMonthStart = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-01`;
55937
55934
  const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
55938
55935
  const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
55939
- const lastMonthStartStr = lastMonthStart.toISOString().split("T")[0];
55940
- const lastMonthEndStr = lastMonthEnd.toISOString().split("T")[0];
55936
+ const lastMonthStartStr = localCalendarDate(lastMonthStart);
55937
+ const lastMonthEndStr = localCalendarDate(lastMonthEnd);
55941
55938
  const currentOrders = await ctx.client.list("Sales Order", {
55942
55939
  fields: ["grand_total"],
55943
55940
  filters: [
@@ -56457,7 +56454,7 @@ var analyticsTools = [
56457
56454
  now.getMonth() - monthsBack + 1,
56458
56455
  1
56459
56456
  );
56460
- const startStr = startDate.toISOString().split("T")[0];
56457
+ const startStr = localCalendarDate(startDate);
56461
56458
  const [salesOrders, purchaseOrders] = await Promise.all([
56462
56459
  // Sales Orders (income) — submitted only
56463
56460
  ctx.client.list("Sales Order", {
@@ -56496,15 +56493,17 @@ var analyticsTools = [
56496
56493
  const income = new Array(monthsBack).fill(0);
56497
56494
  const expenses = new Array(monthsBack).fill(0);
56498
56495
  for (const so of salesOrders) {
56499
- const d = new Date(so.transaction_date);
56500
- const mIdx = (d.getFullYear() - startDate.getFullYear()) * 12 + d.getMonth() - startDate.getMonth();
56496
+ const calendarMonth = frappeCalendarMonth(so.transaction_date);
56497
+ if (!calendarMonth) continue;
56498
+ const mIdx = (calendarMonth.year - startDate.getFullYear()) * 12 + calendarMonth.month - startDate.getMonth();
56501
56499
  if (mIdx >= 0 && mIdx < monthsBack) {
56502
56500
  income[mIdx] += Number(so.grand_total) || 0;
56503
56501
  }
56504
56502
  }
56505
56503
  for (const po of purchaseOrders) {
56506
- const d = new Date(po.transaction_date);
56507
- const mIdx = (d.getFullYear() - startDate.getFullYear()) * 12 + d.getMonth() - startDate.getMonth();
56504
+ const calendarMonth = frappeCalendarMonth(po.transaction_date);
56505
+ if (!calendarMonth) continue;
56506
+ const mIdx = (calendarMonth.year - startDate.getFullYear()) * 12 + calendarMonth.month - startDate.getMonth();
56508
56507
  if (mIdx >= 0 && mIdx < monthsBack) {
56509
56508
  expenses[mIdx] += Number(po.grand_total) || 0;
56510
56509
  }
@@ -56984,8 +56983,11 @@ function buildOpportunityCard(row) {
56984
56983
  if (isDateOverdue(closingDate) && columnId !== "converted" && columnId !== "closed" && columnId !== "lost") {
56985
56984
  badges.push({ label: "Overdue", tone: "error" });
56986
56985
  }
56987
- if (typeof row.source === "string" && row.source.length > 0) {
56988
- badges.push({ label: row.source, tone: "info" });
56986
+ const source = [row.utm_source, row.source].find(
56987
+ (value) => typeof value === "string" && value.length > 0
56988
+ );
56989
+ if (typeof source === "string") {
56990
+ badges.push({ label: source, tone: "info" });
56989
56991
  }
56990
56992
  const metrics = [];
56991
56993
  if (amountValue) metrics.push({ label: "Amount", value: amountValue });
@@ -57311,6 +57313,38 @@ var issueKanbanAdapter = {
57311
57313
  }
57312
57314
  };
57313
57315
 
57316
+ // src/kanban/opportunity-source.ts
57317
+ function isSourceFieldMessage(value) {
57318
+ if (typeof value !== "string") return false;
57319
+ return /^[^:\r\n]+: source$/.test(value.trim());
57320
+ }
57321
+ function isOpportunitySourceFieldError(error2) {
57322
+ if (!(error2 instanceof FrappeAPIError) || error2.status !== 417 || typeof error2.body !== "object" || error2.body === null) return false;
57323
+ const body = error2.body;
57324
+ if (body.exc_type !== "DataError") return false;
57325
+ if (isSourceFieldMessage(body.message)) return true;
57326
+ if (typeof body._server_messages !== "string") return false;
57327
+ let messages;
57328
+ try {
57329
+ messages = JSON.parse(body._server_messages);
57330
+ } catch {
57331
+ return false;
57332
+ }
57333
+ if (!Array.isArray(messages) || messages.length !== 1) return false;
57334
+ let entry = messages[0];
57335
+ if (typeof entry === "string") {
57336
+ try {
57337
+ entry = JSON.parse(entry);
57338
+ } catch {
57339
+ return isSourceFieldMessage(entry);
57340
+ }
57341
+ }
57342
+ if (typeof entry === "object" && entry !== null) {
57343
+ return isSourceFieldMessage(entry.message);
57344
+ }
57345
+ return isSourceFieldMessage(entry);
57346
+ }
57347
+
57314
57348
  // src/tools/kanban.ts
57315
57349
  var ADAPTERS = {
57316
57350
  task: taskKanbanAdapter,
@@ -57396,13 +57430,27 @@ var kanbanTools = [
57396
57430
  const { definition, adapter } = getAdapter(doctype);
57397
57431
  const limit = Math.max(1, Number(input.limit ?? 50));
57398
57432
  const offset = Math.max(0, Number(input.offset ?? 0));
57399
- const rows = await ctx.client.list(doctype, {
57433
+ const options = {
57400
57434
  fields: adapter.getListFields(),
57401
57435
  filters: adapter.buildListFilters(input),
57402
57436
  limit: limit + 1,
57403
57437
  limit_start: offset,
57404
57438
  order_by: "modified desc"
57405
- });
57439
+ };
57440
+ let rows;
57441
+ try {
57442
+ rows = await ctx.client.list(doctype, options);
57443
+ } catch (error2) {
57444
+ if (doctype !== "Opportunity" || !isOpportunitySourceFieldError(error2)) {
57445
+ throw error2;
57446
+ }
57447
+ rows = await ctx.client.list(doctype, {
57448
+ ...options,
57449
+ fields: options.fields.map(
57450
+ (field) => field === "source" ? "utm_source" : field
57451
+ )
57452
+ });
57453
+ }
57406
57454
  const hasMore = rows.length > limit;
57407
57455
  const visibleRows = rows.slice(0, limit);
57408
57456
  const cards = adapter.buildCards(visibleRows);
@@ -57470,12 +57518,13 @@ var kanbanTools = [
57470
57518
  // src/buy/identities.ts
57471
57519
  var BUY_SOURCE_CAPTURE_SCHEMA = "io.casys.mcp-erpnext.buy-source-capture/1.0";
57472
57520
  var BUY_RECORDED_RESULT_SCHEMA = "io.casys.mcp-erpnext.buy-recorded-result/1.0";
57521
+ var BUY_RECORDED_RESULT_SCHEMA_V2 = "io.casys.mcp-erpnext.buy-recorded-result/2.0";
57473
57522
  var BUY_RECORDED_SESSION_SCHEMA = "io.casys.mcp-erpnext.buy-recorded-session/1.0";
57474
57523
  var BUY_EVIDENCE_VIEWER_URI = "ui://mcp-erpnext/buy-evidence-viewer";
57475
57524
  var BUY_VIEW_APP_MANIFEST_URI = "ui://mcp-erpnext/buy-evidence-manifest";
57476
57525
  var BUY_VIEW_APP_ID = "io.casys.mcp-erpnext.buy-evidence";
57477
57526
  var BUY_VIEW_APP_TITLE = "ERPNext Buy Evidence";
57478
- var BUY_VIEW_APP_VERSION = "3.1.0-beta.9";
57527
+ var BUY_VIEW_APP_VERSION = "3.2.0-beta.1";
57479
57528
  var BUY_SOURCE_INSTANCE_KIND = "erpnext-site";
57480
57529
  var BUY_CAPTURE_DOCTYPE = [
57481
57530
  "Item",
@@ -58859,7 +58908,7 @@ function linkDisambiguationRequestKey(inputPath) {
58859
58908
  function supportsElicitation(context2) {
58860
58909
  return context2?.clientCapabilities?.elicitation !== void 0;
58861
58910
  }
58862
- function isRecord6(value) {
58911
+ function isRecord7(value) {
58863
58912
  return typeof value === "object" && value !== null && !Array.isArray(value);
58864
58913
  }
58865
58914
  function buildInputRequiredSignal(ambiguity, inputPath) {
@@ -58901,7 +58950,7 @@ function selectedRecordId(ambiguity, inputPath, context2) {
58901
58950
  }
58902
58951
  const key = linkDisambiguationRequestKey(inputPath);
58903
58952
  const response = context2.inputResponses?.[key];
58904
- if (!isRecord6(response)) {
58953
+ if (!isRecord7(response)) {
58905
58954
  throw new Error(
58906
58955
  `[link-disambiguation] Missing or invalid response for "${key}".`
58907
58956
  );
@@ -58909,7 +58958,7 @@ function selectedRecordId(ambiguity, inputPath, context2) {
58909
58958
  if (response.action === "cancel" || response.action === "decline") {
58910
58959
  throw new Error("[link-disambiguation] Record selection was declined.");
58911
58960
  }
58912
- if (response.action !== "accept" || !isRecord6(response.content)) {
58961
+ if (response.action !== "accept" || !isRecord7(response.content)) {
58913
58962
  throw new Error(
58914
58963
  `[link-disambiguation] Response for "${key}" must accept a record ID.`
58915
58964
  );
@@ -58950,14 +58999,14 @@ async function runWithLinkDisambiguation(options) {
58950
58999
  }
58951
59000
 
58952
59001
  // src/tools/ui-refresh.ts
58953
- function isRecord7(value) {
59002
+ function isRecord8(value) {
58954
59003
  return typeof value === "object" && value !== null;
58955
59004
  }
58956
59005
  function hasUiResource(result) {
58957
59006
  const meta2 = result._meta;
58958
- if (!isRecord7(meta2)) return false;
59007
+ if (!isRecord8(meta2)) return false;
58959
59008
  const ui = meta2.ui;
58960
- if (!isRecord7(ui)) return false;
59009
+ if (!isRecord8(ui)) return false;
58961
59010
  return typeof ui.resourceUri === "string" && ui.resourceUri.length > 0;
58962
59011
  }
58963
59012
  var DOCTYPE_GET_TOOLS = {
@@ -59751,11 +59800,11 @@ function isFunnelViewer(result) {
59751
59800
  function resultDoctype(result) {
59752
59801
  if (typeof result.doctype === "string") return result.doctype;
59753
59802
  const data = result.data;
59754
- if (isRecord7(data) && typeof data.doctype === "string") return data.doctype;
59803
+ if (isRecord8(data) && typeof data.doctype === "string") return data.doctype;
59755
59804
  return void 0;
59756
59805
  }
59757
59806
  function resultDocument(result) {
59758
- return isRecord7(result.data) ? result.data : void 0;
59807
+ return isRecord8(result.data) ? result.data : void 0;
59759
59808
  }
59760
59809
  function isInvoiceViewer(result) {
59761
59810
  const uri = result._meta?.ui?.resourceUri;
@@ -59959,11 +60008,11 @@ function filterNavJumpsByAvailableTools(result, availableToolNames) {
59959
60008
  return filtered;
59960
60009
  }
59961
60010
  function withViewerToolCapabilities(result, availableToolNames) {
59962
- if (!isRecord7(result) || !hasUiResource(result)) return result;
60011
+ if (!isRecord8(result) || !hasUiResource(result)) return result;
59963
60012
  return filterNavJumpsByAvailableTools(result, availableToolNames);
59964
60013
  }
59965
60014
  function withUiRefreshRequest(result, toolName, args, now = /* @__PURE__ */ new Date(), availableToolNames) {
59966
- if (!isRecord7(result) || !hasUiResource(result)) {
60015
+ if (!isRecord8(result) || !hasUiResource(result)) {
59967
60016
  return result;
59968
60017
  }
59969
60018
  const refreshable = result;
@@ -60046,36 +60095,36 @@ function withUiRefreshRequest(result, toolName, args, now = /* @__PURE__ */ new
60046
60095
  }
60047
60096
 
60048
60097
  // src/client.ts
60049
- function isRecord8(value) {
60098
+ function isRecord9(value) {
60050
60099
  return typeof value === "object" && value !== null && !Array.isArray(value);
60051
60100
  }
60052
60101
  function isSingleEmbeddedBlobResult(value) {
60053
- if (!isRecord8(value) || !Array.isArray(value.content)) return false;
60102
+ if (!isRecord9(value) || !Array.isArray(value.content)) return false;
60054
60103
  if (Object.keys(value).some((key) => key !== "content")) return false;
60055
60104
  if (value.content.length !== 2) return false;
60056
60105
  const [summary, embedded] = value.content;
60057
- if (!isRecord8(summary) || summary.type !== "text" || typeof summary.text !== "string") {
60106
+ if (!isRecord9(summary) || summary.type !== "text" || typeof summary.text !== "string") {
60058
60107
  return false;
60059
60108
  }
60060
- if (!isRecord8(embedded) || embedded.type !== "resource") return false;
60061
- if (!isRecord8(embedded.resource)) return false;
60109
+ if (!isRecord9(embedded) || embedded.type !== "resource") return false;
60110
+ if (!isRecord9(embedded.resource)) return false;
60062
60111
  const resource = embedded.resource;
60063
60112
  return typeof resource.uri === "string" && resource.uri.startsWith("file:///") && typeof resource.mimeType === "string" && typeof resource.blob === "string";
60064
60113
  }
60065
60114
  function withSafeUiRefresh(result, tool, args, availableToolNames) {
60066
60115
  const readOnly = tool.annotations?.readOnlyHint === true;
60067
- if (!isRecord8(result)) {
60116
+ if (!isRecord9(result)) {
60068
60117
  return result;
60069
60118
  }
60070
- const resultMeta = isRecord8(result._meta) ? result._meta : {};
60119
+ const resultMeta = isRecord9(result._meta) ? result._meta : {};
60071
60120
  const declaredUi = tool._meta?.ui;
60072
- const viewerResult = declaredUi && !isRecord8(resultMeta.ui) ? {
60121
+ const viewerResult = declaredUi && !isRecord9(resultMeta.ui) ? {
60073
60122
  ...result,
60074
60123
  _meta: { ...resultMeta, ...tool._meta, ui: declaredUi }
60075
60124
  } : result;
60076
- const request = isRecord8(viewerResult.refreshRequest) ? viewerResult.refreshRequest : null;
60125
+ const request = isRecord9(viewerResult.refreshRequest) ? viewerResult.refreshRequest : null;
60077
60126
  const target = request && typeof request.toolName === "string" ? getToolByName(request.toolName) : void 0;
60078
- const hasSafeExplicitRefresh = request !== null && typeof request.toolName === "string" && availableToolNames.has(request.toolName) && isRecord8(request.arguments) && (request.toolName === tool.name ? readOnly : target?.annotations?.readOnlyHint === true);
60127
+ const hasSafeExplicitRefresh = request !== null && typeof request.toolName === "string" && availableToolNames.has(request.toolName) && isRecord9(request.arguments) && (request.toolName === tool.name ? readOnly : target?.annotations?.readOnlyHint === true);
60079
60128
  if (hasSafeExplicitRefresh) {
60080
60129
  return withUiRefreshRequest(
60081
60130
  viewerResult,
@@ -60249,7 +60298,7 @@ var BUY_VIEW_APP_MANIFEST = {
60249
60298
  resources: [{
60250
60299
  uri: BUY_EVIDENCE_VIEWER_URI,
60251
60300
  ownership: "whole-view",
60252
- resultSchemas: [BUY_RECORDED_RESULT_SCHEMA],
60301
+ resultSchemas: [BUY_RECORDED_RESULT_SCHEMA, BUY_RECORDED_RESULT_SCHEMA_V2],
60253
60302
  acceptedActions: [VIEWER_SESSION_APPLY_ACTION],
60254
60303
  sessionSchemas: [BUY_RECORDED_SESSION_SCHEMA]
60255
60304
  }]
@@ -60313,9 +60362,9 @@ function parseBuyViewAppManifest(value) {
60313
60362
  resource.resultSchemas,
60314
60363
  "Buy View App manifest.resources[0].resultSchemas"
60315
60364
  );
60316
- if (resultSchemas.length !== 1 || resultSchemas[0] !== BUY_RECORDED_RESULT_SCHEMA) {
60365
+ if (resultSchemas.length !== 2 || resultSchemas[0] !== BUY_RECORDED_RESULT_SCHEMA || resultSchemas[1] !== BUY_RECORDED_RESULT_SCHEMA_V2) {
60317
60366
  throw new TypeError(
60318
- "Buy View App manifest result schemas must be io.casys.mcp-erpnext.buy-recorded-result/1.0 exactly."
60367
+ "Buy View App manifest result schemas must list buy-recorded-result/1.0 then /2.0 exactly."
60319
60368
  );
60320
60369
  }
60321
60370
  const acceptedActions = denseArray(
@@ -60340,6 +60389,30 @@ function parseBuyViewAppManifest(value) {
60340
60389
  }
60341
60390
  parseBuyViewAppManifest(BUY_VIEW_APP_MANIFEST);
60342
60391
 
60392
+ // src/ui/viewer-errors.ts
60393
+ var ViewerResourceError = class extends Error {
60394
+ code;
60395
+ retryable;
60396
+ context;
60397
+ recovery;
60398
+ constructor(code, detail, options) {
60399
+ const retryable = options.retryable === true;
60400
+ const context2 = Object.freeze({ ...options.context });
60401
+ super(JSON.stringify({
60402
+ code,
60403
+ message: detail,
60404
+ retryable,
60405
+ context: context2,
60406
+ recovery: options.recovery
60407
+ }));
60408
+ this.name = "ViewerResourceError";
60409
+ this.code = code;
60410
+ this.retryable = retryable;
60411
+ this.context = context2;
60412
+ this.recovery = options.recovery;
60413
+ }
60414
+ };
60415
+
60343
60416
  // src/ui/viewer-resource-paths.ts
60344
60417
  function fileUrlToPath2(url2) {
60345
60418
  const decodedPath = decodeURIComponent(url2.pathname);
@@ -60373,18 +60446,110 @@ function resolveViewerDistPath2(moduleUrl, viewerName, exists) {
60373
60446
  }
60374
60447
  return null;
60375
60448
  }
60376
- async function readViewerDist(location, readLocal, fetchRemote = fetch) {
60449
+ var VIEWER_FETCH_TIMEOUT_MS = 15e3;
60450
+ function remoteViewerNetTarget(location) {
60377
60451
  const url2 = new URL(location, "file:///");
60378
- if (!isRemoteUrl(url2)) {
60379
- return await readLocal(location);
60452
+ if (!isRemoteUrl(url2)) return null;
60453
+ const port = url2.port || (url2.protocol === "https:" ? "443" : "80");
60454
+ return `${url2.hostname}:${port}`;
60455
+ }
60456
+ function isViewerNetAllowed(state) {
60457
+ return state === "granted";
60458
+ }
60459
+ function viewerNetRecovery(hostname) {
60460
+ return `Restart with --allow-net=${hostname} (for example --allow-net=jsr.io), or use the npm package (npx -y @casys/mcp-erpnext).`;
60461
+ }
60462
+ var remoteViewerCache = /* @__PURE__ */ new Map();
60463
+ function errorName(error2) {
60464
+ return typeof error2 === "object" && error2 !== null && "name" in error2 ? String(error2.name) : "";
60465
+ }
60466
+ function toViewerResourceError(error2, location, timeoutMs) {
60467
+ if (error2 instanceof ViewerResourceError) return error2;
60468
+ const url2 = new URL(location);
60469
+ const host = remoteViewerNetTarget(location) ?? url2.host;
60470
+ const name = errorName(error2);
60471
+ if (name === "TimeoutError" || name === "AbortError") {
60472
+ return new ViewerResourceError(
60473
+ "VIEWER_REMOTE_TIMEOUT",
60474
+ "Remote viewer fetch timed out",
60475
+ {
60476
+ retryable: true,
60477
+ context: { url: location, host, timeoutMs },
60478
+ recovery: "Retry; check network access to the host, or use the npm package (npx -y @casys/mcp-erpnext)."
60479
+ }
60480
+ );
60380
60481
  }
60381
- const response = await fetchRemote(location);
60382
- if (!response.ok) {
60383
- throw new Error(
60384
- `Viewer resource fetch failed (${response.status} ${response.statusText})`
60482
+ if (name === "NotCapable" || name === "PermissionDenied") {
60483
+ return new ViewerResourceError(
60484
+ "VIEWER_REMOTE_PERMISSION_DENIED",
60485
+ "Network permission refused for the remote viewer",
60486
+ {
60487
+ retryable: false,
60488
+ context: { url: location, host },
60489
+ recovery: viewerNetRecovery(url2.hostname)
60490
+ }
60385
60491
  );
60386
60492
  }
60387
- return await response.text();
60493
+ return new ViewerResourceError(
60494
+ "VIEWER_REMOTE_NETWORK_ERROR",
60495
+ "Remote viewer fetch failed",
60496
+ {
60497
+ retryable: true,
60498
+ context: { url: location, host },
60499
+ recovery: "Retry; check network access to the host, or use the npm package (npx -y @casys/mcp-erpnext)."
60500
+ }
60501
+ );
60502
+ }
60503
+ async function fetchRemoteViewer(location, fetchRemote, timeoutMs) {
60504
+ const signal = AbortSignal.timeout(timeoutMs);
60505
+ try {
60506
+ const response = await fetchRemote(location, { signal });
60507
+ if (!response.ok) {
60508
+ const status = response.status;
60509
+ throw new ViewerResourceError(
60510
+ "VIEWER_REMOTE_HTTP_ERROR",
60511
+ "Remote viewer fetch returned an error status",
60512
+ {
60513
+ retryable: status >= 500 || status === 429,
60514
+ context: {
60515
+ url: location,
60516
+ host: remoteViewerNetTarget(location) ?? new URL(location).host,
60517
+ status
60518
+ },
60519
+ recovery: status >= 500 || status === 429 ? "Retry later, or use the npm package (npx -y @casys/mcp-erpnext)." : "Check that the published version includes src/ui/dist, or use the npm package (npx -y @casys/mcp-erpnext)."
60520
+ }
60521
+ );
60522
+ }
60523
+ return await new Promise((resolve, reject) => {
60524
+ const onAbort = () => reject(signal.reason);
60525
+ if (signal.aborted) return onAbort();
60526
+ signal.addEventListener("abort", onAbort, { once: true });
60527
+ response.text().then(resolve, reject).finally(
60528
+ () => signal.removeEventListener("abort", onAbort)
60529
+ );
60530
+ });
60531
+ } catch (error2) {
60532
+ throw toViewerResourceError(error2, location, timeoutMs);
60533
+ }
60534
+ }
60535
+ function readViewerDist(location, readLocal, options = {}) {
60536
+ const url2 = new URL(location, "file:///");
60537
+ if (!isRemoteUrl(url2)) {
60538
+ return readLocal(location);
60539
+ }
60540
+ const cache2 = options.cache ?? remoteViewerCache;
60541
+ const cached2 = cache2.get(location);
60542
+ if (cached2) return cached2;
60543
+ const pending = fetchRemoteViewer(
60544
+ location,
60545
+ options.fetchRemote ?? fetch,
60546
+ options.timeoutMs ?? VIEWER_FETCH_TIMEOUT_MS
60547
+ );
60548
+ cache2.set(location, pending);
60549
+ pending.catch(() => {
60550
+ if (cache2.get(location) === pending) cache2.delete(location);
60551
+ });
60552
+ return pending;
60388
60553
  }
60389
60554
 
60390
60555
  // src/auth/composite-provider.ts
@@ -60622,7 +60787,7 @@ async function main() {
60622
60787
  );
60623
60788
  const server = new McpApp({
60624
60789
  name: "mcp-erpnext",
60625
- version: "3.1.0-beta.9",
60790
+ version: "3.2.0-beta.1",
60626
60791
  transport: "stateless",
60627
60792
  cache: {
60628
60793
  ttlMs: 36e5,
@@ -60644,6 +60809,8 @@ async function main() {
60644
60809
  const handlers = toolsClient.buildHandlersMap();
60645
60810
  server.registerTools(mcpTools, handlers);
60646
60811
  registerBuyViewAppManifest(server);
60812
+ const skippedRemoteViewers = [];
60813
+ let skippedRemoteHost = "";
60647
60814
  for (const viewerName of UI_VIEWERS) {
60648
60815
  const distPath = resolveViewerDistPath2(
60649
60816
  import.meta.url,
@@ -60652,7 +60819,11 @@ async function main() {
60652
60819
  );
60653
60820
  const resourceUri = `ui://mcp-erpnext/${viewerName}`;
60654
60821
  const humanName = viewerName.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
60655
- if (distPath) {
60822
+ const remoteTarget = distPath ? remoteViewerNetTarget(distPath) : null;
60823
+ if (distPath && remoteTarget !== null && !isViewerNetAllowed(netPermission3(remoteTarget))) {
60824
+ skippedRemoteViewers.push(viewerName);
60825
+ skippedRemoteHost = new URL(distPath).hostname;
60826
+ } else if (distPath) {
60656
60827
  server.registerResource(
60657
60828
  withViewerResourceMeta({
60658
60829
  uri: resourceUri,
@@ -60676,6 +60847,13 @@ async function main() {
60676
60847
  );
60677
60848
  }
60678
60849
  }
60850
+ if (skippedRemoteViewers.length > 0) {
60851
+ console.error(`[mcp-erpnext] ${JSON.stringify({
60852
+ code: "VIEWER_REMOTE_PERMISSION_DENIED",
60853
+ context: { host: skippedRemoteHost, viewers: skippedRemoteViewers },
60854
+ recovery: viewerNetRecovery(skippedRemoteHost)
60855
+ })}`);
60856
+ }
60679
60857
  console.error(
60680
60858
  `[mcp-erpnext] Initialized \u2014 ${toolsClient.count} tools${categories ? ` (categories: ${categories.join(", ")})` : ""}`
60681
60859
  );
@@ -60730,7 +60908,7 @@ main().catch((err) => {
60730
60908
  });
60731
60909
  /*! Bundled license information:
60732
60910
 
60733
- @modelcontextprotocol/server/dist/src-CX2iR2pK.mjs:
60911
+ @modelcontextprotocol/server/dist/src-Cqbh3MYc.mjs:
60734
60912
  (*!
60735
60913
  * content-type
60736
60914
  * Copyright(c) 2015 Douglas Christopher Wilson