browser-rpc 0.0.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.
Files changed (157) hide show
  1. package/dist/index.js +4187 -0
  2. package/package.json +34 -0
  3. package/web-dist/assets/Arc-R3PUWRPJ-CUdEQO8X.js +1 -0
  4. package/web-dist/assets/Brave-24BM36UM-C6C5mkTK.js +1 -0
  5. package/web-dist/assets/Browser-4R4QKTV2-D3ON1q-S.js +1 -0
  6. package/web-dist/assets/Chrome-TLI42HDP-BgiVz-ma.js +1 -0
  7. package/web-dist/assets/Edge-AZ34LAFM-EBh9cG_z.js +1 -0
  8. package/web-dist/assets/Firefox-ZDK7RHKK-5nyhB0sj.js +1 -0
  9. package/web-dist/assets/Linux-VYP66PDO--MOvpQUa.js +1 -0
  10. package/web-dist/assets/Macos-5QL4JBJE-DLNYPiln.js +1 -0
  11. package/web-dist/assets/Opera-BKMCKUXC-CCypmVaM.js +1 -0
  12. package/web-dist/assets/Safari-PXQIVS6N-B-Lfxb9r.js +1 -0
  13. package/web-dist/assets/Windows-GTAT3OTE-K9Pt3pUF.js +1 -0
  14. package/web-dist/assets/add-Bt6ug9as.js +15 -0
  15. package/web-dist/assets/all-wallets-ClkSG7YV.js +6 -0
  16. package/web-dist/assets/app-store-BnzgCmML.js +17 -0
  17. package/web-dist/assets/apple-D3CNMHuT.js +18 -0
  18. package/web-dist/assets/ar_AR-ZRPPM56D-d2WEfzQ_.js +1349 -0
  19. package/web-dist/assets/arbitrum-IA4OWRTN-B0aI2PBQ.js +1 -0
  20. package/web-dist/assets/arrow-bottom-BrYwqDZR.js +8 -0
  21. package/web-dist/assets/arrow-bottom-circle-CBoHFkqN.js +11 -0
  22. package/web-dist/assets/arrow-left-CHVgplmz.js +8 -0
  23. package/web-dist/assets/arrow-right-Do5EdrXQ.js +8 -0
  24. package/web-dist/assets/arrow-top-BOPLd2d5.js +8 -0
  25. package/web-dist/assets/assets-NU2OP443-COMs-Mo6.js +1 -0
  26. package/web-dist/assets/avalanche-MXEFEDSW-DcC5FNt3.js +1 -0
  27. package/web-dist/assets/bank-DafdJl1O.js +14 -0
  28. package/web-dist/assets/base-Z4LFBE5D-DHfqMzJC.js +1 -0
  29. package/web-dist/assets/basic-CLeG2Fx1.js +2124 -0
  30. package/web-dist/assets/blast-TN2WIMWF-BUZNbRBy.js +1 -0
  31. package/web-dist/assets/browser-DRuHXezx.js +14 -0
  32. package/web-dist/assets/bsc-RVE67I5L-DVYEF0vl.js +1 -0
  33. package/web-dist/assets/card-YgaTGJnf.js +14 -0
  34. package/web-dist/assets/ccip-B4x4TU0w.js +1 -0
  35. package/web-dist/assets/ccip-ConwrR6S.js +1 -0
  36. package/web-dist/assets/celo-E6XU57FO-C5IguUgF.js +1 -0
  37. package/web-dist/assets/checkmark-Dgr_oUfC.js +11 -0
  38. package/web-dist/assets/checkmark-bold-b4BEKMa-.js +8 -0
  39. package/web-dist/assets/chevron-bottom-BlzLXicX.js +8 -0
  40. package/web-dist/assets/chevron-left-DWsjEedN.js +8 -0
  41. package/web-dist/assets/chevron-right-B-GnUH_e.js +8 -0
  42. package/web-dist/assets/chevron-top-lK6t2THp.js +8 -0
  43. package/web-dist/assets/chrome-store-CbBGk8YS.js +61 -0
  44. package/web-dist/assets/clock-ByEA0e_s.js +8 -0
  45. package/web-dist/assets/close-BxDaavrr.js +8 -0
  46. package/web-dist/assets/coinPlaceholder-B9aaOU5j.js +8 -0
  47. package/web-dist/assets/coinbaseWallet-WWX6LF36-BMRj6mTC.js +1 -0
  48. package/web-dist/assets/compass-CBP6oSW9.js +8 -0
  49. package/web-dist/assets/connect-MR6XDLIE-BET5HMNk.js +1 -0
  50. package/web-dist/assets/copy-Dp304nbr.js +15 -0
  51. package/web-dist/assets/core-Bf6VrE6v.js +896 -0
  52. package/web-dist/assets/create-X4WFHLCW-De9pC3ym.js +1 -0
  53. package/web-dist/assets/cronos-ROYR77VZ-Prn3LRPZ.js +1 -0
  54. package/web-dist/assets/cursor-WUohjLCE.js +3 -0
  55. package/web-dist/assets/cursor-transparent-CutfCQQz.js +12 -0
  56. package/web-dist/assets/de_DE-GYZFZXWH-CYZf24IR.js +1349 -0
  57. package/web-dist/assets/desktop-kZiy9C-p.js +9 -0
  58. package/web-dist/assets/disconnect-CG5TDY_m.js +8 -0
  59. package/web-dist/assets/discord-JyHSI7q0.js +17 -0
  60. package/web-dist/assets/es_419-OGVOQEFZ-D6BJPTeQ.js +1349 -0
  61. package/web-dist/assets/ethereum-RFBAMUVK-WsW8NXqo.js +1 -0
  62. package/web-dist/assets/etherscan-CyB1NBm9.js +6 -0
  63. package/web-dist/assets/events-DQ172AOg.js +1 -0
  64. package/web-dist/assets/exclamation-triangle-7y5nglSL.js +4 -0
  65. package/web-dist/assets/extension-BjB3--xE.js +8 -0
  66. package/web-dist/assets/external-link-BW0O7z6_.js +8 -0
  67. package/web-dist/assets/facebook-682BXGmP.js +26 -0
  68. package/web-dist/assets/farcaster-BOaaCMAh.js +12 -0
  69. package/web-dist/assets/filters-DFWbfLJh.js +8 -0
  70. package/web-dist/assets/flow-NBCRNYVF-D2XasjKk.js +1 -0
  71. package/web-dist/assets/fr_FR-Q5QBQBX2-lQoTmpTH.js +1349 -0
  72. package/web-dist/assets/github-DpRqYyal.js +18 -0
  73. package/web-dist/assets/gnosis-T7U5EW2Q-CoPEM_sI.js +1 -0
  74. package/web-dist/assets/google-CgUt7hYq.js +18 -0
  75. package/web-dist/assets/hardhat-NEEC6JX7-DzuWQYyS.js +1 -0
  76. package/web-dist/assets/help-circle-DwVgKpjs.js +12 -0
  77. package/web-dist/assets/hi_IN-7I7LRHGW-CTQjmeYe.js +1349 -0
  78. package/web-dist/assets/id-BaTvs6Gs.js +12 -0
  79. package/web-dist/assets/id_ID-ZMGZ2JFV-CgKQKAmU.js +1349 -0
  80. package/web-dist/assets/image-BieDxoY2.js +4 -0
  81. package/web-dist/assets/index-Burh8TwV.js +47 -0
  82. package/web-dist/assets/index-C4Lbscxg.js +1532 -0
  83. package/web-dist/assets/index-C5m0fBnu.js +7 -0
  84. package/web-dist/assets/index-CteTNahN.js +50 -0
  85. package/web-dist/assets/index-DgKl8WD4.js +9 -0
  86. package/web-dist/assets/index-GJH9xypQ.css +1 -0
  87. package/web-dist/assets/index-My90LZL7.js +1 -0
  88. package/web-dist/assets/index-aVimijSo.js +359 -0
  89. package/web-dist/assets/index.es-Me6_HSoS.js +13 -0
  90. package/web-dist/assets/info-CaUhPhOk.js +3 -0
  91. package/web-dist/assets/info-circle-Dgdf-_kY.js +12 -0
  92. package/web-dist/assets/ja_JP-NYBCHQTZ-CMaBl8Za.js +1349 -0
  93. package/web-dist/assets/klaytn-QTDBZIB3-DyuKTpxX.js +1 -0
  94. package/web-dist/assets/ko_KR-67WE736M-DHWhIjcm.js +1349 -0
  95. package/web-dist/assets/lightbulb-h5NbP99t.js +3 -0
  96. package/web-dist/assets/login-CWDTIDNK-DhDUYE4b.js +1 -0
  97. package/web-dist/assets/mail-DUTW6gdU.js +8 -0
  98. package/web-dist/assets/manta-5V6W5D7G-BnjsGzeJ.js +1 -0
  99. package/web-dist/assets/mantle-KBL3OIYT-DIpe0poV.js +1 -0
  100. package/web-dist/assets/metaMaskWallet-YFHEHW7V-BggUDXad.js +1 -0
  101. package/web-dist/assets/mobile-BFFFlSgH.js +9 -0
  102. package/web-dist/assets/more-s9g8TvGr.js +11 -0
  103. package/web-dist/assets/ms_MY-65AJIBUS-BLlUrxe6.js +1349 -0
  104. package/web-dist/assets/network-placeholder-DBVOULy6.js +14 -0
  105. package/web-dist/assets/nftPlaceholder-D8q6GiE5.js +8 -0
  106. package/web-dist/assets/off-7mG5bayL.js +8 -0
  107. package/web-dist/assets/optimism-VD7XDD2W-DpJY1TMb.js +1 -0
  108. package/web-dist/assets/play-store-BFa605Jk.js +32 -0
  109. package/web-dist/assets/plus-BgZ-WP7A.js +13 -0
  110. package/web-dist/assets/polygon-WWEUOMKW-CNBYSB1T.js +1 -0
  111. package/web-dist/assets/pt_BR-DMJANC65-DMs4DrlC.js +1349 -0
  112. package/web-dist/assets/qr-code-B_1WHzPs.js +6 -0
  113. package/web-dist/assets/rainbowWallet-2SR6TVBF-kimcGeuf.js +1 -0
  114. package/web-dist/assets/recycle-horizontal-CuuA7YIy.js +9 -0
  115. package/web-dist/assets/refresh-CSXbxAuT.js +8 -0
  116. package/web-dist/assets/refresh-HJGJRASX-D0rkc63_.js +1 -0
  117. package/web-dist/assets/reown-logo-OK1pdOfH.js +12 -0
  118. package/web-dist/assets/ronin-PNHX5V6H-BS-WPXjQ.js +1 -0
  119. package/web-dist/assets/ru_RU-WER7RQ6A-DsJK55uv.js +1349 -0
  120. package/web-dist/assets/safeWallet-VUYZPLY4-CXnodgMs.js +1 -0
  121. package/web-dist/assets/scan-DEOT2M37-1-mJ5OyF.js +1 -0
  122. package/web-dist/assets/scroll-NMZWDUQH-fIxBV-y0.js +1 -0
  123. package/web-dist/assets/search-b77MGgNN.js +8 -0
  124. package/web-dist/assets/secp256k1-CqlnLpBV.js +1 -0
  125. package/web-dist/assets/secp256k1-xC50DJGj.js +1 -0
  126. package/web-dist/assets/send-DlJtxaMX.js +15 -0
  127. package/web-dist/assets/sign-A7IJEUT5-CGsRnPrd.js +1 -0
  128. package/web-dist/assets/swapHorizontal-BmG4i-CJ.js +8 -0
  129. package/web-dist/assets/swapHorizontalBold-CrnzAaq6.js +8 -0
  130. package/web-dist/assets/swapHorizontalMedium-DuPE93B2.js +16 -0
  131. package/web-dist/assets/swapHorizontalRoundedBold-clkEaP-W.js +8 -0
  132. package/web-dist/assets/swapVertical-DXvCmf9g.js +8 -0
  133. package/web-dist/assets/telegram-uHX2mx77.js +16 -0
  134. package/web-dist/assets/th_TH-JOSHEZ6D-Cp87mIRZ.js +1349 -0
  135. package/web-dist/assets/three-dots-BoFVtYRM.js +5 -0
  136. package/web-dist/assets/tr_TR-EAMG2YPO-C52_xfsf.js +1349 -0
  137. package/web-dist/assets/twitch-BbZVXa-k.js +18 -0
  138. package/web-dist/assets/twitterIcon-DTDEnPwP.js +6 -0
  139. package/web-dist/assets/uk_UA-GO2TRVWA-C1C1400t.js +1349 -0
  140. package/web-dist/assets/verify-DSwt0ow9.js +8 -0
  141. package/web-dist/assets/verify-filled-Dd2saJZ0.js +8 -0
  142. package/web-dist/assets/vi_VN-5HLLSOJA-Dj7ferOp.js +1349 -0
  143. package/web-dist/assets/w3m-modal-Dkca-GXY.js +642 -0
  144. package/web-dist/assets/wallet-DFQUKIzv.js +8 -0
  145. package/web-dist/assets/wallet-placeholder-DBESmMOJ.js +14 -0
  146. package/web-dist/assets/walletConnectWallet-FNSU4KNU-B0ci71fU.js +1 -0
  147. package/web-dist/assets/walletconnect-Byk_h0ya.js +30 -0
  148. package/web-dist/assets/warning-circle-BjOhgUMO.js +12 -0
  149. package/web-dist/assets/x-qhswnC92.js +12 -0
  150. package/web-dist/assets/xdc-X7V4QFNF-CSGs0o6M.js +1 -0
  151. package/web-dist/assets/zetachain-BMJKVYBN-IK2CZBr3.js +1 -0
  152. package/web-dist/assets/zh_CN-THPIFVWJ-Cbp71xMR.js +1349 -0
  153. package/web-dist/assets/zh_HK-R7XP4TGF-CyJtfKGw.js +1349 -0
  154. package/web-dist/assets/zh_TW-F5LD752V-AHFgsYw-.js +1349 -0
  155. package/web-dist/assets/zkSync-JL26RB7U-BYMs9Lzo.js +1 -0
  156. package/web-dist/assets/zora-YZH32HP3-CY3tp3EJ.js +1 -0
  157. package/web-dist/index.html +13 -0
package/dist/index.js ADDED
@@ -0,0 +1,4187 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import { createRequire } from "node:module";
4
+ var __create = Object.create;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __toESM = (mod, isNodeMode, target) => {
10
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
11
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
12
+ for (let key of __getOwnPropNames(mod))
13
+ if (!__hasOwnProp.call(to, key))
14
+ __defProp(to, key, {
15
+ get: () => mod[key],
16
+ enumerable: true
17
+ });
18
+ return to;
19
+ };
20
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
21
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
22
+
23
+ // ../../node_modules/commander/lib/error.js
24
+ var require_error = __commonJS((exports) => {
25
+ class CommanderError extends Error {
26
+ constructor(exitCode, code, message) {
27
+ super(message);
28
+ Error.captureStackTrace(this, this.constructor);
29
+ this.name = this.constructor.name;
30
+ this.code = code;
31
+ this.exitCode = exitCode;
32
+ this.nestedError = undefined;
33
+ }
34
+ }
35
+
36
+ class InvalidArgumentError extends CommanderError {
37
+ constructor(message) {
38
+ super(1, "commander.invalidArgument", message);
39
+ Error.captureStackTrace(this, this.constructor);
40
+ this.name = this.constructor.name;
41
+ }
42
+ }
43
+ exports.CommanderError = CommanderError;
44
+ exports.InvalidArgumentError = InvalidArgumentError;
45
+ });
46
+
47
+ // ../../node_modules/commander/lib/argument.js
48
+ var require_argument = __commonJS((exports) => {
49
+ var { InvalidArgumentError } = require_error();
50
+
51
+ class Argument {
52
+ constructor(name, description) {
53
+ this.description = description || "";
54
+ this.variadic = false;
55
+ this.parseArg = undefined;
56
+ this.defaultValue = undefined;
57
+ this.defaultValueDescription = undefined;
58
+ this.argChoices = undefined;
59
+ switch (name[0]) {
60
+ case "<":
61
+ this.required = true;
62
+ this._name = name.slice(1, -1);
63
+ break;
64
+ case "[":
65
+ this.required = false;
66
+ this._name = name.slice(1, -1);
67
+ break;
68
+ default:
69
+ this.required = true;
70
+ this._name = name;
71
+ break;
72
+ }
73
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
74
+ this.variadic = true;
75
+ this._name = this._name.slice(0, -3);
76
+ }
77
+ }
78
+ name() {
79
+ return this._name;
80
+ }
81
+ _concatValue(value, previous) {
82
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
83
+ return [value];
84
+ }
85
+ return previous.concat(value);
86
+ }
87
+ default(value, description) {
88
+ this.defaultValue = value;
89
+ this.defaultValueDescription = description;
90
+ return this;
91
+ }
92
+ argParser(fn) {
93
+ this.parseArg = fn;
94
+ return this;
95
+ }
96
+ choices(values) {
97
+ this.argChoices = values.slice();
98
+ this.parseArg = (arg, previous) => {
99
+ if (!this.argChoices.includes(arg)) {
100
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
101
+ }
102
+ if (this.variadic) {
103
+ return this._concatValue(arg, previous);
104
+ }
105
+ return arg;
106
+ };
107
+ return this;
108
+ }
109
+ argRequired() {
110
+ this.required = true;
111
+ return this;
112
+ }
113
+ argOptional() {
114
+ this.required = false;
115
+ return this;
116
+ }
117
+ }
118
+ function humanReadableArgName(arg) {
119
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
120
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
121
+ }
122
+ exports.Argument = Argument;
123
+ exports.humanReadableArgName = humanReadableArgName;
124
+ });
125
+
126
+ // ../../node_modules/commander/lib/help.js
127
+ var require_help = __commonJS((exports) => {
128
+ var { humanReadableArgName } = require_argument();
129
+
130
+ class Help {
131
+ constructor() {
132
+ this.helpWidth = undefined;
133
+ this.sortSubcommands = false;
134
+ this.sortOptions = false;
135
+ this.showGlobalOptions = false;
136
+ }
137
+ visibleCommands(cmd) {
138
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
139
+ const helpCommand = cmd._getHelpCommand();
140
+ if (helpCommand && !helpCommand._hidden) {
141
+ visibleCommands.push(helpCommand);
142
+ }
143
+ if (this.sortSubcommands) {
144
+ visibleCommands.sort((a, b) => {
145
+ return a.name().localeCompare(b.name());
146
+ });
147
+ }
148
+ return visibleCommands;
149
+ }
150
+ compareOptions(a, b) {
151
+ const getSortKey = (option) => {
152
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
153
+ };
154
+ return getSortKey(a).localeCompare(getSortKey(b));
155
+ }
156
+ visibleOptions(cmd) {
157
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
158
+ const helpOption = cmd._getHelpOption();
159
+ if (helpOption && !helpOption.hidden) {
160
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
161
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
162
+ if (!removeShort && !removeLong) {
163
+ visibleOptions.push(helpOption);
164
+ } else if (helpOption.long && !removeLong) {
165
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
166
+ } else if (helpOption.short && !removeShort) {
167
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
168
+ }
169
+ }
170
+ if (this.sortOptions) {
171
+ visibleOptions.sort(this.compareOptions);
172
+ }
173
+ return visibleOptions;
174
+ }
175
+ visibleGlobalOptions(cmd) {
176
+ if (!this.showGlobalOptions)
177
+ return [];
178
+ const globalOptions = [];
179
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
180
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
181
+ globalOptions.push(...visibleOptions);
182
+ }
183
+ if (this.sortOptions) {
184
+ globalOptions.sort(this.compareOptions);
185
+ }
186
+ return globalOptions;
187
+ }
188
+ visibleArguments(cmd) {
189
+ if (cmd._argsDescription) {
190
+ cmd.registeredArguments.forEach((argument) => {
191
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
192
+ });
193
+ }
194
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
195
+ return cmd.registeredArguments;
196
+ }
197
+ return [];
198
+ }
199
+ subcommandTerm(cmd) {
200
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
201
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
202
+ }
203
+ optionTerm(option) {
204
+ return option.flags;
205
+ }
206
+ argumentTerm(argument) {
207
+ return argument.name();
208
+ }
209
+ longestSubcommandTermLength(cmd, helper) {
210
+ return helper.visibleCommands(cmd).reduce((max, command) => {
211
+ return Math.max(max, helper.subcommandTerm(command).length);
212
+ }, 0);
213
+ }
214
+ longestOptionTermLength(cmd, helper) {
215
+ return helper.visibleOptions(cmd).reduce((max, option) => {
216
+ return Math.max(max, helper.optionTerm(option).length);
217
+ }, 0);
218
+ }
219
+ longestGlobalOptionTermLength(cmd, helper) {
220
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
221
+ return Math.max(max, helper.optionTerm(option).length);
222
+ }, 0);
223
+ }
224
+ longestArgumentTermLength(cmd, helper) {
225
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
226
+ return Math.max(max, helper.argumentTerm(argument).length);
227
+ }, 0);
228
+ }
229
+ commandUsage(cmd) {
230
+ let cmdName = cmd._name;
231
+ if (cmd._aliases[0]) {
232
+ cmdName = cmdName + "|" + cmd._aliases[0];
233
+ }
234
+ let ancestorCmdNames = "";
235
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
236
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
237
+ }
238
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
239
+ }
240
+ commandDescription(cmd) {
241
+ return cmd.description();
242
+ }
243
+ subcommandDescription(cmd) {
244
+ return cmd.summary() || cmd.description();
245
+ }
246
+ optionDescription(option) {
247
+ const extraInfo = [];
248
+ if (option.argChoices) {
249
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
250
+ }
251
+ if (option.defaultValue !== undefined) {
252
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
253
+ if (showDefault) {
254
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
255
+ }
256
+ }
257
+ if (option.presetArg !== undefined && option.optional) {
258
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
259
+ }
260
+ if (option.envVar !== undefined) {
261
+ extraInfo.push(`env: ${option.envVar}`);
262
+ }
263
+ if (extraInfo.length > 0) {
264
+ return `${option.description} (${extraInfo.join(", ")})`;
265
+ }
266
+ return option.description;
267
+ }
268
+ argumentDescription(argument) {
269
+ const extraInfo = [];
270
+ if (argument.argChoices) {
271
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
272
+ }
273
+ if (argument.defaultValue !== undefined) {
274
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
275
+ }
276
+ if (extraInfo.length > 0) {
277
+ const extraDescripton = `(${extraInfo.join(", ")})`;
278
+ if (argument.description) {
279
+ return `${argument.description} ${extraDescripton}`;
280
+ }
281
+ return extraDescripton;
282
+ }
283
+ return argument.description;
284
+ }
285
+ formatHelp(cmd, helper) {
286
+ const termWidth = helper.padWidth(cmd, helper);
287
+ const helpWidth = helper.helpWidth || 80;
288
+ const itemIndentWidth = 2;
289
+ const itemSeparatorWidth = 2;
290
+ function formatItem(term, description) {
291
+ if (description) {
292
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
293
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
294
+ }
295
+ return term;
296
+ }
297
+ function formatList(textArray) {
298
+ return textArray.join(`
299
+ `).replace(/^/gm, " ".repeat(itemIndentWidth));
300
+ }
301
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
302
+ const commandDescription = helper.commandDescription(cmd);
303
+ if (commandDescription.length > 0) {
304
+ output = output.concat([
305
+ helper.wrap(commandDescription, helpWidth, 0),
306
+ ""
307
+ ]);
308
+ }
309
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
310
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
311
+ });
312
+ if (argumentList.length > 0) {
313
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
314
+ }
315
+ const optionList = helper.visibleOptions(cmd).map((option) => {
316
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
317
+ });
318
+ if (optionList.length > 0) {
319
+ output = output.concat(["Options:", formatList(optionList), ""]);
320
+ }
321
+ if (this.showGlobalOptions) {
322
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
323
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
324
+ });
325
+ if (globalOptionList.length > 0) {
326
+ output = output.concat([
327
+ "Global Options:",
328
+ formatList(globalOptionList),
329
+ ""
330
+ ]);
331
+ }
332
+ }
333
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
334
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
335
+ });
336
+ if (commandList.length > 0) {
337
+ output = output.concat(["Commands:", formatList(commandList), ""]);
338
+ }
339
+ return output.join(`
340
+ `);
341
+ }
342
+ padWidth(cmd, helper) {
343
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
344
+ }
345
+ wrap(str, width, indent, minColumnWidth = 40) {
346
+ const indents = " \\f\\t\\v   -    \uFEFF";
347
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
348
+ if (str.match(manualIndent))
349
+ return str;
350
+ const columnWidth = width - indent;
351
+ if (columnWidth < minColumnWidth)
352
+ return str;
353
+ const leadingStr = str.slice(0, indent);
354
+ const columnText = str.slice(indent).replace(`\r
355
+ `, `
356
+ `);
357
+ const indentString = " ".repeat(indent);
358
+ const zeroWidthSpace = "​";
359
+ const breaks = `\\s${zeroWidthSpace}`;
360
+ const regex = new RegExp(`
361
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
362
+ const lines = columnText.match(regex) || [];
363
+ return leadingStr + lines.map((line, i) => {
364
+ if (line === `
365
+ `)
366
+ return "";
367
+ return (i > 0 ? indentString : "") + line.trimEnd();
368
+ }).join(`
369
+ `);
370
+ }
371
+ }
372
+ exports.Help = Help;
373
+ });
374
+
375
+ // ../../node_modules/commander/lib/option.js
376
+ var require_option = __commonJS((exports) => {
377
+ var { InvalidArgumentError } = require_error();
378
+
379
+ class Option {
380
+ constructor(flags, description) {
381
+ this.flags = flags;
382
+ this.description = description || "";
383
+ this.required = flags.includes("<");
384
+ this.optional = flags.includes("[");
385
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
386
+ this.mandatory = false;
387
+ const optionFlags = splitOptionFlags(flags);
388
+ this.short = optionFlags.shortFlag;
389
+ this.long = optionFlags.longFlag;
390
+ this.negate = false;
391
+ if (this.long) {
392
+ this.negate = this.long.startsWith("--no-");
393
+ }
394
+ this.defaultValue = undefined;
395
+ this.defaultValueDescription = undefined;
396
+ this.presetArg = undefined;
397
+ this.envVar = undefined;
398
+ this.parseArg = undefined;
399
+ this.hidden = false;
400
+ this.argChoices = undefined;
401
+ this.conflictsWith = [];
402
+ this.implied = undefined;
403
+ }
404
+ default(value, description) {
405
+ this.defaultValue = value;
406
+ this.defaultValueDescription = description;
407
+ return this;
408
+ }
409
+ preset(arg) {
410
+ this.presetArg = arg;
411
+ return this;
412
+ }
413
+ conflicts(names) {
414
+ this.conflictsWith = this.conflictsWith.concat(names);
415
+ return this;
416
+ }
417
+ implies(impliedOptionValues) {
418
+ let newImplied = impliedOptionValues;
419
+ if (typeof impliedOptionValues === "string") {
420
+ newImplied = { [impliedOptionValues]: true };
421
+ }
422
+ this.implied = Object.assign(this.implied || {}, newImplied);
423
+ return this;
424
+ }
425
+ env(name) {
426
+ this.envVar = name;
427
+ return this;
428
+ }
429
+ argParser(fn) {
430
+ this.parseArg = fn;
431
+ return this;
432
+ }
433
+ makeOptionMandatory(mandatory = true) {
434
+ this.mandatory = !!mandatory;
435
+ return this;
436
+ }
437
+ hideHelp(hide = true) {
438
+ this.hidden = !!hide;
439
+ return this;
440
+ }
441
+ _concatValue(value, previous) {
442
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
443
+ return [value];
444
+ }
445
+ return previous.concat(value);
446
+ }
447
+ choices(values) {
448
+ this.argChoices = values.slice();
449
+ this.parseArg = (arg, previous) => {
450
+ if (!this.argChoices.includes(arg)) {
451
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
452
+ }
453
+ if (this.variadic) {
454
+ return this._concatValue(arg, previous);
455
+ }
456
+ return arg;
457
+ };
458
+ return this;
459
+ }
460
+ name() {
461
+ if (this.long) {
462
+ return this.long.replace(/^--/, "");
463
+ }
464
+ return this.short.replace(/^-/, "");
465
+ }
466
+ attributeName() {
467
+ return camelcase(this.name().replace(/^no-/, ""));
468
+ }
469
+ is(arg) {
470
+ return this.short === arg || this.long === arg;
471
+ }
472
+ isBoolean() {
473
+ return !this.required && !this.optional && !this.negate;
474
+ }
475
+ }
476
+
477
+ class DualOptions {
478
+ constructor(options) {
479
+ this.positiveOptions = new Map;
480
+ this.negativeOptions = new Map;
481
+ this.dualOptions = new Set;
482
+ options.forEach((option) => {
483
+ if (option.negate) {
484
+ this.negativeOptions.set(option.attributeName(), option);
485
+ } else {
486
+ this.positiveOptions.set(option.attributeName(), option);
487
+ }
488
+ });
489
+ this.negativeOptions.forEach((value, key) => {
490
+ if (this.positiveOptions.has(key)) {
491
+ this.dualOptions.add(key);
492
+ }
493
+ });
494
+ }
495
+ valueFromOption(value, option) {
496
+ const optionKey = option.attributeName();
497
+ if (!this.dualOptions.has(optionKey))
498
+ return true;
499
+ const preset = this.negativeOptions.get(optionKey).presetArg;
500
+ const negativeValue = preset !== undefined ? preset : false;
501
+ return option.negate === (negativeValue === value);
502
+ }
503
+ }
504
+ function camelcase(str) {
505
+ return str.split("-").reduce((str2, word) => {
506
+ return str2 + word[0].toUpperCase() + word.slice(1);
507
+ });
508
+ }
509
+ function splitOptionFlags(flags) {
510
+ let shortFlag;
511
+ let longFlag;
512
+ const flagParts = flags.split(/[ |,]+/);
513
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
514
+ shortFlag = flagParts.shift();
515
+ longFlag = flagParts.shift();
516
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
517
+ shortFlag = longFlag;
518
+ longFlag = undefined;
519
+ }
520
+ return { shortFlag, longFlag };
521
+ }
522
+ exports.Option = Option;
523
+ exports.DualOptions = DualOptions;
524
+ });
525
+
526
+ // ../../node_modules/commander/lib/suggestSimilar.js
527
+ var require_suggestSimilar = __commonJS((exports) => {
528
+ var maxDistance = 3;
529
+ function editDistance(a, b) {
530
+ if (Math.abs(a.length - b.length) > maxDistance)
531
+ return Math.max(a.length, b.length);
532
+ const d = [];
533
+ for (let i = 0;i <= a.length; i++) {
534
+ d[i] = [i];
535
+ }
536
+ for (let j = 0;j <= b.length; j++) {
537
+ d[0][j] = j;
538
+ }
539
+ for (let j = 1;j <= b.length; j++) {
540
+ for (let i = 1;i <= a.length; i++) {
541
+ let cost = 1;
542
+ if (a[i - 1] === b[j - 1]) {
543
+ cost = 0;
544
+ } else {
545
+ cost = 1;
546
+ }
547
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
548
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
549
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
550
+ }
551
+ }
552
+ }
553
+ return d[a.length][b.length];
554
+ }
555
+ function suggestSimilar(word, candidates) {
556
+ if (!candidates || candidates.length === 0)
557
+ return "";
558
+ candidates = Array.from(new Set(candidates));
559
+ const searchingOptions = word.startsWith("--");
560
+ if (searchingOptions) {
561
+ word = word.slice(2);
562
+ candidates = candidates.map((candidate) => candidate.slice(2));
563
+ }
564
+ let similar = [];
565
+ let bestDistance = maxDistance;
566
+ const minSimilarity = 0.4;
567
+ candidates.forEach((candidate) => {
568
+ if (candidate.length <= 1)
569
+ return;
570
+ const distance = editDistance(word, candidate);
571
+ const length = Math.max(word.length, candidate.length);
572
+ const similarity = (length - distance) / length;
573
+ if (similarity > minSimilarity) {
574
+ if (distance < bestDistance) {
575
+ bestDistance = distance;
576
+ similar = [candidate];
577
+ } else if (distance === bestDistance) {
578
+ similar.push(candidate);
579
+ }
580
+ }
581
+ });
582
+ similar.sort((a, b) => a.localeCompare(b));
583
+ if (searchingOptions) {
584
+ similar = similar.map((candidate) => `--${candidate}`);
585
+ }
586
+ if (similar.length > 1) {
587
+ return `
588
+ (Did you mean one of ${similar.join(", ")}?)`;
589
+ }
590
+ if (similar.length === 1) {
591
+ return `
592
+ (Did you mean ${similar[0]}?)`;
593
+ }
594
+ return "";
595
+ }
596
+ exports.suggestSimilar = suggestSimilar;
597
+ });
598
+
599
+ // ../../node_modules/commander/lib/command.js
600
+ var require_command = __commonJS((exports) => {
601
+ var EventEmitter = __require("node:events").EventEmitter;
602
+ var childProcess = __require("node:child_process");
603
+ var path = __require("node:path");
604
+ var fs = __require("node:fs");
605
+ var process2 = __require("node:process");
606
+ var { Argument, humanReadableArgName } = require_argument();
607
+ var { CommanderError } = require_error();
608
+ var { Help } = require_help();
609
+ var { Option, DualOptions } = require_option();
610
+ var { suggestSimilar } = require_suggestSimilar();
611
+
612
+ class Command extends EventEmitter {
613
+ constructor(name) {
614
+ super();
615
+ this.commands = [];
616
+ this.options = [];
617
+ this.parent = null;
618
+ this._allowUnknownOption = false;
619
+ this._allowExcessArguments = true;
620
+ this.registeredArguments = [];
621
+ this._args = this.registeredArguments;
622
+ this.args = [];
623
+ this.rawArgs = [];
624
+ this.processedArgs = [];
625
+ this._scriptPath = null;
626
+ this._name = name || "";
627
+ this._optionValues = {};
628
+ this._optionValueSources = {};
629
+ this._storeOptionsAsProperties = false;
630
+ this._actionHandler = null;
631
+ this._executableHandler = false;
632
+ this._executableFile = null;
633
+ this._executableDir = null;
634
+ this._defaultCommandName = null;
635
+ this._exitCallback = null;
636
+ this._aliases = [];
637
+ this._combineFlagAndOptionalValue = true;
638
+ this._description = "";
639
+ this._summary = "";
640
+ this._argsDescription = undefined;
641
+ this._enablePositionalOptions = false;
642
+ this._passThroughOptions = false;
643
+ this._lifeCycleHooks = {};
644
+ this._showHelpAfterError = false;
645
+ this._showSuggestionAfterError = true;
646
+ this._outputConfiguration = {
647
+ writeOut: (str) => process2.stdout.write(str),
648
+ writeErr: (str) => process2.stderr.write(str),
649
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
650
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
651
+ outputError: (str, write) => write(str)
652
+ };
653
+ this._hidden = false;
654
+ this._helpOption = undefined;
655
+ this._addImplicitHelpCommand = undefined;
656
+ this._helpCommand = undefined;
657
+ this._helpConfiguration = {};
658
+ }
659
+ copyInheritedSettings(sourceCommand) {
660
+ this._outputConfiguration = sourceCommand._outputConfiguration;
661
+ this._helpOption = sourceCommand._helpOption;
662
+ this._helpCommand = sourceCommand._helpCommand;
663
+ this._helpConfiguration = sourceCommand._helpConfiguration;
664
+ this._exitCallback = sourceCommand._exitCallback;
665
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
666
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
667
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
668
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
669
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
670
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
671
+ return this;
672
+ }
673
+ _getCommandAndAncestors() {
674
+ const result = [];
675
+ for (let command = this;command; command = command.parent) {
676
+ result.push(command);
677
+ }
678
+ return result;
679
+ }
680
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
681
+ let desc = actionOptsOrExecDesc;
682
+ let opts = execOpts;
683
+ if (typeof desc === "object" && desc !== null) {
684
+ opts = desc;
685
+ desc = null;
686
+ }
687
+ opts = opts || {};
688
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
689
+ const cmd = this.createCommand(name);
690
+ if (desc) {
691
+ cmd.description(desc);
692
+ cmd._executableHandler = true;
693
+ }
694
+ if (opts.isDefault)
695
+ this._defaultCommandName = cmd._name;
696
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
697
+ cmd._executableFile = opts.executableFile || null;
698
+ if (args)
699
+ cmd.arguments(args);
700
+ this._registerCommand(cmd);
701
+ cmd.parent = this;
702
+ cmd.copyInheritedSettings(this);
703
+ if (desc)
704
+ return this;
705
+ return cmd;
706
+ }
707
+ createCommand(name) {
708
+ return new Command(name);
709
+ }
710
+ createHelp() {
711
+ return Object.assign(new Help, this.configureHelp());
712
+ }
713
+ configureHelp(configuration) {
714
+ if (configuration === undefined)
715
+ return this._helpConfiguration;
716
+ this._helpConfiguration = configuration;
717
+ return this;
718
+ }
719
+ configureOutput(configuration) {
720
+ if (configuration === undefined)
721
+ return this._outputConfiguration;
722
+ Object.assign(this._outputConfiguration, configuration);
723
+ return this;
724
+ }
725
+ showHelpAfterError(displayHelp = true) {
726
+ if (typeof displayHelp !== "string")
727
+ displayHelp = !!displayHelp;
728
+ this._showHelpAfterError = displayHelp;
729
+ return this;
730
+ }
731
+ showSuggestionAfterError(displaySuggestion = true) {
732
+ this._showSuggestionAfterError = !!displaySuggestion;
733
+ return this;
734
+ }
735
+ addCommand(cmd, opts) {
736
+ if (!cmd._name) {
737
+ throw new Error(`Command passed to .addCommand() must have a name
738
+ - specify the name in Command constructor or using .name()`);
739
+ }
740
+ opts = opts || {};
741
+ if (opts.isDefault)
742
+ this._defaultCommandName = cmd._name;
743
+ if (opts.noHelp || opts.hidden)
744
+ cmd._hidden = true;
745
+ this._registerCommand(cmd);
746
+ cmd.parent = this;
747
+ cmd._checkForBrokenPassThrough();
748
+ return this;
749
+ }
750
+ createArgument(name, description) {
751
+ return new Argument(name, description);
752
+ }
753
+ argument(name, description, fn, defaultValue) {
754
+ const argument = this.createArgument(name, description);
755
+ if (typeof fn === "function") {
756
+ argument.default(defaultValue).argParser(fn);
757
+ } else {
758
+ argument.default(fn);
759
+ }
760
+ this.addArgument(argument);
761
+ return this;
762
+ }
763
+ arguments(names) {
764
+ names.trim().split(/ +/).forEach((detail) => {
765
+ this.argument(detail);
766
+ });
767
+ return this;
768
+ }
769
+ addArgument(argument) {
770
+ const previousArgument = this.registeredArguments.slice(-1)[0];
771
+ if (previousArgument && previousArgument.variadic) {
772
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
773
+ }
774
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
775
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
776
+ }
777
+ this.registeredArguments.push(argument);
778
+ return this;
779
+ }
780
+ helpCommand(enableOrNameAndArgs, description) {
781
+ if (typeof enableOrNameAndArgs === "boolean") {
782
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
783
+ return this;
784
+ }
785
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
786
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
787
+ const helpDescription = description ?? "display help for command";
788
+ const helpCommand = this.createCommand(helpName);
789
+ helpCommand.helpOption(false);
790
+ if (helpArgs)
791
+ helpCommand.arguments(helpArgs);
792
+ if (helpDescription)
793
+ helpCommand.description(helpDescription);
794
+ this._addImplicitHelpCommand = true;
795
+ this._helpCommand = helpCommand;
796
+ return this;
797
+ }
798
+ addHelpCommand(helpCommand, deprecatedDescription) {
799
+ if (typeof helpCommand !== "object") {
800
+ this.helpCommand(helpCommand, deprecatedDescription);
801
+ return this;
802
+ }
803
+ this._addImplicitHelpCommand = true;
804
+ this._helpCommand = helpCommand;
805
+ return this;
806
+ }
807
+ _getHelpCommand() {
808
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
809
+ if (hasImplicitHelpCommand) {
810
+ if (this._helpCommand === undefined) {
811
+ this.helpCommand(undefined, undefined);
812
+ }
813
+ return this._helpCommand;
814
+ }
815
+ return null;
816
+ }
817
+ hook(event, listener) {
818
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
819
+ if (!allowedValues.includes(event)) {
820
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
821
+ Expecting one of '${allowedValues.join("', '")}'`);
822
+ }
823
+ if (this._lifeCycleHooks[event]) {
824
+ this._lifeCycleHooks[event].push(listener);
825
+ } else {
826
+ this._lifeCycleHooks[event] = [listener];
827
+ }
828
+ return this;
829
+ }
830
+ exitOverride(fn) {
831
+ if (fn) {
832
+ this._exitCallback = fn;
833
+ } else {
834
+ this._exitCallback = (err) => {
835
+ if (err.code !== "commander.executeSubCommandAsync") {
836
+ throw err;
837
+ } else {}
838
+ };
839
+ }
840
+ return this;
841
+ }
842
+ _exit(exitCode, code, message) {
843
+ if (this._exitCallback) {
844
+ this._exitCallback(new CommanderError(exitCode, code, message));
845
+ }
846
+ process2.exit(exitCode);
847
+ }
848
+ action(fn) {
849
+ const listener = (args) => {
850
+ const expectedArgsCount = this.registeredArguments.length;
851
+ const actionArgs = args.slice(0, expectedArgsCount);
852
+ if (this._storeOptionsAsProperties) {
853
+ actionArgs[expectedArgsCount] = this;
854
+ } else {
855
+ actionArgs[expectedArgsCount] = this.opts();
856
+ }
857
+ actionArgs.push(this);
858
+ return fn.apply(this, actionArgs);
859
+ };
860
+ this._actionHandler = listener;
861
+ return this;
862
+ }
863
+ createOption(flags, description) {
864
+ return new Option(flags, description);
865
+ }
866
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
867
+ try {
868
+ return target.parseArg(value, previous);
869
+ } catch (err) {
870
+ if (err.code === "commander.invalidArgument") {
871
+ const message = `${invalidArgumentMessage} ${err.message}`;
872
+ this.error(message, { exitCode: err.exitCode, code: err.code });
873
+ }
874
+ throw err;
875
+ }
876
+ }
877
+ _registerOption(option) {
878
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
879
+ if (matchingOption) {
880
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
881
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
882
+ - already used by option '${matchingOption.flags}'`);
883
+ }
884
+ this.options.push(option);
885
+ }
886
+ _registerCommand(command) {
887
+ const knownBy = (cmd) => {
888
+ return [cmd.name()].concat(cmd.aliases());
889
+ };
890
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
891
+ if (alreadyUsed) {
892
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
893
+ const newCmd = knownBy(command).join("|");
894
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
895
+ }
896
+ this.commands.push(command);
897
+ }
898
+ addOption(option) {
899
+ this._registerOption(option);
900
+ const oname = option.name();
901
+ const name = option.attributeName();
902
+ if (option.negate) {
903
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
904
+ if (!this._findOption(positiveLongFlag)) {
905
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
906
+ }
907
+ } else if (option.defaultValue !== undefined) {
908
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
909
+ }
910
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
911
+ if (val == null && option.presetArg !== undefined) {
912
+ val = option.presetArg;
913
+ }
914
+ const oldValue = this.getOptionValue(name);
915
+ if (val !== null && option.parseArg) {
916
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
917
+ } else if (val !== null && option.variadic) {
918
+ val = option._concatValue(val, oldValue);
919
+ }
920
+ if (val == null) {
921
+ if (option.negate) {
922
+ val = false;
923
+ } else if (option.isBoolean() || option.optional) {
924
+ val = true;
925
+ } else {
926
+ val = "";
927
+ }
928
+ }
929
+ this.setOptionValueWithSource(name, val, valueSource);
930
+ };
931
+ this.on("option:" + oname, (val) => {
932
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
933
+ handleOptionValue(val, invalidValueMessage, "cli");
934
+ });
935
+ if (option.envVar) {
936
+ this.on("optionEnv:" + oname, (val) => {
937
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
938
+ handleOptionValue(val, invalidValueMessage, "env");
939
+ });
940
+ }
941
+ return this;
942
+ }
943
+ _optionEx(config, flags, description, fn, defaultValue) {
944
+ if (typeof flags === "object" && flags instanceof Option) {
945
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
946
+ }
947
+ const option = this.createOption(flags, description);
948
+ option.makeOptionMandatory(!!config.mandatory);
949
+ if (typeof fn === "function") {
950
+ option.default(defaultValue).argParser(fn);
951
+ } else if (fn instanceof RegExp) {
952
+ const regex = fn;
953
+ fn = (val, def) => {
954
+ const m = regex.exec(val);
955
+ return m ? m[0] : def;
956
+ };
957
+ option.default(defaultValue).argParser(fn);
958
+ } else {
959
+ option.default(fn);
960
+ }
961
+ return this.addOption(option);
962
+ }
963
+ option(flags, description, parseArg, defaultValue) {
964
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
965
+ }
966
+ requiredOption(flags, description, parseArg, defaultValue) {
967
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
968
+ }
969
+ combineFlagAndOptionalValue(combine = true) {
970
+ this._combineFlagAndOptionalValue = !!combine;
971
+ return this;
972
+ }
973
+ allowUnknownOption(allowUnknown = true) {
974
+ this._allowUnknownOption = !!allowUnknown;
975
+ return this;
976
+ }
977
+ allowExcessArguments(allowExcess = true) {
978
+ this._allowExcessArguments = !!allowExcess;
979
+ return this;
980
+ }
981
+ enablePositionalOptions(positional = true) {
982
+ this._enablePositionalOptions = !!positional;
983
+ return this;
984
+ }
985
+ passThroughOptions(passThrough = true) {
986
+ this._passThroughOptions = !!passThrough;
987
+ this._checkForBrokenPassThrough();
988
+ return this;
989
+ }
990
+ _checkForBrokenPassThrough() {
991
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
992
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
993
+ }
994
+ }
995
+ storeOptionsAsProperties(storeAsProperties = true) {
996
+ if (this.options.length) {
997
+ throw new Error("call .storeOptionsAsProperties() before adding options");
998
+ }
999
+ if (Object.keys(this._optionValues).length) {
1000
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1001
+ }
1002
+ this._storeOptionsAsProperties = !!storeAsProperties;
1003
+ return this;
1004
+ }
1005
+ getOptionValue(key) {
1006
+ if (this._storeOptionsAsProperties) {
1007
+ return this[key];
1008
+ }
1009
+ return this._optionValues[key];
1010
+ }
1011
+ setOptionValue(key, value) {
1012
+ return this.setOptionValueWithSource(key, value, undefined);
1013
+ }
1014
+ setOptionValueWithSource(key, value, source) {
1015
+ if (this._storeOptionsAsProperties) {
1016
+ this[key] = value;
1017
+ } else {
1018
+ this._optionValues[key] = value;
1019
+ }
1020
+ this._optionValueSources[key] = source;
1021
+ return this;
1022
+ }
1023
+ getOptionValueSource(key) {
1024
+ return this._optionValueSources[key];
1025
+ }
1026
+ getOptionValueSourceWithGlobals(key) {
1027
+ let source;
1028
+ this._getCommandAndAncestors().forEach((cmd) => {
1029
+ if (cmd.getOptionValueSource(key) !== undefined) {
1030
+ source = cmd.getOptionValueSource(key);
1031
+ }
1032
+ });
1033
+ return source;
1034
+ }
1035
+ _prepareUserArgs(argv, parseOptions) {
1036
+ if (argv !== undefined && !Array.isArray(argv)) {
1037
+ throw new Error("first parameter to parse must be array or undefined");
1038
+ }
1039
+ parseOptions = parseOptions || {};
1040
+ if (argv === undefined && parseOptions.from === undefined) {
1041
+ if (process2.versions?.electron) {
1042
+ parseOptions.from = "electron";
1043
+ }
1044
+ const execArgv = process2.execArgv ?? [];
1045
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1046
+ parseOptions.from = "eval";
1047
+ }
1048
+ }
1049
+ if (argv === undefined) {
1050
+ argv = process2.argv;
1051
+ }
1052
+ this.rawArgs = argv.slice();
1053
+ let userArgs;
1054
+ switch (parseOptions.from) {
1055
+ case undefined:
1056
+ case "node":
1057
+ this._scriptPath = argv[1];
1058
+ userArgs = argv.slice(2);
1059
+ break;
1060
+ case "electron":
1061
+ if (process2.defaultApp) {
1062
+ this._scriptPath = argv[1];
1063
+ userArgs = argv.slice(2);
1064
+ } else {
1065
+ userArgs = argv.slice(1);
1066
+ }
1067
+ break;
1068
+ case "user":
1069
+ userArgs = argv.slice(0);
1070
+ break;
1071
+ case "eval":
1072
+ userArgs = argv.slice(1);
1073
+ break;
1074
+ default:
1075
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1076
+ }
1077
+ if (!this._name && this._scriptPath)
1078
+ this.nameFromFilename(this._scriptPath);
1079
+ this._name = this._name || "program";
1080
+ return userArgs;
1081
+ }
1082
+ parse(argv, parseOptions) {
1083
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1084
+ this._parseCommand([], userArgs);
1085
+ return this;
1086
+ }
1087
+ async parseAsync(argv, parseOptions) {
1088
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1089
+ await this._parseCommand([], userArgs);
1090
+ return this;
1091
+ }
1092
+ _executeSubCommand(subcommand, args) {
1093
+ args = args.slice();
1094
+ let launchWithNode = false;
1095
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1096
+ function findFile(baseDir, baseName) {
1097
+ const localBin = path.resolve(baseDir, baseName);
1098
+ if (fs.existsSync(localBin))
1099
+ return localBin;
1100
+ if (sourceExt.includes(path.extname(baseName)))
1101
+ return;
1102
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1103
+ if (foundExt)
1104
+ return `${localBin}${foundExt}`;
1105
+ return;
1106
+ }
1107
+ this._checkForMissingMandatoryOptions();
1108
+ this._checkForConflictingOptions();
1109
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1110
+ let executableDir = this._executableDir || "";
1111
+ if (this._scriptPath) {
1112
+ let resolvedScriptPath;
1113
+ try {
1114
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1115
+ } catch (err) {
1116
+ resolvedScriptPath = this._scriptPath;
1117
+ }
1118
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1119
+ }
1120
+ if (executableDir) {
1121
+ let localFile = findFile(executableDir, executableFile);
1122
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1123
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1124
+ if (legacyName !== this._name) {
1125
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1126
+ }
1127
+ }
1128
+ executableFile = localFile || executableFile;
1129
+ }
1130
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1131
+ let proc;
1132
+ if (process2.platform !== "win32") {
1133
+ if (launchWithNode) {
1134
+ args.unshift(executableFile);
1135
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1136
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1137
+ } else {
1138
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1139
+ }
1140
+ } else {
1141
+ args.unshift(executableFile);
1142
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1143
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1144
+ }
1145
+ if (!proc.killed) {
1146
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1147
+ signals.forEach((signal) => {
1148
+ process2.on(signal, () => {
1149
+ if (proc.killed === false && proc.exitCode === null) {
1150
+ proc.kill(signal);
1151
+ }
1152
+ });
1153
+ });
1154
+ }
1155
+ const exitCallback = this._exitCallback;
1156
+ proc.on("close", (code) => {
1157
+ code = code ?? 1;
1158
+ if (!exitCallback) {
1159
+ process2.exit(code);
1160
+ } else {
1161
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1162
+ }
1163
+ });
1164
+ proc.on("error", (err) => {
1165
+ if (err.code === "ENOENT") {
1166
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1167
+ const executableMissing = `'${executableFile}' does not exist
1168
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1169
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1170
+ - ${executableDirMessage}`;
1171
+ throw new Error(executableMissing);
1172
+ } else if (err.code === "EACCES") {
1173
+ throw new Error(`'${executableFile}' not executable`);
1174
+ }
1175
+ if (!exitCallback) {
1176
+ process2.exit(1);
1177
+ } else {
1178
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1179
+ wrappedError.nestedError = err;
1180
+ exitCallback(wrappedError);
1181
+ }
1182
+ });
1183
+ this.runningCommand = proc;
1184
+ }
1185
+ _dispatchSubcommand(commandName, operands, unknown) {
1186
+ const subCommand = this._findCommand(commandName);
1187
+ if (!subCommand)
1188
+ this.help({ error: true });
1189
+ let promiseChain;
1190
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1191
+ promiseChain = this._chainOrCall(promiseChain, () => {
1192
+ if (subCommand._executableHandler) {
1193
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1194
+ } else {
1195
+ return subCommand._parseCommand(operands, unknown);
1196
+ }
1197
+ });
1198
+ return promiseChain;
1199
+ }
1200
+ _dispatchHelpCommand(subcommandName) {
1201
+ if (!subcommandName) {
1202
+ this.help();
1203
+ }
1204
+ const subCommand = this._findCommand(subcommandName);
1205
+ if (subCommand && !subCommand._executableHandler) {
1206
+ subCommand.help();
1207
+ }
1208
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1209
+ }
1210
+ _checkNumberOfArguments() {
1211
+ this.registeredArguments.forEach((arg, i) => {
1212
+ if (arg.required && this.args[i] == null) {
1213
+ this.missingArgument(arg.name());
1214
+ }
1215
+ });
1216
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1217
+ return;
1218
+ }
1219
+ if (this.args.length > this.registeredArguments.length) {
1220
+ this._excessArguments(this.args);
1221
+ }
1222
+ }
1223
+ _processArguments() {
1224
+ const myParseArg = (argument, value, previous) => {
1225
+ let parsedValue = value;
1226
+ if (value !== null && argument.parseArg) {
1227
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1228
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1229
+ }
1230
+ return parsedValue;
1231
+ };
1232
+ this._checkNumberOfArguments();
1233
+ const processedArgs = [];
1234
+ this.registeredArguments.forEach((declaredArg, index) => {
1235
+ let value = declaredArg.defaultValue;
1236
+ if (declaredArg.variadic) {
1237
+ if (index < this.args.length) {
1238
+ value = this.args.slice(index);
1239
+ if (declaredArg.parseArg) {
1240
+ value = value.reduce((processed, v) => {
1241
+ return myParseArg(declaredArg, v, processed);
1242
+ }, declaredArg.defaultValue);
1243
+ }
1244
+ } else if (value === undefined) {
1245
+ value = [];
1246
+ }
1247
+ } else if (index < this.args.length) {
1248
+ value = this.args[index];
1249
+ if (declaredArg.parseArg) {
1250
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1251
+ }
1252
+ }
1253
+ processedArgs[index] = value;
1254
+ });
1255
+ this.processedArgs = processedArgs;
1256
+ }
1257
+ _chainOrCall(promise, fn) {
1258
+ if (promise && promise.then && typeof promise.then === "function") {
1259
+ return promise.then(() => fn());
1260
+ }
1261
+ return fn();
1262
+ }
1263
+ _chainOrCallHooks(promise, event) {
1264
+ let result = promise;
1265
+ const hooks = [];
1266
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1267
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1268
+ hooks.push({ hookedCommand, callback });
1269
+ });
1270
+ });
1271
+ if (event === "postAction") {
1272
+ hooks.reverse();
1273
+ }
1274
+ hooks.forEach((hookDetail) => {
1275
+ result = this._chainOrCall(result, () => {
1276
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1277
+ });
1278
+ });
1279
+ return result;
1280
+ }
1281
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1282
+ let result = promise;
1283
+ if (this._lifeCycleHooks[event] !== undefined) {
1284
+ this._lifeCycleHooks[event].forEach((hook) => {
1285
+ result = this._chainOrCall(result, () => {
1286
+ return hook(this, subCommand);
1287
+ });
1288
+ });
1289
+ }
1290
+ return result;
1291
+ }
1292
+ _parseCommand(operands, unknown) {
1293
+ const parsed = this.parseOptions(unknown);
1294
+ this._parseOptionsEnv();
1295
+ this._parseOptionsImplied();
1296
+ operands = operands.concat(parsed.operands);
1297
+ unknown = parsed.unknown;
1298
+ this.args = operands.concat(unknown);
1299
+ if (operands && this._findCommand(operands[0])) {
1300
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1301
+ }
1302
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1303
+ return this._dispatchHelpCommand(operands[1]);
1304
+ }
1305
+ if (this._defaultCommandName) {
1306
+ this._outputHelpIfRequested(unknown);
1307
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1308
+ }
1309
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1310
+ this.help({ error: true });
1311
+ }
1312
+ this._outputHelpIfRequested(parsed.unknown);
1313
+ this._checkForMissingMandatoryOptions();
1314
+ this._checkForConflictingOptions();
1315
+ const checkForUnknownOptions = () => {
1316
+ if (parsed.unknown.length > 0) {
1317
+ this.unknownOption(parsed.unknown[0]);
1318
+ }
1319
+ };
1320
+ const commandEvent = `command:${this.name()}`;
1321
+ if (this._actionHandler) {
1322
+ checkForUnknownOptions();
1323
+ this._processArguments();
1324
+ let promiseChain;
1325
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1326
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1327
+ if (this.parent) {
1328
+ promiseChain = this._chainOrCall(promiseChain, () => {
1329
+ this.parent.emit(commandEvent, operands, unknown);
1330
+ });
1331
+ }
1332
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1333
+ return promiseChain;
1334
+ }
1335
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1336
+ checkForUnknownOptions();
1337
+ this._processArguments();
1338
+ this.parent.emit(commandEvent, operands, unknown);
1339
+ } else if (operands.length) {
1340
+ if (this._findCommand("*")) {
1341
+ return this._dispatchSubcommand("*", operands, unknown);
1342
+ }
1343
+ if (this.listenerCount("command:*")) {
1344
+ this.emit("command:*", operands, unknown);
1345
+ } else if (this.commands.length) {
1346
+ this.unknownCommand();
1347
+ } else {
1348
+ checkForUnknownOptions();
1349
+ this._processArguments();
1350
+ }
1351
+ } else if (this.commands.length) {
1352
+ checkForUnknownOptions();
1353
+ this.help({ error: true });
1354
+ } else {
1355
+ checkForUnknownOptions();
1356
+ this._processArguments();
1357
+ }
1358
+ }
1359
+ _findCommand(name) {
1360
+ if (!name)
1361
+ return;
1362
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1363
+ }
1364
+ _findOption(arg) {
1365
+ return this.options.find((option) => option.is(arg));
1366
+ }
1367
+ _checkForMissingMandatoryOptions() {
1368
+ this._getCommandAndAncestors().forEach((cmd) => {
1369
+ cmd.options.forEach((anOption) => {
1370
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1371
+ cmd.missingMandatoryOptionValue(anOption);
1372
+ }
1373
+ });
1374
+ });
1375
+ }
1376
+ _checkForConflictingLocalOptions() {
1377
+ const definedNonDefaultOptions = this.options.filter((option) => {
1378
+ const optionKey = option.attributeName();
1379
+ if (this.getOptionValue(optionKey) === undefined) {
1380
+ return false;
1381
+ }
1382
+ return this.getOptionValueSource(optionKey) !== "default";
1383
+ });
1384
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1385
+ optionsWithConflicting.forEach((option) => {
1386
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1387
+ if (conflictingAndDefined) {
1388
+ this._conflictingOption(option, conflictingAndDefined);
1389
+ }
1390
+ });
1391
+ }
1392
+ _checkForConflictingOptions() {
1393
+ this._getCommandAndAncestors().forEach((cmd) => {
1394
+ cmd._checkForConflictingLocalOptions();
1395
+ });
1396
+ }
1397
+ parseOptions(argv) {
1398
+ const operands = [];
1399
+ const unknown = [];
1400
+ let dest = operands;
1401
+ const args = argv.slice();
1402
+ function maybeOption(arg) {
1403
+ return arg.length > 1 && arg[0] === "-";
1404
+ }
1405
+ let activeVariadicOption = null;
1406
+ while (args.length) {
1407
+ const arg = args.shift();
1408
+ if (arg === "--") {
1409
+ if (dest === unknown)
1410
+ dest.push(arg);
1411
+ dest.push(...args);
1412
+ break;
1413
+ }
1414
+ if (activeVariadicOption && !maybeOption(arg)) {
1415
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1416
+ continue;
1417
+ }
1418
+ activeVariadicOption = null;
1419
+ if (maybeOption(arg)) {
1420
+ const option = this._findOption(arg);
1421
+ if (option) {
1422
+ if (option.required) {
1423
+ const value = args.shift();
1424
+ if (value === undefined)
1425
+ this.optionMissingArgument(option);
1426
+ this.emit(`option:${option.name()}`, value);
1427
+ } else if (option.optional) {
1428
+ let value = null;
1429
+ if (args.length > 0 && !maybeOption(args[0])) {
1430
+ value = args.shift();
1431
+ }
1432
+ this.emit(`option:${option.name()}`, value);
1433
+ } else {
1434
+ this.emit(`option:${option.name()}`);
1435
+ }
1436
+ activeVariadicOption = option.variadic ? option : null;
1437
+ continue;
1438
+ }
1439
+ }
1440
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1441
+ const option = this._findOption(`-${arg[1]}`);
1442
+ if (option) {
1443
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1444
+ this.emit(`option:${option.name()}`, arg.slice(2));
1445
+ } else {
1446
+ this.emit(`option:${option.name()}`);
1447
+ args.unshift(`-${arg.slice(2)}`);
1448
+ }
1449
+ continue;
1450
+ }
1451
+ }
1452
+ if (/^--[^=]+=/.test(arg)) {
1453
+ const index = arg.indexOf("=");
1454
+ const option = this._findOption(arg.slice(0, index));
1455
+ if (option && (option.required || option.optional)) {
1456
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1457
+ continue;
1458
+ }
1459
+ }
1460
+ if (maybeOption(arg)) {
1461
+ dest = unknown;
1462
+ }
1463
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1464
+ if (this._findCommand(arg)) {
1465
+ operands.push(arg);
1466
+ if (args.length > 0)
1467
+ unknown.push(...args);
1468
+ break;
1469
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1470
+ operands.push(arg);
1471
+ if (args.length > 0)
1472
+ operands.push(...args);
1473
+ break;
1474
+ } else if (this._defaultCommandName) {
1475
+ unknown.push(arg);
1476
+ if (args.length > 0)
1477
+ unknown.push(...args);
1478
+ break;
1479
+ }
1480
+ }
1481
+ if (this._passThroughOptions) {
1482
+ dest.push(arg);
1483
+ if (args.length > 0)
1484
+ dest.push(...args);
1485
+ break;
1486
+ }
1487
+ dest.push(arg);
1488
+ }
1489
+ return { operands, unknown };
1490
+ }
1491
+ opts() {
1492
+ if (this._storeOptionsAsProperties) {
1493
+ const result = {};
1494
+ const len = this.options.length;
1495
+ for (let i = 0;i < len; i++) {
1496
+ const key = this.options[i].attributeName();
1497
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1498
+ }
1499
+ return result;
1500
+ }
1501
+ return this._optionValues;
1502
+ }
1503
+ optsWithGlobals() {
1504
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1505
+ }
1506
+ error(message, errorOptions) {
1507
+ this._outputConfiguration.outputError(`${message}
1508
+ `, this._outputConfiguration.writeErr);
1509
+ if (typeof this._showHelpAfterError === "string") {
1510
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1511
+ `);
1512
+ } else if (this._showHelpAfterError) {
1513
+ this._outputConfiguration.writeErr(`
1514
+ `);
1515
+ this.outputHelp({ error: true });
1516
+ }
1517
+ const config = errorOptions || {};
1518
+ const exitCode = config.exitCode || 1;
1519
+ const code = config.code || "commander.error";
1520
+ this._exit(exitCode, code, message);
1521
+ }
1522
+ _parseOptionsEnv() {
1523
+ this.options.forEach((option) => {
1524
+ if (option.envVar && option.envVar in process2.env) {
1525
+ const optionKey = option.attributeName();
1526
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1527
+ if (option.required || option.optional) {
1528
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1529
+ } else {
1530
+ this.emit(`optionEnv:${option.name()}`);
1531
+ }
1532
+ }
1533
+ }
1534
+ });
1535
+ }
1536
+ _parseOptionsImplied() {
1537
+ const dualHelper = new DualOptions(this.options);
1538
+ const hasCustomOptionValue = (optionKey) => {
1539
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1540
+ };
1541
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1542
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1543
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1544
+ });
1545
+ });
1546
+ }
1547
+ missingArgument(name) {
1548
+ const message = `error: missing required argument '${name}'`;
1549
+ this.error(message, { code: "commander.missingArgument" });
1550
+ }
1551
+ optionMissingArgument(option) {
1552
+ const message = `error: option '${option.flags}' argument missing`;
1553
+ this.error(message, { code: "commander.optionMissingArgument" });
1554
+ }
1555
+ missingMandatoryOptionValue(option) {
1556
+ const message = `error: required option '${option.flags}' not specified`;
1557
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1558
+ }
1559
+ _conflictingOption(option, conflictingOption) {
1560
+ const findBestOptionFromValue = (option2) => {
1561
+ const optionKey = option2.attributeName();
1562
+ const optionValue = this.getOptionValue(optionKey);
1563
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1564
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1565
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1566
+ return negativeOption;
1567
+ }
1568
+ return positiveOption || option2;
1569
+ };
1570
+ const getErrorMessage = (option2) => {
1571
+ const bestOption = findBestOptionFromValue(option2);
1572
+ const optionKey = bestOption.attributeName();
1573
+ const source = this.getOptionValueSource(optionKey);
1574
+ if (source === "env") {
1575
+ return `environment variable '${bestOption.envVar}'`;
1576
+ }
1577
+ return `option '${bestOption.flags}'`;
1578
+ };
1579
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1580
+ this.error(message, { code: "commander.conflictingOption" });
1581
+ }
1582
+ unknownOption(flag) {
1583
+ if (this._allowUnknownOption)
1584
+ return;
1585
+ let suggestion = "";
1586
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1587
+ let candidateFlags = [];
1588
+ let command = this;
1589
+ do {
1590
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1591
+ candidateFlags = candidateFlags.concat(moreFlags);
1592
+ command = command.parent;
1593
+ } while (command && !command._enablePositionalOptions);
1594
+ suggestion = suggestSimilar(flag, candidateFlags);
1595
+ }
1596
+ const message = `error: unknown option '${flag}'${suggestion}`;
1597
+ this.error(message, { code: "commander.unknownOption" });
1598
+ }
1599
+ _excessArguments(receivedArgs) {
1600
+ if (this._allowExcessArguments)
1601
+ return;
1602
+ const expected = this.registeredArguments.length;
1603
+ const s = expected === 1 ? "" : "s";
1604
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1605
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1606
+ this.error(message, { code: "commander.excessArguments" });
1607
+ }
1608
+ unknownCommand() {
1609
+ const unknownName = this.args[0];
1610
+ let suggestion = "";
1611
+ if (this._showSuggestionAfterError) {
1612
+ const candidateNames = [];
1613
+ this.createHelp().visibleCommands(this).forEach((command) => {
1614
+ candidateNames.push(command.name());
1615
+ if (command.alias())
1616
+ candidateNames.push(command.alias());
1617
+ });
1618
+ suggestion = suggestSimilar(unknownName, candidateNames);
1619
+ }
1620
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1621
+ this.error(message, { code: "commander.unknownCommand" });
1622
+ }
1623
+ version(str, flags, description) {
1624
+ if (str === undefined)
1625
+ return this._version;
1626
+ this._version = str;
1627
+ flags = flags || "-V, --version";
1628
+ description = description || "output the version number";
1629
+ const versionOption = this.createOption(flags, description);
1630
+ this._versionOptionName = versionOption.attributeName();
1631
+ this._registerOption(versionOption);
1632
+ this.on("option:" + versionOption.name(), () => {
1633
+ this._outputConfiguration.writeOut(`${str}
1634
+ `);
1635
+ this._exit(0, "commander.version", str);
1636
+ });
1637
+ return this;
1638
+ }
1639
+ description(str, argsDescription) {
1640
+ if (str === undefined && argsDescription === undefined)
1641
+ return this._description;
1642
+ this._description = str;
1643
+ if (argsDescription) {
1644
+ this._argsDescription = argsDescription;
1645
+ }
1646
+ return this;
1647
+ }
1648
+ summary(str) {
1649
+ if (str === undefined)
1650
+ return this._summary;
1651
+ this._summary = str;
1652
+ return this;
1653
+ }
1654
+ alias(alias) {
1655
+ if (alias === undefined)
1656
+ return this._aliases[0];
1657
+ let command = this;
1658
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1659
+ command = this.commands[this.commands.length - 1];
1660
+ }
1661
+ if (alias === command._name)
1662
+ throw new Error("Command alias can't be the same as its name");
1663
+ const matchingCommand = this.parent?._findCommand(alias);
1664
+ if (matchingCommand) {
1665
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1666
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1667
+ }
1668
+ command._aliases.push(alias);
1669
+ return this;
1670
+ }
1671
+ aliases(aliases) {
1672
+ if (aliases === undefined)
1673
+ return this._aliases;
1674
+ aliases.forEach((alias) => this.alias(alias));
1675
+ return this;
1676
+ }
1677
+ usage(str) {
1678
+ if (str === undefined) {
1679
+ if (this._usage)
1680
+ return this._usage;
1681
+ const args = this.registeredArguments.map((arg) => {
1682
+ return humanReadableArgName(arg);
1683
+ });
1684
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1685
+ }
1686
+ this._usage = str;
1687
+ return this;
1688
+ }
1689
+ name(str) {
1690
+ if (str === undefined)
1691
+ return this._name;
1692
+ this._name = str;
1693
+ return this;
1694
+ }
1695
+ nameFromFilename(filename) {
1696
+ this._name = path.basename(filename, path.extname(filename));
1697
+ return this;
1698
+ }
1699
+ executableDir(path2) {
1700
+ if (path2 === undefined)
1701
+ return this._executableDir;
1702
+ this._executableDir = path2;
1703
+ return this;
1704
+ }
1705
+ helpInformation(contextOptions) {
1706
+ const helper = this.createHelp();
1707
+ if (helper.helpWidth === undefined) {
1708
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
1709
+ }
1710
+ return helper.formatHelp(this, helper);
1711
+ }
1712
+ _getHelpContext(contextOptions) {
1713
+ contextOptions = contextOptions || {};
1714
+ const context = { error: !!contextOptions.error };
1715
+ let write;
1716
+ if (context.error) {
1717
+ write = (arg) => this._outputConfiguration.writeErr(arg);
1718
+ } else {
1719
+ write = (arg) => this._outputConfiguration.writeOut(arg);
1720
+ }
1721
+ context.write = contextOptions.write || write;
1722
+ context.command = this;
1723
+ return context;
1724
+ }
1725
+ outputHelp(contextOptions) {
1726
+ let deprecatedCallback;
1727
+ if (typeof contextOptions === "function") {
1728
+ deprecatedCallback = contextOptions;
1729
+ contextOptions = undefined;
1730
+ }
1731
+ const context = this._getHelpContext(contextOptions);
1732
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
1733
+ this.emit("beforeHelp", context);
1734
+ let helpInformation = this.helpInformation(context);
1735
+ if (deprecatedCallback) {
1736
+ helpInformation = deprecatedCallback(helpInformation);
1737
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1738
+ throw new Error("outputHelp callback must return a string or a Buffer");
1739
+ }
1740
+ }
1741
+ context.write(helpInformation);
1742
+ if (this._getHelpOption()?.long) {
1743
+ this.emit(this._getHelpOption().long);
1744
+ }
1745
+ this.emit("afterHelp", context);
1746
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
1747
+ }
1748
+ helpOption(flags, description) {
1749
+ if (typeof flags === "boolean") {
1750
+ if (flags) {
1751
+ this._helpOption = this._helpOption ?? undefined;
1752
+ } else {
1753
+ this._helpOption = null;
1754
+ }
1755
+ return this;
1756
+ }
1757
+ flags = flags ?? "-h, --help";
1758
+ description = description ?? "display help for command";
1759
+ this._helpOption = this.createOption(flags, description);
1760
+ return this;
1761
+ }
1762
+ _getHelpOption() {
1763
+ if (this._helpOption === undefined) {
1764
+ this.helpOption(undefined, undefined);
1765
+ }
1766
+ return this._helpOption;
1767
+ }
1768
+ addHelpOption(option) {
1769
+ this._helpOption = option;
1770
+ return this;
1771
+ }
1772
+ help(contextOptions) {
1773
+ this.outputHelp(contextOptions);
1774
+ let exitCode = process2.exitCode || 0;
1775
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1776
+ exitCode = 1;
1777
+ }
1778
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1779
+ }
1780
+ addHelpText(position, text) {
1781
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1782
+ if (!allowedValues.includes(position)) {
1783
+ throw new Error(`Unexpected value for position to addHelpText.
1784
+ Expecting one of '${allowedValues.join("', '")}'`);
1785
+ }
1786
+ const helpEvent = `${position}Help`;
1787
+ this.on(helpEvent, (context) => {
1788
+ let helpStr;
1789
+ if (typeof text === "function") {
1790
+ helpStr = text({ error: context.error, command: context.command });
1791
+ } else {
1792
+ helpStr = text;
1793
+ }
1794
+ if (helpStr) {
1795
+ context.write(`${helpStr}
1796
+ `);
1797
+ }
1798
+ });
1799
+ return this;
1800
+ }
1801
+ _outputHelpIfRequested(args) {
1802
+ const helpOption = this._getHelpOption();
1803
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1804
+ if (helpRequested) {
1805
+ this.outputHelp();
1806
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
1807
+ }
1808
+ }
1809
+ }
1810
+ function incrementNodeInspectorPort(args) {
1811
+ return args.map((arg) => {
1812
+ if (!arg.startsWith("--inspect")) {
1813
+ return arg;
1814
+ }
1815
+ let debugOption;
1816
+ let debugHost = "127.0.0.1";
1817
+ let debugPort = "9229";
1818
+ let match;
1819
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
1820
+ debugOption = match[1];
1821
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
1822
+ debugOption = match[1];
1823
+ if (/^\d+$/.test(match[3])) {
1824
+ debugPort = match[3];
1825
+ } else {
1826
+ debugHost = match[3];
1827
+ }
1828
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
1829
+ debugOption = match[1];
1830
+ debugHost = match[3];
1831
+ debugPort = match[4];
1832
+ }
1833
+ if (debugOption && debugPort !== "0") {
1834
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
1835
+ }
1836
+ return arg;
1837
+ });
1838
+ }
1839
+ exports.Command = Command;
1840
+ });
1841
+
1842
+ // ../../node_modules/commander/index.js
1843
+ var require_commander = __commonJS((exports) => {
1844
+ var { Argument } = require_argument();
1845
+ var { Command } = require_command();
1846
+ var { CommanderError, InvalidArgumentError } = require_error();
1847
+ var { Help } = require_help();
1848
+ var { Option } = require_option();
1849
+ exports.program = new Command;
1850
+ exports.createCommand = (name) => new Command(name);
1851
+ exports.createOption = (flags, description) => new Option(flags, description);
1852
+ exports.createArgument = (name, description) => new Argument(name, description);
1853
+ exports.Command = Command;
1854
+ exports.Option = Option;
1855
+ exports.Argument = Argument;
1856
+ exports.Help = Help;
1857
+ exports.CommanderError = CommanderError;
1858
+ exports.InvalidArgumentError = InvalidArgumentError;
1859
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
1860
+ });
1861
+
1862
+ // ../../node_modules/commander/esm.mjs
1863
+ var import__ = __toESM(require_commander(), 1);
1864
+ var {
1865
+ program,
1866
+ createCommand,
1867
+ createArgument,
1868
+ createOption,
1869
+ CommanderError,
1870
+ InvalidArgumentError,
1871
+ InvalidOptionArgumentError,
1872
+ Command,
1873
+ Argument,
1874
+ Option,
1875
+ Help
1876
+ } = import__.default;
1877
+
1878
+ // src/server.ts
1879
+ import { existsSync } from "fs";
1880
+
1881
+ // ../../node_modules/hono/dist/compose.js
1882
+ var compose = (middleware, onError, onNotFound) => {
1883
+ return (context, next) => {
1884
+ let index = -1;
1885
+ return dispatch(0);
1886
+ async function dispatch(i) {
1887
+ if (i <= index) {
1888
+ throw new Error("next() called multiple times");
1889
+ }
1890
+ index = i;
1891
+ let res;
1892
+ let isError = false;
1893
+ let handler;
1894
+ if (middleware[i]) {
1895
+ handler = middleware[i][0][0];
1896
+ context.req.routeIndex = i;
1897
+ } else {
1898
+ handler = i === middleware.length && next || undefined;
1899
+ }
1900
+ if (handler) {
1901
+ try {
1902
+ res = await handler(context, () => dispatch(i + 1));
1903
+ } catch (err) {
1904
+ if (err instanceof Error && onError) {
1905
+ context.error = err;
1906
+ res = await onError(err, context);
1907
+ isError = true;
1908
+ } else {
1909
+ throw err;
1910
+ }
1911
+ }
1912
+ } else {
1913
+ if (context.finalized === false && onNotFound) {
1914
+ res = await onNotFound(context);
1915
+ }
1916
+ }
1917
+ if (res && (context.finalized === false || isError)) {
1918
+ context.res = res;
1919
+ }
1920
+ return context;
1921
+ }
1922
+ };
1923
+ };
1924
+
1925
+ // ../../node_modules/hono/dist/request/constants.js
1926
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
1927
+
1928
+ // ../../node_modules/hono/dist/utils/body.js
1929
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
1930
+ const { all = false, dot = false } = options;
1931
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
1932
+ const contentType = headers.get("Content-Type");
1933
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
1934
+ return parseFormData(request, { all, dot });
1935
+ }
1936
+ return {};
1937
+ };
1938
+ async function parseFormData(request, options) {
1939
+ const formData = await request.formData();
1940
+ if (formData) {
1941
+ return convertFormDataToBodyData(formData, options);
1942
+ }
1943
+ return {};
1944
+ }
1945
+ function convertFormDataToBodyData(formData, options) {
1946
+ const form = /* @__PURE__ */ Object.create(null);
1947
+ formData.forEach((value, key) => {
1948
+ const shouldParseAllValues = options.all || key.endsWith("[]");
1949
+ if (!shouldParseAllValues) {
1950
+ form[key] = value;
1951
+ } else {
1952
+ handleParsingAllValues(form, key, value);
1953
+ }
1954
+ });
1955
+ if (options.dot) {
1956
+ Object.entries(form).forEach(([key, value]) => {
1957
+ const shouldParseDotValues = key.includes(".");
1958
+ if (shouldParseDotValues) {
1959
+ handleParsingNestedValues(form, key, value);
1960
+ delete form[key];
1961
+ }
1962
+ });
1963
+ }
1964
+ return form;
1965
+ }
1966
+ var handleParsingAllValues = (form, key, value) => {
1967
+ if (form[key] !== undefined) {
1968
+ if (Array.isArray(form[key])) {
1969
+ form[key].push(value);
1970
+ } else {
1971
+ form[key] = [form[key], value];
1972
+ }
1973
+ } else {
1974
+ if (!key.endsWith("[]")) {
1975
+ form[key] = value;
1976
+ } else {
1977
+ form[key] = [value];
1978
+ }
1979
+ }
1980
+ };
1981
+ var handleParsingNestedValues = (form, key, value) => {
1982
+ let nestedForm = form;
1983
+ const keys = key.split(".");
1984
+ keys.forEach((key2, index) => {
1985
+ if (index === keys.length - 1) {
1986
+ nestedForm[key2] = value;
1987
+ } else {
1988
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
1989
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
1990
+ }
1991
+ nestedForm = nestedForm[key2];
1992
+ }
1993
+ });
1994
+ };
1995
+
1996
+ // ../../node_modules/hono/dist/utils/url.js
1997
+ var splitPath = (path) => {
1998
+ const paths = path.split("/");
1999
+ if (paths[0] === "") {
2000
+ paths.shift();
2001
+ }
2002
+ return paths;
2003
+ };
2004
+ var splitRoutingPath = (routePath) => {
2005
+ const { groups, path } = extractGroupsFromPath(routePath);
2006
+ const paths = splitPath(path);
2007
+ return replaceGroupMarks(paths, groups);
2008
+ };
2009
+ var extractGroupsFromPath = (path) => {
2010
+ const groups = [];
2011
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
2012
+ const mark = `@${index}`;
2013
+ groups.push([mark, match]);
2014
+ return mark;
2015
+ });
2016
+ return { groups, path };
2017
+ };
2018
+ var replaceGroupMarks = (paths, groups) => {
2019
+ for (let i = groups.length - 1;i >= 0; i--) {
2020
+ const [mark] = groups[i];
2021
+ for (let j = paths.length - 1;j >= 0; j--) {
2022
+ if (paths[j].includes(mark)) {
2023
+ paths[j] = paths[j].replace(mark, groups[i][1]);
2024
+ break;
2025
+ }
2026
+ }
2027
+ }
2028
+ return paths;
2029
+ };
2030
+ var patternCache = {};
2031
+ var getPattern = (label, next) => {
2032
+ if (label === "*") {
2033
+ return "*";
2034
+ }
2035
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2036
+ if (match) {
2037
+ const cacheKey = `${label}#${next}`;
2038
+ if (!patternCache[cacheKey]) {
2039
+ if (match[2]) {
2040
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
2041
+ } else {
2042
+ patternCache[cacheKey] = [label, match[1], true];
2043
+ }
2044
+ }
2045
+ return patternCache[cacheKey];
2046
+ }
2047
+ return null;
2048
+ };
2049
+ var tryDecode = (str, decoder) => {
2050
+ try {
2051
+ return decoder(str);
2052
+ } catch {
2053
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
2054
+ try {
2055
+ return decoder(match);
2056
+ } catch {
2057
+ return match;
2058
+ }
2059
+ });
2060
+ }
2061
+ };
2062
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
2063
+ var getPath = (request) => {
2064
+ const url = request.url;
2065
+ const start = url.indexOf("/", url.indexOf(":") + 4);
2066
+ let i = start;
2067
+ for (;i < url.length; i++) {
2068
+ const charCode = url.charCodeAt(i);
2069
+ if (charCode === 37) {
2070
+ const queryIndex = url.indexOf("?", i);
2071
+ const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex);
2072
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
2073
+ } else if (charCode === 63) {
2074
+ break;
2075
+ }
2076
+ }
2077
+ return url.slice(start, i);
2078
+ };
2079
+ var getPathNoStrict = (request) => {
2080
+ const result = getPath(request);
2081
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
2082
+ };
2083
+ var mergePath = (base, sub, ...rest) => {
2084
+ if (rest.length) {
2085
+ sub = mergePath(sub, ...rest);
2086
+ }
2087
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
2088
+ };
2089
+ var checkOptionalParameter = (path) => {
2090
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
2091
+ return null;
2092
+ }
2093
+ const segments = path.split("/");
2094
+ const results = [];
2095
+ let basePath = "";
2096
+ segments.forEach((segment) => {
2097
+ if (segment !== "" && !/\:/.test(segment)) {
2098
+ basePath += "/" + segment;
2099
+ } else if (/\:/.test(segment)) {
2100
+ if (/\?/.test(segment)) {
2101
+ if (results.length === 0 && basePath === "") {
2102
+ results.push("/");
2103
+ } else {
2104
+ results.push(basePath);
2105
+ }
2106
+ const optionalSegment = segment.replace("?", "");
2107
+ basePath += "/" + optionalSegment;
2108
+ results.push(basePath);
2109
+ } else {
2110
+ basePath += "/" + segment;
2111
+ }
2112
+ }
2113
+ });
2114
+ return results.filter((v, i, a) => a.indexOf(v) === i);
2115
+ };
2116
+ var _decodeURI = (value) => {
2117
+ if (!/[%+]/.test(value)) {
2118
+ return value;
2119
+ }
2120
+ if (value.indexOf("+") !== -1) {
2121
+ value = value.replace(/\+/g, " ");
2122
+ }
2123
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
2124
+ };
2125
+ var _getQueryParam = (url, key, multiple) => {
2126
+ let encoded;
2127
+ if (!multiple && key && !/[%+]/.test(key)) {
2128
+ let keyIndex2 = url.indexOf("?", 8);
2129
+ if (keyIndex2 === -1) {
2130
+ return;
2131
+ }
2132
+ if (!url.startsWith(key, keyIndex2 + 1)) {
2133
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
2134
+ }
2135
+ while (keyIndex2 !== -1) {
2136
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
2137
+ if (trailingKeyCode === 61) {
2138
+ const valueIndex = keyIndex2 + key.length + 2;
2139
+ const endIndex = url.indexOf("&", valueIndex);
2140
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
2141
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
2142
+ return "";
2143
+ }
2144
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
2145
+ }
2146
+ encoded = /[%+]/.test(url);
2147
+ if (!encoded) {
2148
+ return;
2149
+ }
2150
+ }
2151
+ const results = {};
2152
+ encoded ??= /[%+]/.test(url);
2153
+ let keyIndex = url.indexOf("?", 8);
2154
+ while (keyIndex !== -1) {
2155
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
2156
+ let valueIndex = url.indexOf("=", keyIndex);
2157
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
2158
+ valueIndex = -1;
2159
+ }
2160
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
2161
+ if (encoded) {
2162
+ name = _decodeURI(name);
2163
+ }
2164
+ keyIndex = nextKeyIndex;
2165
+ if (name === "") {
2166
+ continue;
2167
+ }
2168
+ let value;
2169
+ if (valueIndex === -1) {
2170
+ value = "";
2171
+ } else {
2172
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
2173
+ if (encoded) {
2174
+ value = _decodeURI(value);
2175
+ }
2176
+ }
2177
+ if (multiple) {
2178
+ if (!(results[name] && Array.isArray(results[name]))) {
2179
+ results[name] = [];
2180
+ }
2181
+ results[name].push(value);
2182
+ } else {
2183
+ results[name] ??= value;
2184
+ }
2185
+ }
2186
+ return key ? results[key] : results;
2187
+ };
2188
+ var getQueryParam = _getQueryParam;
2189
+ var getQueryParams = (url, key) => {
2190
+ return _getQueryParam(url, key, true);
2191
+ };
2192
+ var decodeURIComponent_ = decodeURIComponent;
2193
+
2194
+ // ../../node_modules/hono/dist/request.js
2195
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
2196
+ var HonoRequest = class {
2197
+ raw;
2198
+ #validatedData;
2199
+ #matchResult;
2200
+ routeIndex = 0;
2201
+ path;
2202
+ bodyCache = {};
2203
+ constructor(request, path = "/", matchResult = [[]]) {
2204
+ this.raw = request;
2205
+ this.path = path;
2206
+ this.#matchResult = matchResult;
2207
+ this.#validatedData = {};
2208
+ }
2209
+ param(key) {
2210
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
2211
+ }
2212
+ #getDecodedParam(key) {
2213
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
2214
+ const param = this.#getParamValue(paramKey);
2215
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
2216
+ }
2217
+ #getAllDecodedParams() {
2218
+ const decoded = {};
2219
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
2220
+ for (const key of keys) {
2221
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
2222
+ if (value !== undefined) {
2223
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
2224
+ }
2225
+ }
2226
+ return decoded;
2227
+ }
2228
+ #getParamValue(paramKey) {
2229
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
2230
+ }
2231
+ query(key) {
2232
+ return getQueryParam(this.url, key);
2233
+ }
2234
+ queries(key) {
2235
+ return getQueryParams(this.url, key);
2236
+ }
2237
+ header(name) {
2238
+ if (name) {
2239
+ return this.raw.headers.get(name) ?? undefined;
2240
+ }
2241
+ const headerData = {};
2242
+ this.raw.headers.forEach((value, key) => {
2243
+ headerData[key] = value;
2244
+ });
2245
+ return headerData;
2246
+ }
2247
+ async parseBody(options) {
2248
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
2249
+ }
2250
+ #cachedBody = (key) => {
2251
+ const { bodyCache, raw } = this;
2252
+ const cachedBody = bodyCache[key];
2253
+ if (cachedBody) {
2254
+ return cachedBody;
2255
+ }
2256
+ const anyCachedKey = Object.keys(bodyCache)[0];
2257
+ if (anyCachedKey) {
2258
+ return bodyCache[anyCachedKey].then((body) => {
2259
+ if (anyCachedKey === "json") {
2260
+ body = JSON.stringify(body);
2261
+ }
2262
+ return new Response(body)[key]();
2263
+ });
2264
+ }
2265
+ return bodyCache[key] = raw[key]();
2266
+ };
2267
+ json() {
2268
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
2269
+ }
2270
+ text() {
2271
+ return this.#cachedBody("text");
2272
+ }
2273
+ arrayBuffer() {
2274
+ return this.#cachedBody("arrayBuffer");
2275
+ }
2276
+ blob() {
2277
+ return this.#cachedBody("blob");
2278
+ }
2279
+ formData() {
2280
+ return this.#cachedBody("formData");
2281
+ }
2282
+ addValidatedData(target, data) {
2283
+ this.#validatedData[target] = data;
2284
+ }
2285
+ valid(target) {
2286
+ return this.#validatedData[target];
2287
+ }
2288
+ get url() {
2289
+ return this.raw.url;
2290
+ }
2291
+ get method() {
2292
+ return this.raw.method;
2293
+ }
2294
+ get [GET_MATCH_RESULT]() {
2295
+ return this.#matchResult;
2296
+ }
2297
+ get matchedRoutes() {
2298
+ return this.#matchResult[0].map(([[, route]]) => route);
2299
+ }
2300
+ get routePath() {
2301
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
2302
+ }
2303
+ };
2304
+
2305
+ // ../../node_modules/hono/dist/utils/html.js
2306
+ var HtmlEscapedCallbackPhase = {
2307
+ Stringify: 1,
2308
+ BeforeStream: 2,
2309
+ Stream: 3
2310
+ };
2311
+ var raw = (value, callbacks) => {
2312
+ const escapedString = new String(value);
2313
+ escapedString.isEscaped = true;
2314
+ escapedString.callbacks = callbacks;
2315
+ return escapedString;
2316
+ };
2317
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
2318
+ if (typeof str === "object" && !(str instanceof String)) {
2319
+ if (!(str instanceof Promise)) {
2320
+ str = str.toString();
2321
+ }
2322
+ if (str instanceof Promise) {
2323
+ str = await str;
2324
+ }
2325
+ }
2326
+ const callbacks = str.callbacks;
2327
+ if (!callbacks?.length) {
2328
+ return Promise.resolve(str);
2329
+ }
2330
+ if (buffer) {
2331
+ buffer[0] += str;
2332
+ } else {
2333
+ buffer = [str];
2334
+ }
2335
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
2336
+ if (preserveCallbacks) {
2337
+ return raw(await resStr, callbacks);
2338
+ } else {
2339
+ return resStr;
2340
+ }
2341
+ };
2342
+
2343
+ // ../../node_modules/hono/dist/context.js
2344
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
2345
+ var setDefaultContentType = (contentType, headers) => {
2346
+ return {
2347
+ "Content-Type": contentType,
2348
+ ...headers
2349
+ };
2350
+ };
2351
+ var Context = class {
2352
+ #rawRequest;
2353
+ #req;
2354
+ env = {};
2355
+ #var;
2356
+ finalized = false;
2357
+ error;
2358
+ #status;
2359
+ #executionCtx;
2360
+ #res;
2361
+ #layout;
2362
+ #renderer;
2363
+ #notFoundHandler;
2364
+ #preparedHeaders;
2365
+ #matchResult;
2366
+ #path;
2367
+ constructor(req, options) {
2368
+ this.#rawRequest = req;
2369
+ if (options) {
2370
+ this.#executionCtx = options.executionCtx;
2371
+ this.env = options.env;
2372
+ this.#notFoundHandler = options.notFoundHandler;
2373
+ this.#path = options.path;
2374
+ this.#matchResult = options.matchResult;
2375
+ }
2376
+ }
2377
+ get req() {
2378
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
2379
+ return this.#req;
2380
+ }
2381
+ get event() {
2382
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
2383
+ return this.#executionCtx;
2384
+ } else {
2385
+ throw Error("This context has no FetchEvent");
2386
+ }
2387
+ }
2388
+ get executionCtx() {
2389
+ if (this.#executionCtx) {
2390
+ return this.#executionCtx;
2391
+ } else {
2392
+ throw Error("This context has no ExecutionContext");
2393
+ }
2394
+ }
2395
+ get res() {
2396
+ return this.#res ||= new Response(null, {
2397
+ headers: this.#preparedHeaders ??= new Headers
2398
+ });
2399
+ }
2400
+ set res(_res) {
2401
+ if (this.#res && _res) {
2402
+ _res = new Response(_res.body, _res);
2403
+ for (const [k, v] of this.#res.headers.entries()) {
2404
+ if (k === "content-type") {
2405
+ continue;
2406
+ }
2407
+ if (k === "set-cookie") {
2408
+ const cookies = this.#res.headers.getSetCookie();
2409
+ _res.headers.delete("set-cookie");
2410
+ for (const cookie of cookies) {
2411
+ _res.headers.append("set-cookie", cookie);
2412
+ }
2413
+ } else {
2414
+ _res.headers.set(k, v);
2415
+ }
2416
+ }
2417
+ }
2418
+ this.#res = _res;
2419
+ this.finalized = true;
2420
+ }
2421
+ render = (...args) => {
2422
+ this.#renderer ??= (content) => this.html(content);
2423
+ return this.#renderer(...args);
2424
+ };
2425
+ setLayout = (layout) => this.#layout = layout;
2426
+ getLayout = () => this.#layout;
2427
+ setRenderer = (renderer) => {
2428
+ this.#renderer = renderer;
2429
+ };
2430
+ header = (name, value, options) => {
2431
+ if (this.finalized) {
2432
+ this.#res = new Response(this.#res.body, this.#res);
2433
+ }
2434
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
2435
+ if (value === undefined) {
2436
+ headers.delete(name);
2437
+ } else if (options?.append) {
2438
+ headers.append(name, value);
2439
+ } else {
2440
+ headers.set(name, value);
2441
+ }
2442
+ };
2443
+ status = (status) => {
2444
+ this.#status = status;
2445
+ };
2446
+ set = (key, value) => {
2447
+ this.#var ??= /* @__PURE__ */ new Map;
2448
+ this.#var.set(key, value);
2449
+ };
2450
+ get = (key) => {
2451
+ return this.#var ? this.#var.get(key) : undefined;
2452
+ };
2453
+ get var() {
2454
+ if (!this.#var) {
2455
+ return {};
2456
+ }
2457
+ return Object.fromEntries(this.#var);
2458
+ }
2459
+ #newResponse(data, arg, headers) {
2460
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
2461
+ if (typeof arg === "object" && "headers" in arg) {
2462
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
2463
+ for (const [key, value] of argHeaders) {
2464
+ if (key.toLowerCase() === "set-cookie") {
2465
+ responseHeaders.append(key, value);
2466
+ } else {
2467
+ responseHeaders.set(key, value);
2468
+ }
2469
+ }
2470
+ }
2471
+ if (headers) {
2472
+ for (const [k, v] of Object.entries(headers)) {
2473
+ if (typeof v === "string") {
2474
+ responseHeaders.set(k, v);
2475
+ } else {
2476
+ responseHeaders.delete(k);
2477
+ for (const v2 of v) {
2478
+ responseHeaders.append(k, v2);
2479
+ }
2480
+ }
2481
+ }
2482
+ }
2483
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
2484
+ return new Response(data, { status, headers: responseHeaders });
2485
+ }
2486
+ newResponse = (...args) => this.#newResponse(...args);
2487
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
2488
+ text = (text, arg, headers) => {
2489
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
2490
+ };
2491
+ json = (object, arg, headers) => {
2492
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
2493
+ };
2494
+ html = (html, arg, headers) => {
2495
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
2496
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
2497
+ };
2498
+ redirect = (location, status) => {
2499
+ const locationString = String(location);
2500
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
2501
+ return this.newResponse(null, status ?? 302);
2502
+ };
2503
+ notFound = () => {
2504
+ this.#notFoundHandler ??= () => new Response;
2505
+ return this.#notFoundHandler(this);
2506
+ };
2507
+ };
2508
+
2509
+ // ../../node_modules/hono/dist/router.js
2510
+ var METHOD_NAME_ALL = "ALL";
2511
+ var METHOD_NAME_ALL_LOWERCASE = "all";
2512
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
2513
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
2514
+ var UnsupportedPathError = class extends Error {
2515
+ };
2516
+
2517
+ // ../../node_modules/hono/dist/utils/constants.js
2518
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
2519
+
2520
+ // ../../node_modules/hono/dist/hono-base.js
2521
+ var notFoundHandler = (c) => {
2522
+ return c.text("404 Not Found", 404);
2523
+ };
2524
+ var errorHandler = (err, c) => {
2525
+ if ("getResponse" in err) {
2526
+ const res = err.getResponse();
2527
+ return c.newResponse(res.body, res);
2528
+ }
2529
+ console.error(err);
2530
+ return c.text("Internal Server Error", 500);
2531
+ };
2532
+ var Hono = class _Hono {
2533
+ get;
2534
+ post;
2535
+ put;
2536
+ delete;
2537
+ options;
2538
+ patch;
2539
+ all;
2540
+ on;
2541
+ use;
2542
+ router;
2543
+ getPath;
2544
+ _basePath = "/";
2545
+ #path = "/";
2546
+ routes = [];
2547
+ constructor(options = {}) {
2548
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
2549
+ allMethods.forEach((method) => {
2550
+ this[method] = (args1, ...args) => {
2551
+ if (typeof args1 === "string") {
2552
+ this.#path = args1;
2553
+ } else {
2554
+ this.#addRoute(method, this.#path, args1);
2555
+ }
2556
+ args.forEach((handler) => {
2557
+ this.#addRoute(method, this.#path, handler);
2558
+ });
2559
+ return this;
2560
+ };
2561
+ });
2562
+ this.on = (method, path, ...handlers) => {
2563
+ for (const p of [path].flat()) {
2564
+ this.#path = p;
2565
+ for (const m of [method].flat()) {
2566
+ handlers.map((handler) => {
2567
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
2568
+ });
2569
+ }
2570
+ }
2571
+ return this;
2572
+ };
2573
+ this.use = (arg1, ...handlers) => {
2574
+ if (typeof arg1 === "string") {
2575
+ this.#path = arg1;
2576
+ } else {
2577
+ this.#path = "*";
2578
+ handlers.unshift(arg1);
2579
+ }
2580
+ handlers.forEach((handler) => {
2581
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
2582
+ });
2583
+ return this;
2584
+ };
2585
+ const { strict, ...optionsWithoutStrict } = options;
2586
+ Object.assign(this, optionsWithoutStrict);
2587
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
2588
+ }
2589
+ #clone() {
2590
+ const clone = new _Hono({
2591
+ router: this.router,
2592
+ getPath: this.getPath
2593
+ });
2594
+ clone.errorHandler = this.errorHandler;
2595
+ clone.#notFoundHandler = this.#notFoundHandler;
2596
+ clone.routes = this.routes;
2597
+ return clone;
2598
+ }
2599
+ #notFoundHandler = notFoundHandler;
2600
+ errorHandler = errorHandler;
2601
+ route(path, app) {
2602
+ const subApp = this.basePath(path);
2603
+ app.routes.map((r) => {
2604
+ let handler;
2605
+ if (app.errorHandler === errorHandler) {
2606
+ handler = r.handler;
2607
+ } else {
2608
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
2609
+ handler[COMPOSED_HANDLER] = r.handler;
2610
+ }
2611
+ subApp.#addRoute(r.method, r.path, handler);
2612
+ });
2613
+ return this;
2614
+ }
2615
+ basePath(path) {
2616
+ const subApp = this.#clone();
2617
+ subApp._basePath = mergePath(this._basePath, path);
2618
+ return subApp;
2619
+ }
2620
+ onError = (handler) => {
2621
+ this.errorHandler = handler;
2622
+ return this;
2623
+ };
2624
+ notFound = (handler) => {
2625
+ this.#notFoundHandler = handler;
2626
+ return this;
2627
+ };
2628
+ mount(path, applicationHandler, options) {
2629
+ let replaceRequest;
2630
+ let optionHandler;
2631
+ if (options) {
2632
+ if (typeof options === "function") {
2633
+ optionHandler = options;
2634
+ } else {
2635
+ optionHandler = options.optionHandler;
2636
+ if (options.replaceRequest === false) {
2637
+ replaceRequest = (request) => request;
2638
+ } else {
2639
+ replaceRequest = options.replaceRequest;
2640
+ }
2641
+ }
2642
+ }
2643
+ const getOptions = optionHandler ? (c) => {
2644
+ const options2 = optionHandler(c);
2645
+ return Array.isArray(options2) ? options2 : [options2];
2646
+ } : (c) => {
2647
+ let executionContext = undefined;
2648
+ try {
2649
+ executionContext = c.executionCtx;
2650
+ } catch {}
2651
+ return [c.env, executionContext];
2652
+ };
2653
+ replaceRequest ||= (() => {
2654
+ const mergedPath = mergePath(this._basePath, path);
2655
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
2656
+ return (request) => {
2657
+ const url = new URL(request.url);
2658
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
2659
+ return new Request(url, request);
2660
+ };
2661
+ })();
2662
+ const handler = async (c, next) => {
2663
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
2664
+ if (res) {
2665
+ return res;
2666
+ }
2667
+ await next();
2668
+ };
2669
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
2670
+ return this;
2671
+ }
2672
+ #addRoute(method, path, handler) {
2673
+ method = method.toUpperCase();
2674
+ path = mergePath(this._basePath, path);
2675
+ const r = { basePath: this._basePath, path, method, handler };
2676
+ this.router.add(method, path, [handler, r]);
2677
+ this.routes.push(r);
2678
+ }
2679
+ #handleError(err, c) {
2680
+ if (err instanceof Error) {
2681
+ return this.errorHandler(err, c);
2682
+ }
2683
+ throw err;
2684
+ }
2685
+ #dispatch(request, executionCtx, env, method) {
2686
+ if (method === "HEAD") {
2687
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
2688
+ }
2689
+ const path = this.getPath(request, { env });
2690
+ const matchResult = this.router.match(method, path);
2691
+ const c = new Context(request, {
2692
+ path,
2693
+ matchResult,
2694
+ env,
2695
+ executionCtx,
2696
+ notFoundHandler: this.#notFoundHandler
2697
+ });
2698
+ if (matchResult[0].length === 1) {
2699
+ let res;
2700
+ try {
2701
+ res = matchResult[0][0][0][0](c, async () => {
2702
+ c.res = await this.#notFoundHandler(c);
2703
+ });
2704
+ } catch (err) {
2705
+ return this.#handleError(err, c);
2706
+ }
2707
+ 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);
2708
+ }
2709
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2710
+ return (async () => {
2711
+ try {
2712
+ const context = await composed(c);
2713
+ if (!context.finalized) {
2714
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
2715
+ }
2716
+ return context.res;
2717
+ } catch (err) {
2718
+ return this.#handleError(err, c);
2719
+ }
2720
+ })();
2721
+ }
2722
+ fetch = (request, ...rest) => {
2723
+ return this.#dispatch(request, rest[1], rest[0], request.method);
2724
+ };
2725
+ request = (input, requestInit, Env, executionCtx) => {
2726
+ if (input instanceof Request) {
2727
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2728
+ }
2729
+ input = input.toString();
2730
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
2731
+ };
2732
+ fire = () => {
2733
+ addEventListener("fetch", (event) => {
2734
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
2735
+ });
2736
+ };
2737
+ };
2738
+
2739
+ // ../../node_modules/hono/dist/router/reg-exp-router/matcher.js
2740
+ var emptyParam = [];
2741
+ function match(method, path) {
2742
+ const matchers = this.buildAllMatchers();
2743
+ const match2 = (method2, path2) => {
2744
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2745
+ const staticMatch = matcher[2][path2];
2746
+ if (staticMatch) {
2747
+ return staticMatch;
2748
+ }
2749
+ const match3 = path2.match(matcher[0]);
2750
+ if (!match3) {
2751
+ return [[], emptyParam];
2752
+ }
2753
+ const index = match3.indexOf("", 1);
2754
+ return [matcher[1][index], match3];
2755
+ };
2756
+ this.match = match2;
2757
+ return match2(method, path);
2758
+ }
2759
+
2760
+ // ../../node_modules/hono/dist/router/reg-exp-router/node.js
2761
+ var LABEL_REG_EXP_STR = "[^/]+";
2762
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
2763
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2764
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
2765
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2766
+ function compareKey(a, b) {
2767
+ if (a.length === 1) {
2768
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2769
+ }
2770
+ if (b.length === 1) {
2771
+ return 1;
2772
+ }
2773
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2774
+ return 1;
2775
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2776
+ return -1;
2777
+ }
2778
+ if (a === LABEL_REG_EXP_STR) {
2779
+ return 1;
2780
+ } else if (b === LABEL_REG_EXP_STR) {
2781
+ return -1;
2782
+ }
2783
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2784
+ }
2785
+ var Node = class _Node {
2786
+ #index;
2787
+ #varIndex;
2788
+ #children = /* @__PURE__ */ Object.create(null);
2789
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2790
+ if (tokens.length === 0) {
2791
+ if (this.#index !== undefined) {
2792
+ throw PATH_ERROR;
2793
+ }
2794
+ if (pathErrorCheckOnly) {
2795
+ return;
2796
+ }
2797
+ this.#index = index;
2798
+ return;
2799
+ }
2800
+ const [token, ...restTokens] = tokens;
2801
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2802
+ let node;
2803
+ if (pattern) {
2804
+ const name = pattern[1];
2805
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2806
+ if (name && pattern[2]) {
2807
+ if (regexpStr === ".*") {
2808
+ throw PATH_ERROR;
2809
+ }
2810
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2811
+ if (/\((?!\?:)/.test(regexpStr)) {
2812
+ throw PATH_ERROR;
2813
+ }
2814
+ }
2815
+ node = this.#children[regexpStr];
2816
+ if (!node) {
2817
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
2818
+ throw PATH_ERROR;
2819
+ }
2820
+ if (pathErrorCheckOnly) {
2821
+ return;
2822
+ }
2823
+ node = this.#children[regexpStr] = new _Node;
2824
+ if (name !== "") {
2825
+ node.#varIndex = context.varIndex++;
2826
+ }
2827
+ }
2828
+ if (!pathErrorCheckOnly && name !== "") {
2829
+ paramMap.push([name, node.#varIndex]);
2830
+ }
2831
+ } else {
2832
+ node = this.#children[token];
2833
+ if (!node) {
2834
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
2835
+ throw PATH_ERROR;
2836
+ }
2837
+ if (pathErrorCheckOnly) {
2838
+ return;
2839
+ }
2840
+ node = this.#children[token] = new _Node;
2841
+ }
2842
+ }
2843
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2844
+ }
2845
+ buildRegExpStr() {
2846
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2847
+ const strList = childKeys.map((k) => {
2848
+ const c = this.#children[k];
2849
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2850
+ });
2851
+ if (typeof this.#index === "number") {
2852
+ strList.unshift(`#${this.#index}`);
2853
+ }
2854
+ if (strList.length === 0) {
2855
+ return "";
2856
+ }
2857
+ if (strList.length === 1) {
2858
+ return strList[0];
2859
+ }
2860
+ return "(?:" + strList.join("|") + ")";
2861
+ }
2862
+ };
2863
+
2864
+ // ../../node_modules/hono/dist/router/reg-exp-router/trie.js
2865
+ var Trie = class {
2866
+ #context = { varIndex: 0 };
2867
+ #root = new Node;
2868
+ insert(path, index, pathErrorCheckOnly) {
2869
+ const paramAssoc = [];
2870
+ const groups = [];
2871
+ for (let i = 0;; ) {
2872
+ let replaced = false;
2873
+ path = path.replace(/\{[^}]+\}/g, (m) => {
2874
+ const mark = `@\\${i}`;
2875
+ groups[i] = [mark, m];
2876
+ i++;
2877
+ replaced = true;
2878
+ return mark;
2879
+ });
2880
+ if (!replaced) {
2881
+ break;
2882
+ }
2883
+ }
2884
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2885
+ for (let i = groups.length - 1;i >= 0; i--) {
2886
+ const [mark] = groups[i];
2887
+ for (let j = tokens.length - 1;j >= 0; j--) {
2888
+ if (tokens[j].indexOf(mark) !== -1) {
2889
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2890
+ break;
2891
+ }
2892
+ }
2893
+ }
2894
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2895
+ return paramAssoc;
2896
+ }
2897
+ buildRegExp() {
2898
+ let regexp = this.#root.buildRegExpStr();
2899
+ if (regexp === "") {
2900
+ return [/^$/, [], []];
2901
+ }
2902
+ let captureIndex = 0;
2903
+ const indexReplacementMap = [];
2904
+ const paramReplacementMap = [];
2905
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2906
+ if (handlerIndex !== undefined) {
2907
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
2908
+ return "$()";
2909
+ }
2910
+ if (paramIndex !== undefined) {
2911
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2912
+ return "";
2913
+ }
2914
+ return "";
2915
+ });
2916
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2917
+ }
2918
+ };
2919
+
2920
+ // ../../node_modules/hono/dist/router/reg-exp-router/router.js
2921
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2922
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2923
+ function buildWildcardRegExp(path) {
2924
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
2925
+ }
2926
+ function clearWildcardRegExpCache() {
2927
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2928
+ }
2929
+ function buildMatcherFromPreprocessedRoutes(routes) {
2930
+ const trie = new Trie;
2931
+ const handlerData = [];
2932
+ if (routes.length === 0) {
2933
+ return nullMatcher;
2934
+ }
2935
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
2936
+ const staticMap = /* @__PURE__ */ Object.create(null);
2937
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
2938
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2939
+ if (pathErrorCheckOnly) {
2940
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2941
+ } else {
2942
+ j++;
2943
+ }
2944
+ let paramAssoc;
2945
+ try {
2946
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2947
+ } catch (e) {
2948
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2949
+ }
2950
+ if (pathErrorCheckOnly) {
2951
+ continue;
2952
+ }
2953
+ handlerData[j] = handlers.map(([h, paramCount]) => {
2954
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
2955
+ paramCount -= 1;
2956
+ for (;paramCount >= 0; paramCount--) {
2957
+ const [key, value] = paramAssoc[paramCount];
2958
+ paramIndexMap[key] = value;
2959
+ }
2960
+ return [h, paramIndexMap];
2961
+ });
2962
+ }
2963
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2964
+ for (let i = 0, len = handlerData.length;i < len; i++) {
2965
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
2966
+ const map = handlerData[i][j]?.[1];
2967
+ if (!map) {
2968
+ continue;
2969
+ }
2970
+ const keys = Object.keys(map);
2971
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
2972
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
2973
+ }
2974
+ }
2975
+ }
2976
+ const handlerMap = [];
2977
+ for (const i in indexReplacementMap) {
2978
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
2979
+ }
2980
+ return [regexp, handlerMap, staticMap];
2981
+ }
2982
+ function findMiddleware(middleware, path) {
2983
+ if (!middleware) {
2984
+ return;
2985
+ }
2986
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2987
+ if (buildWildcardRegExp(k).test(path)) {
2988
+ return [...middleware[k]];
2989
+ }
2990
+ }
2991
+ return;
2992
+ }
2993
+ var RegExpRouter = class {
2994
+ name = "RegExpRouter";
2995
+ #middleware;
2996
+ #routes;
2997
+ constructor() {
2998
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2999
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3000
+ }
3001
+ add(method, path, handler) {
3002
+ const middleware = this.#middleware;
3003
+ const routes = this.#routes;
3004
+ if (!middleware || !routes) {
3005
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3006
+ }
3007
+ if (!middleware[method]) {
3008
+ [middleware, routes].forEach((handlerMap) => {
3009
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
3010
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
3011
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
3012
+ });
3013
+ });
3014
+ }
3015
+ if (path === "/*") {
3016
+ path = "*";
3017
+ }
3018
+ const paramCount = (path.match(/\/:/g) || []).length;
3019
+ if (/\*$/.test(path)) {
3020
+ const re = buildWildcardRegExp(path);
3021
+ if (method === METHOD_NAME_ALL) {
3022
+ Object.keys(middleware).forEach((m) => {
3023
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
3024
+ });
3025
+ } else {
3026
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
3027
+ }
3028
+ Object.keys(middleware).forEach((m) => {
3029
+ if (method === METHOD_NAME_ALL || method === m) {
3030
+ Object.keys(middleware[m]).forEach((p) => {
3031
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
3032
+ });
3033
+ }
3034
+ });
3035
+ Object.keys(routes).forEach((m) => {
3036
+ if (method === METHOD_NAME_ALL || method === m) {
3037
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
3038
+ }
3039
+ });
3040
+ return;
3041
+ }
3042
+ const paths = checkOptionalParameter(path) || [path];
3043
+ for (let i = 0, len = paths.length;i < len; i++) {
3044
+ const path2 = paths[i];
3045
+ Object.keys(routes).forEach((m) => {
3046
+ if (method === METHOD_NAME_ALL || method === m) {
3047
+ routes[m][path2] ||= [
3048
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
3049
+ ];
3050
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
3051
+ }
3052
+ });
3053
+ }
3054
+ }
3055
+ match = match;
3056
+ buildAllMatchers() {
3057
+ const matchers = /* @__PURE__ */ Object.create(null);
3058
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
3059
+ matchers[method] ||= this.#buildMatcher(method);
3060
+ });
3061
+ this.#middleware = this.#routes = undefined;
3062
+ clearWildcardRegExpCache();
3063
+ return matchers;
3064
+ }
3065
+ #buildMatcher(method) {
3066
+ const routes = [];
3067
+ let hasOwnRoute = method === METHOD_NAME_ALL;
3068
+ [this.#middleware, this.#routes].forEach((r) => {
3069
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
3070
+ if (ownRoute.length !== 0) {
3071
+ hasOwnRoute ||= true;
3072
+ routes.push(...ownRoute);
3073
+ } else if (method !== METHOD_NAME_ALL) {
3074
+ routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
3075
+ }
3076
+ });
3077
+ if (!hasOwnRoute) {
3078
+ return null;
3079
+ } else {
3080
+ return buildMatcherFromPreprocessedRoutes(routes);
3081
+ }
3082
+ }
3083
+ };
3084
+
3085
+ // ../../node_modules/hono/dist/router/reg-exp-router/prepared-router.js
3086
+ var PreparedRegExpRouter = class {
3087
+ name = "PreparedRegExpRouter";
3088
+ #matchers;
3089
+ #relocateMap;
3090
+ constructor(matchers, relocateMap) {
3091
+ this.#matchers = matchers;
3092
+ this.#relocateMap = relocateMap;
3093
+ }
3094
+ #addWildcard(method, handlerData) {
3095
+ const matcher = this.#matchers[method];
3096
+ matcher[1].forEach((list) => list && list.push(handlerData));
3097
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
3098
+ }
3099
+ #addPath(method, path, handler, indexes, map) {
3100
+ const matcher = this.#matchers[method];
3101
+ if (!map) {
3102
+ matcher[2][path][0].push([handler, {}]);
3103
+ } else {
3104
+ indexes.forEach((index) => {
3105
+ if (typeof index === "number") {
3106
+ matcher[1][index].push([handler, map]);
3107
+ } else {
3108
+ matcher[2][index || path][0].push([handler, map]);
3109
+ }
3110
+ });
3111
+ }
3112
+ }
3113
+ add(method, path, handler) {
3114
+ if (!this.#matchers[method]) {
3115
+ const all = this.#matchers[METHOD_NAME_ALL];
3116
+ const staticMap = {};
3117
+ for (const key in all[2]) {
3118
+ staticMap[key] = [all[2][key][0].slice(), emptyParam];
3119
+ }
3120
+ this.#matchers[method] = [
3121
+ all[0],
3122
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
3123
+ staticMap
3124
+ ];
3125
+ }
3126
+ if (path === "/*" || path === "*") {
3127
+ const handlerData = [handler, {}];
3128
+ if (method === METHOD_NAME_ALL) {
3129
+ for (const m in this.#matchers) {
3130
+ this.#addWildcard(m, handlerData);
3131
+ }
3132
+ } else {
3133
+ this.#addWildcard(method, handlerData);
3134
+ }
3135
+ return;
3136
+ }
3137
+ const data = this.#relocateMap[path];
3138
+ if (!data) {
3139
+ throw new Error(`Path ${path} is not registered`);
3140
+ }
3141
+ for (const [indexes, map] of data) {
3142
+ if (method === METHOD_NAME_ALL) {
3143
+ for (const m in this.#matchers) {
3144
+ this.#addPath(m, path, handler, indexes, map);
3145
+ }
3146
+ } else {
3147
+ this.#addPath(method, path, handler, indexes, map);
3148
+ }
3149
+ }
3150
+ }
3151
+ buildAllMatchers() {
3152
+ return this.#matchers;
3153
+ }
3154
+ match = match;
3155
+ };
3156
+
3157
+ // ../../node_modules/hono/dist/router/smart-router/router.js
3158
+ var SmartRouter = class {
3159
+ name = "SmartRouter";
3160
+ #routers = [];
3161
+ #routes = [];
3162
+ constructor(init) {
3163
+ this.#routers = init.routers;
3164
+ }
3165
+ add(method, path, handler) {
3166
+ if (!this.#routes) {
3167
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3168
+ }
3169
+ this.#routes.push([method, path, handler]);
3170
+ }
3171
+ match(method, path) {
3172
+ if (!this.#routes) {
3173
+ throw new Error("Fatal error");
3174
+ }
3175
+ const routers = this.#routers;
3176
+ const routes = this.#routes;
3177
+ const len = routers.length;
3178
+ let i = 0;
3179
+ let res;
3180
+ for (;i < len; i++) {
3181
+ const router = routers[i];
3182
+ try {
3183
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
3184
+ router.add(...routes[i2]);
3185
+ }
3186
+ res = router.match(method, path);
3187
+ } catch (e) {
3188
+ if (e instanceof UnsupportedPathError) {
3189
+ continue;
3190
+ }
3191
+ throw e;
3192
+ }
3193
+ this.match = router.match.bind(router);
3194
+ this.#routers = [router];
3195
+ this.#routes = undefined;
3196
+ break;
3197
+ }
3198
+ if (i === len) {
3199
+ throw new Error("Fatal error");
3200
+ }
3201
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
3202
+ return res;
3203
+ }
3204
+ get activeRouter() {
3205
+ if (this.#routes || this.#routers.length !== 1) {
3206
+ throw new Error("No active router has been determined yet.");
3207
+ }
3208
+ return this.#routers[0];
3209
+ }
3210
+ };
3211
+
3212
+ // ../../node_modules/hono/dist/router/trie-router/node.js
3213
+ var emptyParams = /* @__PURE__ */ Object.create(null);
3214
+ var Node2 = class _Node2 {
3215
+ #methods;
3216
+ #children;
3217
+ #patterns;
3218
+ #order = 0;
3219
+ #params = emptyParams;
3220
+ constructor(method, handler, children) {
3221
+ this.#children = children || /* @__PURE__ */ Object.create(null);
3222
+ this.#methods = [];
3223
+ if (method && handler) {
3224
+ const m = /* @__PURE__ */ Object.create(null);
3225
+ m[method] = { handler, possibleKeys: [], score: 0 };
3226
+ this.#methods = [m];
3227
+ }
3228
+ this.#patterns = [];
3229
+ }
3230
+ insert(method, path, handler) {
3231
+ this.#order = ++this.#order;
3232
+ let curNode = this;
3233
+ const parts = splitRoutingPath(path);
3234
+ const possibleKeys = [];
3235
+ for (let i = 0, len = parts.length;i < len; i++) {
3236
+ const p = parts[i];
3237
+ const nextP = parts[i + 1];
3238
+ const pattern = getPattern(p, nextP);
3239
+ const key = Array.isArray(pattern) ? pattern[0] : p;
3240
+ if (key in curNode.#children) {
3241
+ curNode = curNode.#children[key];
3242
+ if (pattern) {
3243
+ possibleKeys.push(pattern[1]);
3244
+ }
3245
+ continue;
3246
+ }
3247
+ curNode.#children[key] = new _Node2;
3248
+ if (pattern) {
3249
+ curNode.#patterns.push(pattern);
3250
+ possibleKeys.push(pattern[1]);
3251
+ }
3252
+ curNode = curNode.#children[key];
3253
+ }
3254
+ curNode.#methods.push({
3255
+ [method]: {
3256
+ handler,
3257
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
3258
+ score: this.#order
3259
+ }
3260
+ });
3261
+ return curNode;
3262
+ }
3263
+ #getHandlerSets(node, method, nodeParams, params) {
3264
+ const handlerSets = [];
3265
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
3266
+ const m = node.#methods[i];
3267
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
3268
+ const processedSet = {};
3269
+ if (handlerSet !== undefined) {
3270
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
3271
+ handlerSets.push(handlerSet);
3272
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
3273
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
3274
+ const key = handlerSet.possibleKeys[i2];
3275
+ const processed = processedSet[handlerSet.score];
3276
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
3277
+ processedSet[handlerSet.score] = true;
3278
+ }
3279
+ }
3280
+ }
3281
+ }
3282
+ return handlerSets;
3283
+ }
3284
+ search(method, path) {
3285
+ const handlerSets = [];
3286
+ this.#params = emptyParams;
3287
+ const curNode = this;
3288
+ let curNodes = [curNode];
3289
+ const parts = splitPath(path);
3290
+ const curNodesQueue = [];
3291
+ for (let i = 0, len = parts.length;i < len; i++) {
3292
+ const part = parts[i];
3293
+ const isLast = i === len - 1;
3294
+ const tempNodes = [];
3295
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
3296
+ const node = curNodes[j];
3297
+ const nextNode = node.#children[part];
3298
+ if (nextNode) {
3299
+ nextNode.#params = node.#params;
3300
+ if (isLast) {
3301
+ if (nextNode.#children["*"]) {
3302
+ handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
3303
+ }
3304
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
3305
+ } else {
3306
+ tempNodes.push(nextNode);
3307
+ }
3308
+ }
3309
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
3310
+ const pattern = node.#patterns[k];
3311
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
3312
+ if (pattern === "*") {
3313
+ const astNode = node.#children["*"];
3314
+ if (astNode) {
3315
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
3316
+ astNode.#params = params;
3317
+ tempNodes.push(astNode);
3318
+ }
3319
+ continue;
3320
+ }
3321
+ const [key, name, matcher] = pattern;
3322
+ if (!part && !(matcher instanceof RegExp)) {
3323
+ continue;
3324
+ }
3325
+ const child = node.#children[key];
3326
+ const restPathString = parts.slice(i).join("/");
3327
+ if (matcher instanceof RegExp) {
3328
+ const m = matcher.exec(restPathString);
3329
+ if (m) {
3330
+ params[name] = m[0];
3331
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
3332
+ if (Object.keys(child.#children).length) {
3333
+ child.#params = params;
3334
+ const componentCount = m[0].match(/\//)?.length ?? 0;
3335
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
3336
+ targetCurNodes.push(child);
3337
+ }
3338
+ continue;
3339
+ }
3340
+ }
3341
+ if (matcher === true || matcher.test(part)) {
3342
+ params[name] = part;
3343
+ if (isLast) {
3344
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
3345
+ if (child.#children["*"]) {
3346
+ handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
3347
+ }
3348
+ } else {
3349
+ child.#params = params;
3350
+ tempNodes.push(child);
3351
+ }
3352
+ }
3353
+ }
3354
+ }
3355
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
3356
+ }
3357
+ if (handlerSets.length > 1) {
3358
+ handlerSets.sort((a, b) => {
3359
+ return a.score - b.score;
3360
+ });
3361
+ }
3362
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
3363
+ }
3364
+ };
3365
+
3366
+ // ../../node_modules/hono/dist/router/trie-router/router.js
3367
+ var TrieRouter = class {
3368
+ name = "TrieRouter";
3369
+ #node;
3370
+ constructor() {
3371
+ this.#node = new Node2;
3372
+ }
3373
+ add(method, path, handler) {
3374
+ const results = checkOptionalParameter(path);
3375
+ if (results) {
3376
+ for (let i = 0, len = results.length;i < len; i++) {
3377
+ this.#node.insert(method, results[i], handler);
3378
+ }
3379
+ return;
3380
+ }
3381
+ this.#node.insert(method, path, handler);
3382
+ }
3383
+ match(method, path) {
3384
+ return this.#node.search(method, path);
3385
+ }
3386
+ };
3387
+
3388
+ // ../../node_modules/hono/dist/hono.js
3389
+ var Hono2 = class extends Hono {
3390
+ constructor(options = {}) {
3391
+ super(options);
3392
+ this.router = options.router ?? new SmartRouter({
3393
+ routers: [new RegExpRouter, new TrieRouter]
3394
+ });
3395
+ }
3396
+ };
3397
+
3398
+ // ../../node_modules/hono/dist/adapter/bun/serve-static.js
3399
+ import { stat } from "node:fs/promises";
3400
+ import { join } from "node:path";
3401
+
3402
+ // ../../node_modules/hono/dist/utils/compress.js
3403
+ var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
3404
+
3405
+ // ../../node_modules/hono/dist/utils/mime.js
3406
+ var getMimeType = (filename, mimes = baseMimes) => {
3407
+ const regexp = /\.([a-zA-Z0-9]+?)$/;
3408
+ const match2 = filename.match(regexp);
3409
+ if (!match2) {
3410
+ return;
3411
+ }
3412
+ let mimeType = mimes[match2[1]];
3413
+ if (mimeType && mimeType.startsWith("text")) {
3414
+ mimeType += "; charset=utf-8";
3415
+ }
3416
+ return mimeType;
3417
+ };
3418
+ var _baseMimes = {
3419
+ aac: "audio/aac",
3420
+ avi: "video/x-msvideo",
3421
+ avif: "image/avif",
3422
+ av1: "video/av1",
3423
+ bin: "application/octet-stream",
3424
+ bmp: "image/bmp",
3425
+ css: "text/css",
3426
+ csv: "text/csv",
3427
+ eot: "application/vnd.ms-fontobject",
3428
+ epub: "application/epub+zip",
3429
+ gif: "image/gif",
3430
+ gz: "application/gzip",
3431
+ htm: "text/html",
3432
+ html: "text/html",
3433
+ ico: "image/x-icon",
3434
+ ics: "text/calendar",
3435
+ jpeg: "image/jpeg",
3436
+ jpg: "image/jpeg",
3437
+ js: "text/javascript",
3438
+ json: "application/json",
3439
+ jsonld: "application/ld+json",
3440
+ map: "application/json",
3441
+ mid: "audio/x-midi",
3442
+ midi: "audio/x-midi",
3443
+ mjs: "text/javascript",
3444
+ mp3: "audio/mpeg",
3445
+ mp4: "video/mp4",
3446
+ mpeg: "video/mpeg",
3447
+ oga: "audio/ogg",
3448
+ ogv: "video/ogg",
3449
+ ogx: "application/ogg",
3450
+ opus: "audio/opus",
3451
+ otf: "font/otf",
3452
+ pdf: "application/pdf",
3453
+ png: "image/png",
3454
+ rtf: "application/rtf",
3455
+ svg: "image/svg+xml",
3456
+ tif: "image/tiff",
3457
+ tiff: "image/tiff",
3458
+ ts: "video/mp2t",
3459
+ ttf: "font/ttf",
3460
+ txt: "text/plain",
3461
+ wasm: "application/wasm",
3462
+ webm: "video/webm",
3463
+ weba: "audio/webm",
3464
+ webmanifest: "application/manifest+json",
3465
+ webp: "image/webp",
3466
+ woff: "font/woff",
3467
+ woff2: "font/woff2",
3468
+ xhtml: "application/xhtml+xml",
3469
+ xml: "application/xml",
3470
+ zip: "application/zip",
3471
+ "3gp": "video/3gpp",
3472
+ "3g2": "video/3gpp2",
3473
+ gltf: "model/gltf+json",
3474
+ glb: "model/gltf-binary"
3475
+ };
3476
+ var baseMimes = _baseMimes;
3477
+
3478
+ // ../../node_modules/hono/dist/middleware/serve-static/path.js
3479
+ var defaultJoin = (...paths) => {
3480
+ let result = paths.filter((p) => p !== "").join("/");
3481
+ result = result.replace(/(?<=\/)\/+/g, "");
3482
+ const segments = result.split("/");
3483
+ const resolved = [];
3484
+ for (const segment of segments) {
3485
+ if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") {
3486
+ resolved.pop();
3487
+ } else if (segment !== ".") {
3488
+ resolved.push(segment);
3489
+ }
3490
+ }
3491
+ return resolved.join("/") || ".";
3492
+ };
3493
+
3494
+ // ../../node_modules/hono/dist/middleware/serve-static/index.js
3495
+ var ENCODINGS = {
3496
+ br: ".br",
3497
+ zstd: ".zst",
3498
+ gzip: ".gz"
3499
+ };
3500
+ var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
3501
+ var DEFAULT_DOCUMENT = "index.html";
3502
+ var serveStatic = (options) => {
3503
+ const root = options.root ?? "./";
3504
+ const optionPath = options.path;
3505
+ const join = options.join ?? defaultJoin;
3506
+ return async (c, next) => {
3507
+ if (c.finalized) {
3508
+ return next();
3509
+ }
3510
+ let filename;
3511
+ if (options.path) {
3512
+ filename = options.path;
3513
+ } else {
3514
+ try {
3515
+ filename = decodeURIComponent(c.req.path);
3516
+ if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {
3517
+ throw new Error;
3518
+ }
3519
+ } catch {
3520
+ await options.onNotFound?.(c.req.path, c);
3521
+ return next();
3522
+ }
3523
+ }
3524
+ let path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename);
3525
+ if (options.isDir && await options.isDir(path)) {
3526
+ path = join(path, DEFAULT_DOCUMENT);
3527
+ }
3528
+ const getContent = options.getContent;
3529
+ let content = await getContent(path, c);
3530
+ if (content instanceof Response) {
3531
+ return c.newResponse(content.body, content);
3532
+ }
3533
+ if (content) {
3534
+ const mimeType = options.mimes && getMimeType(path, options.mimes) || getMimeType(path);
3535
+ c.header("Content-Type", mimeType || "application/octet-stream");
3536
+ if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
3537
+ const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
3538
+ for (const encoding of ENCODINGS_ORDERED_KEYS) {
3539
+ if (!acceptEncodingSet.has(encoding)) {
3540
+ continue;
3541
+ }
3542
+ const compressedContent = await getContent(path + ENCODINGS[encoding], c);
3543
+ if (compressedContent) {
3544
+ content = compressedContent;
3545
+ c.header("Content-Encoding", encoding);
3546
+ c.header("Vary", "Accept-Encoding", { append: true });
3547
+ break;
3548
+ }
3549
+ }
3550
+ }
3551
+ await options.onFound?.(path, c);
3552
+ return c.body(content);
3553
+ }
3554
+ await options.onNotFound?.(path, c);
3555
+ await next();
3556
+ return;
3557
+ };
3558
+ };
3559
+
3560
+ // ../../node_modules/hono/dist/adapter/bun/serve-static.js
3561
+ var serveStatic2 = (options) => {
3562
+ return async function serveStatic2(c, next) {
3563
+ const getContent = async (path) => {
3564
+ const file = Bun.file(path);
3565
+ return await file.exists() ? file : null;
3566
+ };
3567
+ const isDir = async (path) => {
3568
+ let isDir2;
3569
+ try {
3570
+ const stats = await stat(path);
3571
+ isDir2 = stats.isDirectory();
3572
+ } catch {}
3573
+ return isDir2;
3574
+ };
3575
+ return serveStatic({
3576
+ ...options,
3577
+ getContent,
3578
+ join,
3579
+ isDir
3580
+ })(c, next);
3581
+ };
3582
+ };
3583
+
3584
+ // ../../node_modules/hono/dist/helper/ssg/middleware.js
3585
+ var X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg";
3586
+ var SSG_DISABLED_RESPONSE = (() => {
3587
+ try {
3588
+ return new Response("SSG is disabled", {
3589
+ status: 404,
3590
+ headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" }
3591
+ });
3592
+ } catch {
3593
+ return null;
3594
+ }
3595
+ })();
3596
+ // ../../node_modules/hono/dist/adapter/bun/ssg.js
3597
+ var { write } = Bun;
3598
+
3599
+ // ../../node_modules/hono/dist/helper/websocket/index.js
3600
+ var WSContext = class {
3601
+ #init;
3602
+ constructor(init) {
3603
+ this.#init = init;
3604
+ this.raw = init.raw;
3605
+ this.url = init.url ? new URL(init.url) : null;
3606
+ this.protocol = init.protocol ?? null;
3607
+ }
3608
+ send(source, options) {
3609
+ this.#init.send(source, options ?? {});
3610
+ }
3611
+ raw;
3612
+ binaryType = "arraybuffer";
3613
+ get readyState() {
3614
+ return this.#init.readyState;
3615
+ }
3616
+ url;
3617
+ protocol;
3618
+ close(code, reason) {
3619
+ this.#init.close(code, reason);
3620
+ }
3621
+ };
3622
+ var defineWebSocketHelper = (handler) => {
3623
+ return (...args) => {
3624
+ if (typeof args[0] === "function") {
3625
+ const [createEvents, options] = args;
3626
+ return async function upgradeWebSocket(c, next) {
3627
+ const events = await createEvents(c);
3628
+ const result = await handler(c, events, options);
3629
+ if (result) {
3630
+ return result;
3631
+ }
3632
+ await next();
3633
+ };
3634
+ } else {
3635
+ const [c, events, options] = args;
3636
+ return (async () => {
3637
+ const upgraded = await handler(c, events, options);
3638
+ if (!upgraded) {
3639
+ throw new Error("Failed to upgrade WebSocket");
3640
+ }
3641
+ return upgraded;
3642
+ })();
3643
+ }
3644
+ };
3645
+ };
3646
+
3647
+ // ../../node_modules/hono/dist/adapter/bun/server.js
3648
+ var getBunServer = (c) => ("server" in c.env) ? c.env.server : c.env;
3649
+
3650
+ // ../../node_modules/hono/dist/adapter/bun/websocket.js
3651
+ var upgradeWebSocket = defineWebSocketHelper((c, events) => {
3652
+ const server = getBunServer(c);
3653
+ if (!server) {
3654
+ throw new TypeError("env has to include the 2nd argument of fetch.");
3655
+ }
3656
+ const upgradeResult = server.upgrade(c.req.raw, {
3657
+ data: {
3658
+ events,
3659
+ url: new URL(c.req.url),
3660
+ protocol: c.req.url
3661
+ }
3662
+ });
3663
+ if (upgradeResult) {
3664
+ return new Response(null);
3665
+ }
3666
+ return;
3667
+ });
3668
+
3669
+ // ../../node_modules/hono/dist/middleware/cors/index.js
3670
+ var cors = (options) => {
3671
+ const defaults = {
3672
+ origin: "*",
3673
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
3674
+ allowHeaders: [],
3675
+ exposeHeaders: []
3676
+ };
3677
+ const opts = {
3678
+ ...defaults,
3679
+ ...options
3680
+ };
3681
+ const findAllowOrigin = ((optsOrigin) => {
3682
+ if (typeof optsOrigin === "string") {
3683
+ if (optsOrigin === "*") {
3684
+ return () => optsOrigin;
3685
+ } else {
3686
+ return (origin) => optsOrigin === origin ? origin : null;
3687
+ }
3688
+ } else if (typeof optsOrigin === "function") {
3689
+ return optsOrigin;
3690
+ } else {
3691
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
3692
+ }
3693
+ })(opts.origin);
3694
+ const findAllowMethods = ((optsAllowMethods) => {
3695
+ if (typeof optsAllowMethods === "function") {
3696
+ return optsAllowMethods;
3697
+ } else if (Array.isArray(optsAllowMethods)) {
3698
+ return () => optsAllowMethods;
3699
+ } else {
3700
+ return () => [];
3701
+ }
3702
+ })(opts.allowMethods);
3703
+ return async function cors2(c, next) {
3704
+ function set(key, value) {
3705
+ c.res.headers.set(key, value);
3706
+ }
3707
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
3708
+ if (allowOrigin) {
3709
+ set("Access-Control-Allow-Origin", allowOrigin);
3710
+ }
3711
+ if (opts.credentials) {
3712
+ set("Access-Control-Allow-Credentials", "true");
3713
+ }
3714
+ if (opts.exposeHeaders?.length) {
3715
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
3716
+ }
3717
+ if (c.req.method === "OPTIONS") {
3718
+ if (opts.origin !== "*") {
3719
+ set("Vary", "Origin");
3720
+ }
3721
+ if (opts.maxAge != null) {
3722
+ set("Access-Control-Max-Age", opts.maxAge.toString());
3723
+ }
3724
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
3725
+ if (allowMethods.length) {
3726
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
3727
+ }
3728
+ let headers = opts.allowHeaders;
3729
+ if (!headers?.length) {
3730
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
3731
+ if (requestHeaders) {
3732
+ headers = requestHeaders.split(/\s*,\s*/);
3733
+ }
3734
+ }
3735
+ if (headers?.length) {
3736
+ set("Access-Control-Allow-Headers", headers.join(","));
3737
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
3738
+ }
3739
+ c.res.headers.delete("Content-Length");
3740
+ c.res.headers.delete("Content-Type");
3741
+ return new Response(null, {
3742
+ headers: c.res.headers,
3743
+ status: 204,
3744
+ statusText: "No Content"
3745
+ });
3746
+ }
3747
+ await next();
3748
+ if (opts.origin !== "*") {
3749
+ c.header("Vary", "Origin", { append: true });
3750
+ }
3751
+ };
3752
+ };
3753
+
3754
+ // src/server.ts
3755
+ import path from "path";
3756
+
3757
+ // src/pending/store.ts
3758
+ import { randomUUID } from "crypto";
3759
+ var pending = new Map;
3760
+ var REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
3761
+ function createPendingTransaction(jsonRpcId, transaction) {
3762
+ const id = randomUUID();
3763
+ const request = {
3764
+ type: "transaction",
3765
+ id,
3766
+ jsonRpcId,
3767
+ transaction,
3768
+ createdAt: Date.now()
3769
+ };
3770
+ return createPendingEntry(id, request);
3771
+ }
3772
+ function createPendingSignTypedData(jsonRpcId, address, typedData) {
3773
+ const id = randomUUID();
3774
+ const request = {
3775
+ type: "signTypedData",
3776
+ id,
3777
+ jsonRpcId,
3778
+ request: { address, typedData },
3779
+ createdAt: Date.now()
3780
+ };
3781
+ return createPendingEntry(id, request);
3782
+ }
3783
+ function createPendingSign(jsonRpcId, address, message) {
3784
+ const id = randomUUID();
3785
+ const request = {
3786
+ type: "sign",
3787
+ id,
3788
+ jsonRpcId,
3789
+ address,
3790
+ message,
3791
+ createdAt: Date.now()
3792
+ };
3793
+ return createPendingEntry(id, request);
3794
+ }
3795
+ function createPendingEntry(id, request) {
3796
+ let resolvePromise;
3797
+ const promise = new Promise((resolve) => {
3798
+ resolvePromise = resolve;
3799
+ });
3800
+ pending.set(id, {
3801
+ request,
3802
+ resolve: resolvePromise
3803
+ });
3804
+ console.log(`\uD83D\uDD10 Pending saved: id=${id} type=${request.type} jsonrpc=${request.jsonRpcId}`);
3805
+ setTimeout(() => {
3806
+ const entry = pending.get(id);
3807
+ if (entry) {
3808
+ entry.resolve({
3809
+ success: false,
3810
+ error: "Request timed out"
3811
+ });
3812
+ pending.delete(id);
3813
+ }
3814
+ }, REQUEST_TIMEOUT_MS);
3815
+ return { id, promise };
3816
+ }
3817
+ function getPendingRequest(id) {
3818
+ return pending.get(id)?.request;
3819
+ }
3820
+ function resolvePendingRequest(id, result) {
3821
+ const entry = pending.get(id);
3822
+ if (!entry) {
3823
+ return false;
3824
+ }
3825
+ entry.resolve(result);
3826
+ pending.delete(id);
3827
+ return true;
3828
+ }
3829
+ function getAllPendingIds() {
3830
+ return Array.from(pending.keys());
3831
+ }
3832
+
3833
+ // src/api/routes.ts
3834
+ var api = new Hono2;
3835
+ api.use("/*", cors());
3836
+ api.get("/pending/:id", (c) => {
3837
+ const { id } = c.req.param();
3838
+ const request = getPendingRequest(id);
3839
+ if (!request) {
3840
+ return c.json({ error: "Request not found or expired" }, 404);
3841
+ }
3842
+ return c.json(request);
3843
+ });
3844
+ api.post("/tx/:id/hash", async (c) => {
3845
+ const { id } = c.req.param();
3846
+ let body = null;
3847
+ try {
3848
+ body = await c.req.json();
3849
+ } catch (err) {
3850
+ return c.json({ error: "Invalid JSON payload" }, 400);
3851
+ }
3852
+ if (!body?.hash) {
3853
+ return c.json({ error: "Missing hash" }, 400);
3854
+ }
3855
+ const request = getPendingRequest(id);
3856
+ if (!request) {
3857
+ console.warn(`\uD83D\uDD10 Pending missing: id=${id} hash=${body.hash}`);
3858
+ return c.json({ error: "Request not found or expired" }, 404);
3859
+ }
3860
+ console.log(`\uD83D\uDD10 Tx submitted: ${body.hash}`);
3861
+ return c.json({ ok: true });
3862
+ });
3863
+ api.post("/complete/:id", async (c) => {
3864
+ const { id } = c.req.param();
3865
+ const body = await c.req.json();
3866
+ const resolved = resolvePendingRequest(id, {
3867
+ success: body.success,
3868
+ result: body.result,
3869
+ error: body.error
3870
+ });
3871
+ if (!resolved) {
3872
+ return c.json({ error: "Request not found or already completed" }, 404);
3873
+ }
3874
+ return c.json({ ok: true });
3875
+ });
3876
+ api.get("/pending", (c) => {
3877
+ const ids = getAllPendingIds();
3878
+ return c.json({ pending: ids });
3879
+ });
3880
+
3881
+ // src/rpc/methods.ts
3882
+ var INTERCEPTED_METHODS = new Set([
3883
+ "eth_sendTransaction",
3884
+ "eth_signTypedData",
3885
+ "eth_signTypedData_v3",
3886
+ "eth_signTypedData_v4",
3887
+ "eth_sign",
3888
+ "personal_sign"
3889
+ ]);
3890
+ var PASSTHROUGH_METHODS = new Set([
3891
+ "eth_call",
3892
+ "eth_estimateGas",
3893
+ "eth_chainId",
3894
+ "eth_blockNumber",
3895
+ "eth_getBalance",
3896
+ "eth_getTransactionReceipt",
3897
+ "eth_getTransactionByHash",
3898
+ "eth_getBlockByNumber",
3899
+ "eth_getBlockByHash",
3900
+ "eth_gasPrice",
3901
+ "eth_maxPriorityFeePerGas",
3902
+ "eth_getCode",
3903
+ "eth_getStorageAt",
3904
+ "eth_getTransactionCount",
3905
+ "eth_getLogs",
3906
+ "eth_accounts",
3907
+ "eth_requestAccounts",
3908
+ "net_version",
3909
+ "web3_clientVersion"
3910
+ ]);
3911
+ function shouldIntercept(method) {
3912
+ return INTERCEPTED_METHODS.has(method);
3913
+ }
3914
+ function getInterceptedMethodType(method) {
3915
+ switch (method) {
3916
+ case "eth_sendTransaction":
3917
+ return "transaction";
3918
+ case "eth_signTypedData":
3919
+ case "eth_signTypedData_v3":
3920
+ case "eth_signTypedData_v4":
3921
+ return "signTypedData";
3922
+ case "eth_sign":
3923
+ case "personal_sign":
3924
+ return "sign";
3925
+ default:
3926
+ return null;
3927
+ }
3928
+ }
3929
+
3930
+ // src/rpc/handler.ts
3931
+ async function handleRpcRequest(request, config) {
3932
+ const { method, params, id } = request;
3933
+ if (shouldIntercept(method)) {
3934
+ return handleInterceptedMethod(request, config);
3935
+ }
3936
+ return forwardToUpstream(request, config.upstreamRpcUrl);
3937
+ }
3938
+ async function handleInterceptedMethod(request, config) {
3939
+ const { method, params, id } = request;
3940
+ const methodType = getInterceptedMethodType(method);
3941
+ if (!methodType) {
3942
+ return {
3943
+ jsonrpc: "2.0",
3944
+ id,
3945
+ error: {
3946
+ code: -32601,
3947
+ message: `Method ${method} not supported`
3948
+ }
3949
+ };
3950
+ }
3951
+ try {
3952
+ switch (methodType) {
3953
+ case "transaction": {
3954
+ const tx = params?.[0] || {};
3955
+ const pending2 = createPendingTransaction(id, tx);
3956
+ const url = `${config.uiBaseUrl}/tx/${pending2.id}`;
3957
+ config.onPendingRequest(pending2.id, url);
3958
+ const result = await pending2.promise;
3959
+ if (result.success) {
3960
+ return {
3961
+ jsonrpc: "2.0",
3962
+ id,
3963
+ result: result.result
3964
+ };
3965
+ } else {
3966
+ return {
3967
+ jsonrpc: "2.0",
3968
+ id,
3969
+ error: {
3970
+ code: 4001,
3971
+ message: result.error || "User rejected request"
3972
+ }
3973
+ };
3974
+ }
3975
+ }
3976
+ case "signTypedData": {
3977
+ const address = params?.[0] || "";
3978
+ const typedData = params?.[1];
3979
+ const pending2 = createPendingSignTypedData(id, address, typedData);
3980
+ const url = `${config.uiBaseUrl}/tx/${pending2.id}`;
3981
+ config.onPendingRequest(pending2.id, url);
3982
+ const result = await pending2.promise;
3983
+ if (result.success) {
3984
+ return {
3985
+ jsonrpc: "2.0",
3986
+ id,
3987
+ result: result.result
3988
+ };
3989
+ } else {
3990
+ return {
3991
+ jsonrpc: "2.0",
3992
+ id,
3993
+ error: {
3994
+ code: 4001,
3995
+ message: result.error || "User rejected request"
3996
+ }
3997
+ };
3998
+ }
3999
+ }
4000
+ case "sign": {
4001
+ let address;
4002
+ let message;
4003
+ if (method === "personal_sign") {
4004
+ message = params?.[0] || "";
4005
+ address = params?.[1] || "";
4006
+ } else {
4007
+ address = params?.[0] || "";
4008
+ message = params?.[1] || "";
4009
+ }
4010
+ const pending2 = createPendingSign(id, address, message);
4011
+ const url = `${config.uiBaseUrl}/tx/${pending2.id}`;
4012
+ config.onPendingRequest(pending2.id, url);
4013
+ const result = await pending2.promise;
4014
+ if (result.success) {
4015
+ return {
4016
+ jsonrpc: "2.0",
4017
+ id,
4018
+ result: result.result
4019
+ };
4020
+ } else {
4021
+ return {
4022
+ jsonrpc: "2.0",
4023
+ id,
4024
+ error: {
4025
+ code: 4001,
4026
+ message: result.error || "User rejected request"
4027
+ }
4028
+ };
4029
+ }
4030
+ }
4031
+ }
4032
+ } catch (error) {
4033
+ return {
4034
+ jsonrpc: "2.0",
4035
+ id,
4036
+ error: {
4037
+ code: -32603,
4038
+ message: error instanceof Error ? error.message : "Internal error"
4039
+ }
4040
+ };
4041
+ }
4042
+ }
4043
+ async function forwardToUpstream(request, upstreamUrl) {
4044
+ try {
4045
+ const response = await fetch(upstreamUrl, {
4046
+ method: "POST",
4047
+ headers: {
4048
+ "Content-Type": "application/json"
4049
+ },
4050
+ body: JSON.stringify(request)
4051
+ });
4052
+ if (!response.ok) {
4053
+ return {
4054
+ jsonrpc: "2.0",
4055
+ id: request.id,
4056
+ error: {
4057
+ code: -32603,
4058
+ message: `Upstream RPC error: ${response.status} ${response.statusText}`
4059
+ }
4060
+ };
4061
+ }
4062
+ return await response.json();
4063
+ } catch (error) {
4064
+ return {
4065
+ jsonrpc: "2.0",
4066
+ id: request.id,
4067
+ error: {
4068
+ code: -32603,
4069
+ message: error instanceof Error ? `Upstream RPC error: ${error.message}` : "Failed to connect to upstream RPC"
4070
+ }
4071
+ };
4072
+ }
4073
+ }
4074
+
4075
+ // src/server.ts
4076
+ function resolveWebDistPath() {
4077
+ const bundledPath = path.resolve(import.meta.dir, "../web-dist");
4078
+ const devPath = path.resolve(import.meta.dir, "../../web/dist");
4079
+ if (existsSync(bundledPath))
4080
+ return bundledPath;
4081
+ return devPath;
4082
+ }
4083
+ var webDistPath = resolveWebDistPath();
4084
+ function createServer(config) {
4085
+ const app = new Hono2;
4086
+ app.use("*", cors());
4087
+ app.use("*", async (c, next) => {
4088
+ await next();
4089
+ });
4090
+ app.route("/api", api);
4091
+ const handleRpc = async (c) => {
4092
+ try {
4093
+ const body = await c.req.json();
4094
+ if (Array.isArray(body)) {
4095
+ const methods = body.map((req) => req.method).join(", ");
4096
+ console.log(` RPC batch: [${methods}]`);
4097
+ const responses = await Promise.all(body.map((req) => handleRpcRequest(req, {
4098
+ upstreamRpcUrl: config.upstreamRpcUrl,
4099
+ uiBaseUrl: `http://localhost:${config.port}`,
4100
+ onPendingRequest: config.onPendingRequest
4101
+ })));
4102
+ return c.json(responses);
4103
+ }
4104
+ console.log(` RPC: ${body.method}`);
4105
+ const response = await handleRpcRequest(body, {
4106
+ upstreamRpcUrl: config.upstreamRpcUrl,
4107
+ uiBaseUrl: `http://localhost:${config.port}`,
4108
+ onPendingRequest: config.onPendingRequest
4109
+ });
4110
+ return c.json(response);
4111
+ } catch (error) {
4112
+ return c.json({
4113
+ jsonrpc: "2.0",
4114
+ id: null,
4115
+ error: {
4116
+ code: -32700,
4117
+ message: "Parse error"
4118
+ }
4119
+ }, 400);
4120
+ }
4121
+ };
4122
+ app.post("/", handleRpc);
4123
+ app.post("/rpc", handleRpc);
4124
+ app.get("/health", (c) => c.json({ ok: true }));
4125
+ app.use("/assets/*", serveStatic2({ root: webDistPath }));
4126
+ app.get("*", async (c) => {
4127
+ const indexPath = path.join(webDistPath, "index.html");
4128
+ const file = Bun.file(indexPath);
4129
+ if (await file.exists()) {
4130
+ return c.html(await file.text());
4131
+ }
4132
+ return c.text("Web UI not found. Run 'bun run build' in packages/web first.", 404);
4133
+ });
4134
+ return app;
4135
+ }
4136
+
4137
+ // src/index.ts
4138
+ program.name("browser-rpc").description("Local RPC proxy for secure transaction signing via browser wallet").requiredOption("-r, --rpc <url>", "Upstream RPC URL for read calls").option("-p, --port <number>", "Server port", "8545").option("--no-open", "Disable auto-opening browser for transactions").parse();
4139
+ var options = program.opts();
4140
+ var port = parseInt(options.port, 10);
4141
+ async function openBrowser(url) {
4142
+ const args = [url];
4143
+ let command;
4144
+ if (process.platform === "darwin") {
4145
+ command = "open";
4146
+ } else if (process.platform === "win32") {
4147
+ command = "cmd";
4148
+ args.unshift("/c", "start", "");
4149
+ } else {
4150
+ command = "xdg-open";
4151
+ }
4152
+ try {
4153
+ Bun.spawn([command, ...args]);
4154
+ } catch (error) {
4155
+ console.error(`Failed to open browser: ${error}`);
4156
+ }
4157
+ }
4158
+ var server = createServer({
4159
+ upstreamRpcUrl: options.rpc,
4160
+ port,
4161
+ onPendingRequest: (id, url) => {
4162
+ console.log(`
4163
+ \uD83D\uDD10 Transaction pending: ${url}`);
4164
+ if (options.open) {
4165
+ openBrowser(url);
4166
+ }
4167
+ }
4168
+ });
4169
+ Bun.serve({
4170
+ fetch: server.fetch,
4171
+ port
4172
+ });
4173
+ console.log(`
4174
+ \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
4175
+ \u2551 browser-rpc \u2551
4176
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
4177
+
4178
+ Server: http://localhost:${port}
4179
+ Upstream: ${options.rpc}
4180
+ Auto-open: ${options.open ? "enabled" : "disabled"}
4181
+
4182
+ Use http://localhost:${port} as your RPC URL in Foundry/Hardhat.
4183
+
4184
+ Example:
4185
+ forge script script/Deploy.s.sol --rpc-url http://localhost:${port}
4186
+
4187
+ `);