@mtcute/dispatcher 0.16.7 → 0.16.13

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 (237) hide show
  1. package/{cjs/callback-data-builder.d.ts → callback-data-builder.d.ts} +2 -2
  2. package/callback-data-builder.test.d.ts +1 -0
  3. package/{esm/context → context}/base.d.ts +2 -2
  4. package/{esm/context → context}/business-message.d.ts +5 -6
  5. package/{esm/context → context}/callback-query.d.ts +6 -7
  6. package/{cjs/context → context}/chat-join-request.d.ts +3 -3
  7. package/{esm/context → context}/chosen-inline-result.d.ts +3 -3
  8. package/{esm/context → context}/inline-query.d.ts +4 -5
  9. package/{cjs/context → context}/message.d.ts +11 -6
  10. package/{cjs/context → context}/parse.d.ts +3 -3
  11. package/{esm/context → context}/pre-checkout-query.d.ts +3 -3
  12. package/{esm/context → context}/scene-transition.d.ts +1 -1
  13. package/{cjs/dispatcher.d.ts → dispatcher.d.ts} +9 -10
  14. package/{cjs/filters → filters}/bots.d.ts +4 -4
  15. package/filters/bots.test.d.ts +1 -0
  16. package/{cjs/filters → filters}/chat.d.ts +3 -3
  17. package/{esm/filters → filters}/group.d.ts +4 -4
  18. package/{cjs/filters → filters}/logic.d.ts +1 -1
  19. package/filters/logic.test.d.ts +1 -0
  20. package/{esm/filters → filters}/message.d.ts +9 -5
  21. package/{cjs/filters → filters}/state.d.ts +2 -2
  22. package/{esm/filters → filters}/text.d.ts +3 -3
  23. package/{cjs/filters → filters}/types.d.ts +2 -2
  24. package/{cjs/filters → filters}/updates.d.ts +2 -2
  25. package/{cjs/filters → filters}/user.d.ts +3 -4
  26. package/{cjs/handler.d.ts → handler.d.ts} +5 -5
  27. package/index.cjs +2534 -0
  28. package/index.d.ts +8 -1
  29. package/index.js +2529 -1
  30. package/package.json +28 -24
  31. package/{cjs/state → state}/key.d.ts +3 -3
  32. package/state/provider.d.ts +5 -0
  33. package/{cjs/state → state}/providers/memory.d.ts +3 -4
  34. package/{esm/state → state}/providers/sqlite.d.ts +3 -3
  35. package/{cjs/state → state}/repository.d.ts +1 -1
  36. package/{esm/state → state}/service.d.ts +2 -2
  37. package/{cjs/state → state}/update-state.d.ts +2 -2
  38. package/{esm/wizard.d.ts → wizard.d.ts} +5 -6
  39. package/cjs/callback-data-builder.js +0 -141
  40. package/cjs/callback-data-builder.js.map +0 -1
  41. package/cjs/context/base.d.ts +0 -9
  42. package/cjs/context/base.js +0 -3
  43. package/cjs/context/base.js.map +0 -1
  44. package/cjs/context/business-message.d.ts +0 -61
  45. package/cjs/context/business-message.js +0 -146
  46. package/cjs/context/business-message.js.map +0 -1
  47. package/cjs/context/callback-query.d.ts +0 -63
  48. package/cjs/context/callback-query.js +0 -109
  49. package/cjs/context/callback-query.js.map +0 -1
  50. package/cjs/context/chat-join-request.js +0 -35
  51. package/cjs/context/chat-join-request.js.map +0 -1
  52. package/cjs/context/chosen-inline-result.d.ts +0 -22
  53. package/cjs/context/chosen-inline-result.js +0 -36
  54. package/cjs/context/chosen-inline-result.js.map +0 -1
  55. package/cjs/context/index.js +0 -25
  56. package/cjs/context/index.js.map +0 -1
  57. package/cjs/context/inline-query.d.ts +0 -16
  58. package/cjs/context/inline-query.js +0 -23
  59. package/cjs/context/inline-query.js.map +0 -1
  60. package/cjs/context/message.js +0 -171
  61. package/cjs/context/message.js.map +0 -1
  62. package/cjs/context/parse.js +0 -42
  63. package/cjs/context/parse.js.map +0 -1
  64. package/cjs/context/pre-checkout-query.d.ts +0 -17
  65. package/cjs/context/pre-checkout-query.js +0 -27
  66. package/cjs/context/pre-checkout-query.js.map +0 -1
  67. package/cjs/context/scene-transition.d.ts +0 -24
  68. package/cjs/context/scene-transition.js +0 -52
  69. package/cjs/context/scene-transition.js.map +0 -1
  70. package/cjs/dispatcher.js +0 -908
  71. package/cjs/dispatcher.js.map +0 -1
  72. package/cjs/filters/bots.js +0 -135
  73. package/cjs/filters/bots.js.map +0 -1
  74. package/cjs/filters/bundle.js +0 -27
  75. package/cjs/filters/bundle.js.map +0 -1
  76. package/cjs/filters/chat.js +0 -56
  77. package/cjs/filters/chat.js.map +0 -1
  78. package/cjs/filters/group.d.ts +0 -26
  79. package/cjs/filters/group.js +0 -69
  80. package/cjs/filters/group.js.map +0 -1
  81. package/cjs/filters/index.js +0 -29
  82. package/cjs/filters/index.js.map +0 -1
  83. package/cjs/filters/logic.js +0 -112
  84. package/cjs/filters/logic.js.map +0 -1
  85. package/cjs/filters/message.d.ts +0 -215
  86. package/cjs/filters/message.js +0 -191
  87. package/cjs/filters/message.js.map +0 -1
  88. package/cjs/filters/state.js +0 -33
  89. package/cjs/filters/state.js.map +0 -1
  90. package/cjs/filters/text.d.ts +0 -64
  91. package/cjs/filters/text.js +0 -136
  92. package/cjs/filters/text.js.map +0 -1
  93. package/cjs/filters/types.js +0 -3
  94. package/cjs/filters/types.js.map +0 -1
  95. package/cjs/filters/updates.js +0 -40
  96. package/cjs/filters/updates.js.map +0 -1
  97. package/cjs/filters/user.js +0 -77
  98. package/cjs/filters/user.js.map +0 -1
  99. package/cjs/handler.js +0 -4
  100. package/cjs/handler.js.map +0 -1
  101. package/cjs/index.js +0 -31
  102. package/cjs/index.js.map +0 -1
  103. package/cjs/package.json +0 -3
  104. package/cjs/propagation.js +0 -27
  105. package/cjs/propagation.js.map +0 -1
  106. package/cjs/state/index.js +0 -22
  107. package/cjs/state/index.js.map +0 -1
  108. package/cjs/state/key.js +0 -43
  109. package/cjs/state/key.js.map +0 -1
  110. package/cjs/state/provider.d.ts +0 -5
  111. package/cjs/state/provider.js +0 -3
  112. package/cjs/state/provider.js.map +0 -1
  113. package/cjs/state/providers/index.js +0 -19
  114. package/cjs/state/providers/index.js.map +0 -1
  115. package/cjs/state/providers/memory.js +0 -81
  116. package/cjs/state/providers/memory.js.map +0 -1
  117. package/cjs/state/providers/sqlite.d.ts +0 -28
  118. package/cjs/state/providers/sqlite.js +0 -100
  119. package/cjs/state/providers/sqlite.js.map +0 -1
  120. package/cjs/state/repository.js +0 -3
  121. package/cjs/state/repository.js.map +0 -1
  122. package/cjs/state/service.d.ts +0 -20
  123. package/cjs/state/service.js +0 -70
  124. package/cjs/state/service.js.map +0 -1
  125. package/cjs/state/update-state.js +0 -219
  126. package/cjs/state/update-state.js.map +0 -1
  127. package/cjs/wizard.d.ts +0 -65
  128. package/cjs/wizard.js +0 -105
  129. package/cjs/wizard.js.map +0 -1
  130. package/esm/callback-data-builder.d.ts +0 -49
  131. package/esm/callback-data-builder.js +0 -137
  132. package/esm/callback-data-builder.js.map +0 -1
  133. package/esm/context/base.js +0 -2
  134. package/esm/context/base.js.map +0 -1
  135. package/esm/context/business-message.js +0 -142
  136. package/esm/context/business-message.js.map +0 -1
  137. package/esm/context/callback-query.js +0 -103
  138. package/esm/context/callback-query.js.map +0 -1
  139. package/esm/context/chat-join-request.d.ts +0 -17
  140. package/esm/context/chat-join-request.js +0 -31
  141. package/esm/context/chat-join-request.js.map +0 -1
  142. package/esm/context/chosen-inline-result.js +0 -32
  143. package/esm/context/chosen-inline-result.js.map +0 -1
  144. package/esm/context/index.d.ts +0 -9
  145. package/esm/context/index.js +0 -9
  146. package/esm/context/index.js.map +0 -1
  147. package/esm/context/inline-query.js +0 -19
  148. package/esm/context/inline-query.js.map +0 -1
  149. package/esm/context/message.d.ts +0 -77
  150. package/esm/context/message.js +0 -167
  151. package/esm/context/message.js.map +0 -1
  152. package/esm/context/parse.d.ts +0 -13
  153. package/esm/context/parse.js +0 -39
  154. package/esm/context/parse.js.map +0 -1
  155. package/esm/context/pre-checkout-query.js +0 -23
  156. package/esm/context/pre-checkout-query.js.map +0 -1
  157. package/esm/context/scene-transition.js +0 -48
  158. package/esm/context/scene-transition.js.map +0 -1
  159. package/esm/dispatcher.d.ts +0 -881
  160. package/esm/dispatcher.js +0 -904
  161. package/esm/dispatcher.js.map +0 -1
  162. package/esm/filters/bots.d.ts +0 -64
  163. package/esm/filters/bots.js +0 -131
  164. package/esm/filters/bots.js.map +0 -1
  165. package/esm/filters/bundle.d.ts +0 -10
  166. package/esm/filters/bundle.js +0 -11
  167. package/esm/filters/bundle.js.map +0 -1
  168. package/esm/filters/chat.d.ts +0 -27
  169. package/esm/filters/chat.js +0 -51
  170. package/esm/filters/chat.js.map +0 -1
  171. package/esm/filters/group.js +0 -65
  172. package/esm/filters/group.js.map +0 -1
  173. package/esm/filters/index.d.ts +0 -4
  174. package/esm/filters/index.js +0 -3
  175. package/esm/filters/index.js.map +0 -1
  176. package/esm/filters/logic.d.ts +0 -29
  177. package/esm/filters/logic.js +0 -105
  178. package/esm/filters/logic.js.map +0 -1
  179. package/esm/filters/message.js +0 -168
  180. package/esm/filters/message.js.map +0 -1
  181. package/esm/filters/state.d.ts +0 -15
  182. package/esm/filters/state.js +0 -28
  183. package/esm/filters/state.js.map +0 -1
  184. package/esm/filters/text.js +0 -129
  185. package/esm/filters/text.js.map +0 -1
  186. package/esm/filters/types.d.ts +0 -91
  187. package/esm/filters/types.js +0 -2
  188. package/esm/filters/types.js.map +0 -1
  189. package/esm/filters/updates.d.ts +0 -39
  190. package/esm/filters/updates.js +0 -34
  191. package/esm/filters/updates.js.map +0 -1
  192. package/esm/filters/user.d.ts +0 -25
  193. package/esm/filters/user.js +0 -71
  194. package/esm/filters/user.js.map +0 -1
  195. package/esm/handler.d.ts +0 -41
  196. package/esm/handler.js +0 -3
  197. package/esm/handler.js.map +0 -1
  198. package/esm/index.d.ts +0 -8
  199. package/esm/index.js +0 -9
  200. package/esm/index.js.map +0 -1
  201. package/esm/propagation.d.ts +0 -22
  202. package/esm/propagation.js +0 -24
  203. package/esm/propagation.js.map +0 -1
  204. package/esm/state/index.d.ts +0 -5
  205. package/esm/state/index.js +0 -6
  206. package/esm/state/index.js.map +0 -1
  207. package/esm/state/key.d.ts +0 -24
  208. package/esm/state/key.js +0 -39
  209. package/esm/state/key.js.map +0 -1
  210. package/esm/state/provider.d.ts +0 -5
  211. package/esm/state/provider.js +0 -2
  212. package/esm/state/provider.js.map +0 -1
  213. package/esm/state/providers/index.d.ts +0 -2
  214. package/esm/state/providers/index.js +0 -3
  215. package/esm/state/providers/index.js.map +0 -1
  216. package/esm/state/providers/memory.d.ts +0 -30
  217. package/esm/state/providers/memory.js +0 -77
  218. package/esm/state/providers/memory.js.map +0 -1
  219. package/esm/state/providers/sqlite.js +0 -96
  220. package/esm/state/providers/sqlite.js.map +0 -1
  221. package/esm/state/repository.d.ts +0 -62
  222. package/esm/state/repository.js +0 -2
  223. package/esm/state/repository.js.map +0 -1
  224. package/esm/state/service.js +0 -66
  225. package/esm/state/service.js.map +0 -1
  226. package/esm/state/update-state.d.ts +0 -151
  227. package/esm/state/update-state.js +0 -214
  228. package/esm/state/update-state.js.map +0 -1
  229. package/esm/wizard.js +0 -101
  230. package/esm/wizard.js.map +0 -1
  231. /package/{cjs/context → context}/index.d.ts +0 -0
  232. /package/{cjs/filters → filters}/bundle.d.ts +0 -0
  233. /package/{cjs/filters → filters}/index.d.ts +0 -0
  234. /package/{cjs/index.d.ts → index.d.cts} +0 -0
  235. /package/{cjs/propagation.d.ts → propagation.d.ts} +0 -0
  236. /package/{cjs/state → state}/index.d.ts +0 -0
  237. /package/{cjs/state → state}/providers/index.d.ts +0 -0
package/index.cjs ADDED
@@ -0,0 +1,2534 @@
1
+ if (typeof globalThis !== "undefined" && !globalThis._MTCUTE_CJS_DEPRECATION_WARNED) {
2
+ globalThis._MTCUTE_CJS_DEPRECATION_WARNED = true;
3
+ console.warn("[@mtcute/dispatcher] CommonJS support is deprecated and will be removed soon. Please consider switching to ESM, it's " + (/* @__PURE__ */ new Date()).getFullYear() + " already.");
4
+ console.warn("[@mtcute/dispatcher] Learn more about switching to ESM: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c");
5
+ }
6
+ "use strict";
7
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
8
+ const core = require("@mtcute/core");
9
+ const utils_js = require("@mtcute/core/utils.js");
10
+ class CallbackDataBuilder {
11
+ /**
12
+ * @param prefix Prefix for the data. Use something unique across your bot.
13
+ * @param fields Field names in the order they will be serialized.
14
+ */
15
+ constructor(prefix, ...fields) {
16
+ this.prefix = prefix;
17
+ this._fields = fields;
18
+ }
19
+ _fields;
20
+ sep = ":";
21
+ /**
22
+ * Build a callback data string
23
+ *
24
+ * @param obj Object containing the data
25
+ */
26
+ build(obj) {
27
+ const ret = this.prefix + this.sep + this._fields.map((f) => {
28
+ const val = obj[f];
29
+ if (val.includes(this.sep)) {
30
+ throw new core.MtArgumentError(
31
+ `Value for ${f} ${val} contains separator ${this.sep} and cannot be used.`
32
+ );
33
+ }
34
+ return val;
35
+ }).join(this.sep);
36
+ if (ret.length > 64) {
37
+ throw new core.MtArgumentError("Resulting callback data is too long.");
38
+ }
39
+ return ret;
40
+ }
41
+ parse(data, safe = false) {
42
+ const parts = data.split(this.sep);
43
+ if (parts[0] !== this.prefix) {
44
+ if (safe) return null;
45
+ throw new core.MtArgumentError(
46
+ `Invalid data passed: "${data}" (bad prefix, expected ${this.prefix}, got ${parts[0]})`
47
+ );
48
+ }
49
+ if (parts.length !== this._fields.length + 1) {
50
+ if (safe) return null;
51
+ throw new core.MtArgumentError(
52
+ `Invalid data passed: "${data}" (bad parts count, expected ${this._fields.length}, got ${parts.length - 1})`
53
+ );
54
+ }
55
+ const ret = {};
56
+ parts.forEach((it, idx) => {
57
+ if (idx === 0) return;
58
+ ret[this._fields[idx - 1]] = it;
59
+ });
60
+ return ret;
61
+ }
62
+ /**
63
+ * Create a filter for this callback data.
64
+ *
65
+ * You can either pass an object with field names as keys and values as strings or regexes,
66
+ * which will be compiled to a RegExp, or a function that will be called with the parsed data.
67
+ * Note that the strings will be passed to `RegExp` **directly**, so you may want to escape them.
68
+ *
69
+ * When using a function, you can either return a boolean, or an object with field names as keys
70
+ * and values as strings or regexes. In the latter case, the resulting object will be matched
71
+ * against the parsed data the same way as if you passed it directly.
72
+ *
73
+ * @param params
74
+ */
75
+ filter(params = {}) {
76
+ if (typeof params === "function") {
77
+ return async (query) => {
78
+ if (!query.dataStr) return false;
79
+ const data = this.parse(query.dataStr, true);
80
+ if (!data) return false;
81
+ const fnResult = await params(query, data);
82
+ if (typeof fnResult === "boolean") {
83
+ query.match = data;
84
+ return fnResult;
85
+ }
86
+ for (const key in fnResult) {
87
+ const value = data[key];
88
+ if (value === void 0) return false;
89
+ let matchers = fnResult[key];
90
+ if (!Array.isArray(matchers)) matchers = [matchers];
91
+ for (const matcher of matchers) {
92
+ if (typeof matcher === "string") {
93
+ if (value !== matcher) return false;
94
+ } else if (!matcher.test(value)) {
95
+ return false;
96
+ }
97
+ }
98
+ }
99
+ query.match = data;
100
+ return true;
101
+ };
102
+ }
103
+ const parts = [];
104
+ this._fields.forEach((field) => {
105
+ if (!(field in params)) {
106
+ parts.push(`[^${this.sep}]*?`);
107
+ return;
108
+ }
109
+ const value = params[field];
110
+ if (Array.isArray(value)) {
111
+ parts.push(`(${value.map((i) => typeof i === "string" ? i : i.source).join("|")})`);
112
+ } else {
113
+ parts.push(typeof value === "string" ? value : value.source);
114
+ }
115
+ });
116
+ const regex2 = new RegExp(`^${this.prefix}${this.sep}${parts.join(this.sep)}$`);
117
+ return (query) => {
118
+ const m = query.dataStr?.match(regex2);
119
+ if (!m) {
120
+ return false;
121
+ }
122
+ query.match = this.parse(m[0]);
123
+ return true;
124
+ };
125
+ }
126
+ }
127
+ class BusinessMessageContext extends core.BusinessMessage {
128
+ constructor(client, message) {
129
+ const msg = Array.isArray(message) ? message[message.length - 1] : message;
130
+ super(msg.update, msg._peers);
131
+ this.client = client;
132
+ this.messages = Array.isArray(message) ? message.map((it) => new BusinessMessageContext(client, it)) : [this];
133
+ this.isMessageGroup = Array.isArray(message);
134
+ }
135
+ // this is primarily for proper types in filters, so don't bother much with actual value
136
+ _name = "new_business_message";
137
+ /**
138
+ * List of messages in the message group.
139
+ *
140
+ * For other updates, this is a list with a single element (`this`).
141
+ */
142
+ messages;
143
+ /** Whether this update is about a message group */
144
+ isMessageGroup;
145
+ /** Get all custom emojis contained in this message (message group), if any */
146
+ getCustomEmojis() {
147
+ return this.client.getCustomEmojisFromMessages(this.messages);
148
+ }
149
+ /** Send a text message to the same chat (and topic, if applicable) as a given message */
150
+ answerText(...params) {
151
+ const [send, params_ = {}] = params;
152
+ params_.businessConnectionId = this.update.connectionId;
153
+ return this.client.answerText(this, send, params_);
154
+ }
155
+ /** Send a media to the same chat (and topic, if applicable) as a given message */
156
+ answerMedia(...params) {
157
+ const [send, params_ = {}] = params;
158
+ params_.businessConnectionId = this.update.connectionId;
159
+ return this.client.answerMedia(this, send, params_);
160
+ }
161
+ /** Send a media group to the same chat (and topic, if applicable) as a given message */
162
+ answerMediaGroup(...params) {
163
+ const [send, params_ = {}] = params;
164
+ params_.businessConnectionId = this.update.connectionId;
165
+ return this.client.answerMediaGroup(this, send, params_);
166
+ }
167
+ /** Send a text message in reply to this message */
168
+ replyText(...params) {
169
+ const [send, params_ = {}] = params;
170
+ params_.businessConnectionId = this.update.connectionId;
171
+ return this.client.replyText(this, send, params_);
172
+ }
173
+ /** Send a media in reply to this message */
174
+ replyMedia(...params) {
175
+ const [send, params_ = {}] = params;
176
+ params_.businessConnectionId = this.update.connectionId;
177
+ return this.client.replyMedia(this, send, params_);
178
+ }
179
+ /** Send a media group in reply to this message */
180
+ replyMediaGroup(...params) {
181
+ const [send, params_ = {}] = params;
182
+ params_.businessConnectionId = this.update.connectionId;
183
+ return this.client.replyMediaGroup(this, send, params_);
184
+ }
185
+ /** Send a text message in reply to this message */
186
+ quoteWithText(params) {
187
+ params.businessConnectionId = this.update.connectionId;
188
+ return this.client.quoteWithText(this, params);
189
+ }
190
+ /** Send a media in reply to this message */
191
+ quoteWithMedia(params) {
192
+ params.businessConnectionId = this.update.connectionId;
193
+ return this.client.quoteWithMedia(this, params);
194
+ }
195
+ /** Send a media group in reply to this message */
196
+ quoteWithMediaGroup(params) {
197
+ params.businessConnectionId = this.update.connectionId;
198
+ return this.client.quoteWithMediaGroup(this, params);
199
+ }
200
+ /** Delete this message (message group) */
201
+ delete(params) {
202
+ return this.client.deleteMessagesById(
203
+ this.chat.inputPeer,
204
+ this.messages.map((it) => it.id),
205
+ params
206
+ );
207
+ }
208
+ /** Pin this message */
209
+ pin(params) {
210
+ return this.client.pinMessage({
211
+ chatId: this.chat.inputPeer,
212
+ message: this.id,
213
+ ...params
214
+ });
215
+ }
216
+ /** Unpin this message */
217
+ unpin() {
218
+ return this.client.unpinMessage({
219
+ chatId: this.chat.inputPeer,
220
+ message: this.id
221
+ });
222
+ }
223
+ /** Edit this message */
224
+ edit(params) {
225
+ return this.client.editMessage({
226
+ chatId: this.chat.inputPeer,
227
+ message: this.id,
228
+ ...params
229
+ });
230
+ }
231
+ /** Forward this message (message group) */
232
+ forwardTo(params) {
233
+ return this.client.forwardMessagesById({
234
+ fromChatId: this.chat.inputPeer,
235
+ messages: this.messages.map((it) => it.id),
236
+ ...params
237
+ });
238
+ }
239
+ /** Send a copy of this message (message group) */
240
+ copy(params) {
241
+ if (this.isMessageGroup) {
242
+ return this.client.sendCopyGroup({
243
+ messages: this.messages,
244
+ ...params
245
+ });
246
+ }
247
+ return this.client.sendCopy({
248
+ message: this,
249
+ ...params
250
+ });
251
+ }
252
+ /** React to this message */
253
+ react(params) {
254
+ return this.client.sendReaction({
255
+ chatId: this.chat.inputPeer,
256
+ message: this.id,
257
+ ...params
258
+ });
259
+ }
260
+ }
261
+ class CallbackQueryContext extends core.CallbackQuery {
262
+ constructor(client, query) {
263
+ super(query.raw, query._peers);
264
+ this.client = client;
265
+ }
266
+ _name = "callback_query";
267
+ /** Answer to this callback query */
268
+ answer(params) {
269
+ return this.client.answerCallbackQuery(this.id, params);
270
+ }
271
+ /**
272
+ * Get the message containing the callback button being clicked.
273
+ *
274
+ * Note that the message may have been deleted, in which case
275
+ * `null` will be returned.
276
+ */
277
+ async getMessage() {
278
+ return this.client.getCallbackQueryMessage(this);
279
+ }
280
+ /**
281
+ * Edit the message that contained the callback button that was clicked.
282
+ */
283
+ async editMessage(params) {
284
+ return this.client.editMessage({
285
+ chatId: this.raw.peer,
286
+ message: this.raw.msgId,
287
+ ...params
288
+ });
289
+ }
290
+ /**
291
+ * Shortcut for getting the message and editing it.
292
+ */
293
+ async editMessageWith(handler) {
294
+ const msg = await this.getMessage();
295
+ if (!msg) return;
296
+ const res = await handler(msg);
297
+ if (!res) return;
298
+ return this.editMessage(res);
299
+ }
300
+ }
301
+ class InlineCallbackQueryContext extends core.InlineCallbackQuery {
302
+ constructor(client, query) {
303
+ super(query.raw, query._peers);
304
+ this.client = client;
305
+ }
306
+ _name = "inline_callback_query";
307
+ /** Answer to this callback query */
308
+ answer(params) {
309
+ return this.client.answerCallbackQuery(this.id, params);
310
+ }
311
+ /**
312
+ * Edit the message that contained the callback button that was clicked.
313
+ */
314
+ async editMessage(params) {
315
+ return this.client.editInlineMessage({
316
+ messageId: this.raw.msgId,
317
+ ...params
318
+ });
319
+ }
320
+ }
321
+ class BusinessCallbackQueryContext extends core.BusinessCallbackQuery {
322
+ constructor(client, query) {
323
+ super(query.raw, query._peers);
324
+ this.client = client;
325
+ }
326
+ _name = "business_callback_query";
327
+ /** Answer to this callback query */
328
+ answer(params) {
329
+ return this.client.answerCallbackQuery(this.id, params);
330
+ }
331
+ /**
332
+ * Edit the message that contained the callback button that was clicked.
333
+ */
334
+ async editMessage(params) {
335
+ return this.client.editMessage({
336
+ message: this.message,
337
+ businessConnectionId: this.connectionId,
338
+ ...params
339
+ });
340
+ }
341
+ }
342
+ class ChatJoinRequestUpdateContext extends core.BotChatJoinRequestUpdate {
343
+ constructor(client, update) {
344
+ super(update.raw, update._peers);
345
+ this.client = client;
346
+ }
347
+ _name = "bot_chat_join_request";
348
+ /** Approve the request */
349
+ approve() {
350
+ return this.client.hideJoinRequest({
351
+ action: "approve",
352
+ user: this.user.inputPeer,
353
+ chatId: this.chat.inputPeer
354
+ });
355
+ }
356
+ /** Decline the request */
357
+ decline() {
358
+ return this.client.hideJoinRequest({
359
+ action: "decline",
360
+ user: this.user.inputPeer,
361
+ chatId: this.chat.inputPeer
362
+ });
363
+ }
364
+ }
365
+ class ChosenInlineResultContext extends core.ChosenInlineResult {
366
+ constructor(client, result) {
367
+ super(result.raw, result._peers);
368
+ this.client = client;
369
+ }
370
+ _name = "chosen_inline_result";
371
+ /**
372
+ * Edit the message that was sent when this inline result that was chosen.
373
+ *
374
+ * > **Note**: This method can only be used if the message contained a reply markup
375
+ */
376
+ async editMessage(params) {
377
+ if (!this.raw.msgId) {
378
+ throw new core.MtArgumentError("No message ID, make sure you have included reply markup!");
379
+ }
380
+ return this.client.editInlineMessage({
381
+ ...params,
382
+ messageId: this.raw.msgId
383
+ });
384
+ }
385
+ }
386
+ class InlineQueryContext extends core.InlineQuery {
387
+ constructor(client, query) {
388
+ super(query.raw, query._peers);
389
+ this.client = client;
390
+ }
391
+ _name = "inline_query";
392
+ /** Answer to this inline query */
393
+ answer(...params) {
394
+ return this.client.answerInlineQuery(this.id, ...params);
395
+ }
396
+ }
397
+ class MessageContext extends core.Message {
398
+ constructor(client, message) {
399
+ const msg = Array.isArray(message) ? message[message.length - 1] : message;
400
+ super(msg.raw, msg._peers, msg.isScheduled);
401
+ this.client = client;
402
+ this.messages = Array.isArray(message) ? message.map((it) => new MessageContext(client, it)) : [this];
403
+ this.isMessageGroup = Array.isArray(message);
404
+ }
405
+ // this is primarily for proper types in filters, so don't bother much with actual value
406
+ _name = "new_message";
407
+ /**
408
+ * List of messages in the message group.
409
+ *
410
+ * For other updates, this is a list with a single element (`this`).
411
+ */
412
+ messages;
413
+ /** Whether this update is about a message group */
414
+ isMessageGroup;
415
+ /**
416
+ * Get complete information about {@link sender}
417
+ *
418
+ * Learn more: [Incomplete peers](https://mtcute.dev/guide/topics/peers.html#incomplete-peers)
419
+ */
420
+ async getCompleteSender() {
421
+ if (!this.sender.isMin) return this.sender;
422
+ let res;
423
+ if (this.sender.type === "user") {
424
+ [res] = await this.client.getUsers(this.sender);
425
+ } else {
426
+ res = await this.client.getChat(this.sender);
427
+ }
428
+ if (!res) throw new core.MtPeerNotFoundError("Failed to fetch sender");
429
+ Object.defineProperty(this, "sender", { value: res });
430
+ return res;
431
+ }
432
+ /**
433
+ * Get complete information about {@link chat}
434
+ *
435
+ * Learn more: [Incomplete peers](https://mtcute.dev/guide/topics/peers.html#incomplete-peers)
436
+ */
437
+ async getCompleteChat() {
438
+ if (!this.chat.isMin) return this.chat;
439
+ const res = await this.client.getChat(this.chat);
440
+ if (!res) throw new core.MtPeerNotFoundError("Failed to fetch chat");
441
+ Object.defineProperty(this, "chat", { value: res });
442
+ return res;
443
+ }
444
+ /** Get a message that this message is a reply to */
445
+ getReplyTo() {
446
+ return this.client.getReplyTo(this);
447
+ }
448
+ /** If this is a channel post, get its automatic forward in the discussion group */
449
+ getDiscussionMessage() {
450
+ return this.client.getDiscussionMessage({ chatId: this.chat.inputPeer, message: this.id });
451
+ }
452
+ /** Get all custom emojis contained in this message (message group), if any */
453
+ getCustomEmojis() {
454
+ return this.client.getCustomEmojisFromMessages(this.messages);
455
+ }
456
+ /** Send a text message to the same chat (and topic, if applicable) as a given message */
457
+ answerText(...params) {
458
+ return this.client.answerText(this, ...params);
459
+ }
460
+ /** Send a media to the same chat (and topic, if applicable) as a given message */
461
+ answerMedia(...params) {
462
+ return this.client.answerMedia(this, ...params);
463
+ }
464
+ /** Send a media group to the same chat (and topic, if applicable) as a given message */
465
+ answerMediaGroup(...params) {
466
+ return this.client.answerMediaGroup(this, ...params);
467
+ }
468
+ /** Send a text message in reply to this message */
469
+ replyText(...params) {
470
+ return this.client.replyText(this, ...params);
471
+ }
472
+ /** Send a media in reply to this message */
473
+ replyMedia(...params) {
474
+ return this.client.replyMedia(this, ...params);
475
+ }
476
+ /** Send a media group in reply to this message */
477
+ replyMediaGroup(...params) {
478
+ return this.client.replyMediaGroup(this, ...params);
479
+ }
480
+ /** Send a text message in reply to this message */
481
+ quoteWithText(params) {
482
+ return this.client.quoteWithText(this, params);
483
+ }
484
+ /** Send a media in reply to this message */
485
+ quoteWithMedia(params) {
486
+ return this.client.quoteWithMedia(this, params);
487
+ }
488
+ /** Send a media group in reply to this message */
489
+ quoteWithMediaGroup(params) {
490
+ return this.client.quoteWithMediaGroup(this, params);
491
+ }
492
+ /** Send a text as a comment to this message */
493
+ commentText(...params) {
494
+ return this.client.commentText(this, ...params);
495
+ }
496
+ /** Send a media as a comment to this message */
497
+ commentMedia(...params) {
498
+ return this.client.commentMedia(this, ...params);
499
+ }
500
+ /** Send a media group as a comment to this message */
501
+ commentMediaGroup(...params) {
502
+ return this.client.commentMediaGroup(this, ...params);
503
+ }
504
+ /** Delete this message (message group) */
505
+ delete(params) {
506
+ return this.client.deleteMessagesById(
507
+ this.chat.inputPeer,
508
+ this.messages.map((it) => it.id),
509
+ params
510
+ );
511
+ }
512
+ /** Pin this message */
513
+ pin(params) {
514
+ return this.client.pinMessage({
515
+ chatId: this.chat.inputPeer,
516
+ message: this.id,
517
+ ...params
518
+ });
519
+ }
520
+ /** Unpin this message */
521
+ unpin() {
522
+ return this.client.unpinMessage({
523
+ chatId: this.chat.inputPeer,
524
+ message: this.id
525
+ });
526
+ }
527
+ /** Edit this message */
528
+ edit(params) {
529
+ return this.client.editMessage({
530
+ chatId: this.chat.inputPeer,
531
+ message: this.id,
532
+ ...params
533
+ });
534
+ }
535
+ /** Forward this message (message group) */
536
+ forwardTo(params) {
537
+ return this.client.forwardMessagesById({
538
+ fromChatId: this.chat.inputPeer,
539
+ messages: this.messages.map((it) => it.id),
540
+ ...params
541
+ });
542
+ }
543
+ /** Send a copy of this message (message group) */
544
+ copy(params) {
545
+ if (this.isMessageGroup) {
546
+ return this.client.sendCopyGroup({
547
+ messages: this.messages,
548
+ ...params
549
+ });
550
+ }
551
+ return this.client.sendCopy({
552
+ message: this,
553
+ ...params
554
+ });
555
+ }
556
+ /** React to this message */
557
+ react(params) {
558
+ return this.client.sendReaction({
559
+ chatId: this.chat.inputPeer,
560
+ message: this.id,
561
+ ...params
562
+ });
563
+ }
564
+ }
565
+ class PreCheckoutQueryContext extends core.PreCheckoutQuery {
566
+ constructor(client, query) {
567
+ super(query.raw, query._peers);
568
+ this.client = client;
569
+ }
570
+ _name = "pre_checkout_query";
571
+ /** Approve the query */
572
+ approve() {
573
+ return this.client.answerPreCheckoutQuery(this.raw.queryId);
574
+ }
575
+ /** Decline the query, optionally with an error */
576
+ decline(error = "") {
577
+ return this.client.answerPreCheckoutQuery(this.raw.queryId, { error });
578
+ }
579
+ }
580
+ function _parsedUpdateToContext(client, update) {
581
+ switch (update.name) {
582
+ case "new_message":
583
+ case "edit_message":
584
+ case "message_group":
585
+ return new MessageContext(client, update.data);
586
+ case "inline_query":
587
+ return new InlineQueryContext(client, update.data);
588
+ case "chosen_inline_result":
589
+ return new ChosenInlineResultContext(client, update.data);
590
+ case "callback_query":
591
+ return new CallbackQueryContext(client, update.data);
592
+ case "inline_callback_query":
593
+ return new InlineCallbackQueryContext(client, update.data);
594
+ case "business_callback_query":
595
+ return new BusinessCallbackQueryContext(client, update.data);
596
+ case "bot_chat_join_request":
597
+ return new ChatJoinRequestUpdateContext(client, update.data);
598
+ case "pre_checkout_query":
599
+ return new PreCheckoutQueryContext(client, update.data);
600
+ case "new_business_message":
601
+ case "edit_business_message":
602
+ case "business_message_group":
603
+ return new BusinessMessageContext(client, update.data);
604
+ }
605
+ const _update = update.data;
606
+ _update.client = client;
607
+ _update._name = update.name;
608
+ return _update;
609
+ }
610
+ class SceneTransitionContext {
611
+ constructor(previousScene, update) {
612
+ this.previousScene = previousScene;
613
+ this.update = update;
614
+ }
615
+ /** Get {@link update}, asserting it is a message-related update */
616
+ get message() {
617
+ if (this.update instanceof MessageContext) {
618
+ return this.update;
619
+ }
620
+ throw new core.MtTypeAssertionError("SceneTransitionContext.message", "message", this.update._name);
621
+ }
622
+ /** Get {@link update}, asserting it is a business message-related update */
623
+ get businessMessage() {
624
+ if (this.update instanceof BusinessMessageContext) {
625
+ return this.update;
626
+ }
627
+ throw new core.MtTypeAssertionError("SceneTransitionContext.businessMessage", "business message", this.update._name);
628
+ }
629
+ /** Get {@link update}, asserting it is a callback query update */
630
+ get callbackQuery() {
631
+ if (this.update instanceof CallbackQueryContext) {
632
+ return this.update;
633
+ }
634
+ throw new core.MtTypeAssertionError("SceneTransitionContext.callbackQuery", "callback query", this.update._name);
635
+ }
636
+ /** Get {@link update}, asserting it is an inline callback query update */
637
+ get inlineCallbackQuery() {
638
+ if (this.update instanceof InlineCallbackQueryContext) {
639
+ return this.update;
640
+ }
641
+ throw new core.MtTypeAssertionError(
642
+ "SceneTransitionContext.inlineCallbackQuery",
643
+ "inline callback query",
644
+ this.update._name
645
+ );
646
+ }
647
+ }
648
+ utils_js.makeInspectable(SceneTransitionContext);
649
+ const defaultStateKeyDelegate = (upd) => {
650
+ if ("type" in upd) {
651
+ return String(upd.id);
652
+ }
653
+ if (upd._name === "new_message" || upd._name === "new_business_message") {
654
+ switch (upd.chat.chatType) {
655
+ case "private":
656
+ case "bot":
657
+ case "channel":
658
+ return String(upd.chat.id);
659
+ case "group":
660
+ case "supergroup":
661
+ case "gigagroup":
662
+ return `${upd.chat.id}_${upd.sender.id}`;
663
+ default:
664
+ core.assertNever(upd.chat.chatType);
665
+ }
666
+ }
667
+ if (upd._name === "callback_query") {
668
+ if (upd.chat.chatType === "private") return `${upd.user.id}`;
669
+ return `${upd.chat.id}_${upd.user.id}`;
670
+ }
671
+ return null;
672
+ };
673
+ class MemoryStateRepository {
674
+ constructor(_driver) {
675
+ this._driver = _driver;
676
+ this.state = this._driver.getState("dispatcher_fsm", () => /* @__PURE__ */ new Map());
677
+ this.rl = this._driver.getState("rl", () => /* @__PURE__ */ new Map());
678
+ }
679
+ state;
680
+ rl;
681
+ setState(key, state2, ttl) {
682
+ this.state.set(key, {
683
+ value: state2,
684
+ expiresAt: ttl ? Date.now() + ttl * 1e3 : void 0
685
+ });
686
+ }
687
+ getState(key, now) {
688
+ const state2 = this.state.get(key);
689
+ if (!state2) return null;
690
+ if (state2.expiresAt && state2.expiresAt < now) {
691
+ this.state.delete(key);
692
+ return null;
693
+ }
694
+ return state2.value;
695
+ }
696
+ deleteState(key) {
697
+ this.state.delete(key);
698
+ }
699
+ vacuum(now) {
700
+ for (const [key, state2] of this.state.entries()) {
701
+ if (state2.expiresAt && state2.expiresAt < now) {
702
+ this.state.delete(key);
703
+ }
704
+ }
705
+ for (const [key, state2] of this.rl.entries()) {
706
+ if (state2.reset < now) {
707
+ this.rl.delete(key);
708
+ }
709
+ }
710
+ }
711
+ getRateLimit(key, now, limit, window) {
712
+ const item = this.rl.get(key);
713
+ if (!item) {
714
+ const state2 = {
715
+ reset: now + window * 1e3,
716
+ remaining: limit
717
+ };
718
+ this.rl.set(key, state2);
719
+ return [state2.remaining, state2.reset];
720
+ }
721
+ if (item.reset < now) {
722
+ const state2 = {
723
+ reset: now + window * 1e3,
724
+ remaining: limit
725
+ };
726
+ this.rl.set(key, state2);
727
+ return [state2.remaining, state2.reset];
728
+ }
729
+ item.remaining = item.remaining > 0 ? item.remaining - 1 : 0;
730
+ return [item.remaining, item.reset];
731
+ }
732
+ resetRateLimit(key) {
733
+ this.rl.delete(key);
734
+ }
735
+ }
736
+ class MemoryStateStorage {
737
+ constructor(driver = new core.MemoryStorageDriver()) {
738
+ this.driver = driver;
739
+ this.state = new MemoryStateRepository(this.driver);
740
+ }
741
+ state;
742
+ }
743
+ class SqliteStateRepository {
744
+ constructor(_driver) {
745
+ this._driver = _driver;
746
+ _driver.registerMigration("state", 1, (db) => {
747
+ db.exec(`
748
+ create table fsm_state (
749
+ key text primary key,
750
+ value text not null,
751
+ expires_at integer
752
+ );
753
+ create table rl_state (
754
+ key text primary key,
755
+ reset integer not null,
756
+ remaining integer not null
757
+ );
758
+ `);
759
+ });
760
+ _driver.onLoad(() => {
761
+ this._setState = _driver.db.prepare(
762
+ "insert or replace into fsm_state (key, value, expires_at) values (?, ?, ?)"
763
+ );
764
+ this._getState = _driver.db.prepare("select value, expires_at from fsm_state where key = ?");
765
+ this._deleteState = _driver.db.prepare("delete from fsm_state where key = ?");
766
+ this._deleteOldState = _driver.db.prepare("delete from fsm_state where expires_at < ?");
767
+ this._setRl = _driver.db.prepare("insert or replace into rl_state (key, reset, remaining) values (?, ?, ?)");
768
+ this._getRl = _driver.db.prepare("select reset, remaining from rl_state where key = ?");
769
+ this._deleteRl = _driver.db.prepare("delete from rl_state where key = ?");
770
+ this._deleteOldRl = _driver.db.prepare("delete from rl_state where reset < ?");
771
+ });
772
+ _driver.registerLegacyMigration("state", (db) => {
773
+ db.exec("drop table state");
774
+ });
775
+ }
776
+ _setState;
777
+ setState(key, state2, ttl) {
778
+ this._setState.run(key, state2, ttl ? Date.now() + ttl * 1e3 : void 0);
779
+ }
780
+ _getState;
781
+ getState(key, now) {
782
+ const res_ = this._getState.get(key);
783
+ if (!res_) return null;
784
+ const res = res_;
785
+ if (res.expires_at && res.expires_at < now) {
786
+ this._deleteState.run(key);
787
+ return null;
788
+ }
789
+ return res.value;
790
+ }
791
+ _deleteState;
792
+ deleteState(key) {
793
+ this._deleteState.run(key);
794
+ }
795
+ _deleteOldState;
796
+ _deleteOldRl;
797
+ vacuum(now) {
798
+ this._deleteOldState.run(now);
799
+ this._deleteOldRl.run(now);
800
+ }
801
+ _setRl;
802
+ _getRl;
803
+ _deleteRl;
804
+ getRateLimit(key, now, limit, window) {
805
+ const val = this._getRl.get(key);
806
+ if (!val || val.reset < now) {
807
+ const item = {
808
+ reset: now + window * 1e3,
809
+ remaining: limit
810
+ };
811
+ this._setRl.run(key, item.reset, item.remaining);
812
+ return [item.remaining, item.reset];
813
+ }
814
+ if (val.remaining > 0) {
815
+ val.remaining -= 1;
816
+ this._setRl.run(key, val.reset, val.remaining);
817
+ }
818
+ return [val.remaining, val.reset];
819
+ }
820
+ resetRateLimit(key) {
821
+ this._deleteRl.run(key);
822
+ }
823
+ }
824
+ class SqliteStateStorage {
825
+ constructor(driver) {
826
+ this.driver = driver;
827
+ this.state = new SqliteStateRepository(driver);
828
+ }
829
+ state;
830
+ static from(provider) {
831
+ return new SqliteStateStorage(provider.driver);
832
+ }
833
+ }
834
+ class RateLimitError extends core.MtcuteError {
835
+ constructor(reset) {
836
+ super("You are being rate limited.");
837
+ this.reset = reset;
838
+ }
839
+ }
840
+ class UpdateState {
841
+ _key;
842
+ _localKey;
843
+ _storage;
844
+ _scene;
845
+ _scoped;
846
+ _cached;
847
+ _localStorage;
848
+ _localKeyBase;
849
+ constructor(storage, key, scene, scoped, customStorage, customKey) {
850
+ this._storage = storage;
851
+ this._key = key;
852
+ this._scene = scene;
853
+ this._scoped = scoped;
854
+ this._localStorage = customStorage ?? storage;
855
+ this._localKeyBase = customKey ?? key;
856
+ this._updateLocalKey();
857
+ }
858
+ /** Name of the current scene */
859
+ get scene() {
860
+ return this._scene;
861
+ }
862
+ _updateLocalKey() {
863
+ if (!this._scoped) {
864
+ this._localKey = this._localKeyBase;
865
+ } else {
866
+ this._localKey = this._scene ? `${this._scene}_${this._localKeyBase}` : this._localKeyBase;
867
+ }
868
+ }
869
+ async get(fallback, force) {
870
+ if (typeof fallback === "boolean") {
871
+ force = fallback;
872
+ fallback = void 0;
873
+ }
874
+ if (!force && this._cached !== void 0) {
875
+ if (!this._cached && fallback) {
876
+ return typeof fallback === "function" ? fallback() : fallback;
877
+ }
878
+ return this._cached;
879
+ }
880
+ let res = await this._localStorage.getState(this._localKey);
881
+ if (!res && fallback) {
882
+ res = typeof fallback === "function" ? fallback() : fallback;
883
+ }
884
+ this._cached = res;
885
+ return res;
886
+ }
887
+ /**
888
+ * Set new state to the storage
889
+ *
890
+ * @param state New state
891
+ * @param ttl TTL for the new state (in seconds)
892
+ */
893
+ async set(state2, ttl) {
894
+ this._cached = state2;
895
+ await this._localStorage.setState(this._localKey, state2, ttl);
896
+ }
897
+ /**
898
+ * Merge the given object to the current state.
899
+ *
900
+ * > **Note**: If the storage currently has no state,
901
+ * > then `fallback` must be provided.
902
+ *
903
+ * Basically a shorthand to calling `.get()`,
904
+ * modifying and then calling `.set()`
905
+ *
906
+ * @param state State to be merged
907
+ * @param fallback Default state
908
+ * @param ttl TTL for the new state (in seconds)
909
+ * @param forceLoad Whether to force load the old state from storage
910
+ */
911
+ async merge(state2, params = {}) {
912
+ const { fallback, ttl, forceLoad } = params;
913
+ const old = await this.get(forceLoad);
914
+ if (!old) {
915
+ if (!fallback) {
916
+ throw new core.MtArgumentError("Cannot use merge on empty state without fallback.");
917
+ }
918
+ const fallback_ = typeof fallback === "function" ? fallback() : fallback;
919
+ await this.set({ ...fallback_, ...state2 }, ttl);
920
+ } else {
921
+ await this.set({ ...old, ...state2 }, ttl);
922
+ }
923
+ return this._cached;
924
+ }
925
+ /**
926
+ * Delete the state from the storage
927
+ */
928
+ async delete() {
929
+ this._cached = null;
930
+ await this._localStorage.deleteState(this._localKey);
931
+ }
932
+ /**
933
+ * Enter some scene
934
+ */
935
+ async enter(scene, params) {
936
+ const { with: with_, ttl, reset = true } = params ?? {};
937
+ if (reset && this._scoped) await this.delete();
938
+ if (!scene["_scene"]) {
939
+ throw new core.MtArgumentError("Cannot enter a non-scene Dispatcher");
940
+ }
941
+ if (!scene["_parent"]) {
942
+ throw new core.MtArgumentError("This scene has not been registered");
943
+ }
944
+ this._scene = scene["_scene"];
945
+ this._scoped = scene["_sceneScoped"];
946
+ this._updateLocalKey();
947
+ await this._storage.setCurrentScene(this._key, this._scene, ttl);
948
+ if (with_) {
949
+ if (scene["_customStateKeyDelegate"]) {
950
+ throw new core.MtArgumentError("Cannot use `with` parameter when the scene uses a custom state key delegate");
951
+ }
952
+ await scene.getState(this._key).set(with_, ttl);
953
+ }
954
+ }
955
+ /**
956
+ * Exit from current scene to the root
957
+ *
958
+ * @param reset
959
+ * Whether to reset scene state (only applicable in case this is a scoped scene)
960
+ */
961
+ async exit(reset = true) {
962
+ if (reset && this._scoped) await this.delete();
963
+ this._scene = null;
964
+ this._updateLocalKey();
965
+ await this._storage.deleteCurrentScene(this._key);
966
+ }
967
+ /**
968
+ * Rate limit some handler.
969
+ *
970
+ * When the rate limit exceeds, {@link RateLimitError} is thrown.
971
+ *
972
+ * This is a simple rate-limiting solution that uses
973
+ * the same key as the state. If you need something more
974
+ * sophisticated and/or customizable, you'll have to implement
975
+ * your own rate-limiter.
976
+ *
977
+ * > **Note**: `key` is used to prefix the local key
978
+ * > derived using the given key delegate.
979
+ *
980
+ * @param key Key of the rate limit
981
+ * @param limit Maximum number of requests in `window`
982
+ * @param window Window size in seconds
983
+ * @returns Tuple containing the number of remaining and
984
+ * unix time in ms when the user can try again
985
+ */
986
+ async rateLimit(key, limit, window) {
987
+ const [remaining, reset] = await this._localStorage.getRateLimit(`${key}:${this._localKey}`, limit, window);
988
+ if (!remaining) {
989
+ throw new RateLimitError(reset);
990
+ }
991
+ return [remaining - 1, reset];
992
+ }
993
+ /**
994
+ * Throttle some handler.
995
+ *
996
+ * When the rate limit exceeds, this function waits for it to reset.
997
+ *
998
+ * This is a simple wrapper over {@link rateLimit}, and follows the same logic.
999
+ *
1000
+ * > **Note**: `key` is used to prefix the local key
1001
+ * > derived using the given key delegate.
1002
+ *
1003
+ * @param key Key of the rate limit
1004
+ * @param limit Maximum number of requests in `window`
1005
+ * @param window Window size in seconds
1006
+ * @returns Tuple containing the number of remaining and
1007
+ * unix time in ms when the user can try again
1008
+ */
1009
+ async throttle(key, limit, window) {
1010
+ try {
1011
+ return await this.rateLimit(key, limit, window);
1012
+ } catch (e) {
1013
+ if (e instanceof RateLimitError) {
1014
+ await utils_js.sleep(e.reset - Date.now());
1015
+ return this.throttle(key, limit, window);
1016
+ }
1017
+ throw e;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Reset the rate limit
1022
+ *
1023
+ * @param key Key of the rate limit
1024
+ */
1025
+ async resetRateLimit(key) {
1026
+ await this._localStorage.resetRateLimit(`${key}:${this._localKey}`);
1027
+ }
1028
+ }
1029
+ const makeCurrentSceneKey = (key) => `$current_scene_${key}`;
1030
+ class StateService {
1031
+ constructor(provider) {
1032
+ this.provider = provider;
1033
+ }
1034
+ _cache = new utils_js.LruMap(100);
1035
+ _vacuumTimer;
1036
+ _loaded = false;
1037
+ _load = utils_js.asyncResettable(async () => {
1038
+ await this.provider.driver.load?.();
1039
+ this._loaded = true;
1040
+ });
1041
+ async load() {
1042
+ await this._load.run();
1043
+ this._vacuumTimer = utils_js.timers.setInterval(() => {
1044
+ Promise.resolve(this.provider.state.vacuum(Date.now())).catch(() => {
1045
+ });
1046
+ }, 3e5);
1047
+ }
1048
+ async destroy() {
1049
+ await this.provider.driver.save?.();
1050
+ await this.provider.driver.destroy?.();
1051
+ utils_js.timers.clearInterval(this._vacuumTimer);
1052
+ this._loaded = false;
1053
+ }
1054
+ async getState(key) {
1055
+ if (!this._loaded) await this.load();
1056
+ const cached = this._cache.get(key);
1057
+ if (cached) return cached;
1058
+ const state2 = await this.provider.state.getState(key, Date.now());
1059
+ if (!state2) return null;
1060
+ return JSON.parse(state2);
1061
+ }
1062
+ async setState(key, state2, ttl) {
1063
+ if (!this._loaded) await this.load();
1064
+ this._cache.set(key, state2);
1065
+ await this.provider.state.setState(key, JSON.stringify(state2), ttl);
1066
+ }
1067
+ async deleteState(key) {
1068
+ if (!this._loaded) await this.load();
1069
+ this._cache.delete(key);
1070
+ await this.provider.state.deleteState(key);
1071
+ }
1072
+ getCurrentScene(key) {
1073
+ return this.getState(makeCurrentSceneKey(key));
1074
+ }
1075
+ setCurrentScene(key, scene, ttl) {
1076
+ return this.setState(makeCurrentSceneKey(key), scene, ttl);
1077
+ }
1078
+ deleteCurrentScene(key) {
1079
+ return this.deleteState(makeCurrentSceneKey(key));
1080
+ }
1081
+ getRateLimit(key, limit, window) {
1082
+ return this.provider.state.getRateLimit(key, Date.now(), limit, window);
1083
+ }
1084
+ resetRateLimit(key) {
1085
+ return this.provider.state.resetRateLimit(key);
1086
+ }
1087
+ }
1088
+ class Dispatcher {
1089
+ _groups = /* @__PURE__ */ new Map();
1090
+ _groupsOrder = [];
1091
+ _client;
1092
+ _parent;
1093
+ _children = [];
1094
+ _scenes;
1095
+ _scene;
1096
+ _sceneScoped;
1097
+ _storage;
1098
+ _stateKeyDelegate;
1099
+ _customStateKeyDelegate;
1100
+ _customStorage;
1101
+ _deps = {};
1102
+ _errorHandler;
1103
+ _preUpdateHandler;
1104
+ _postUpdateHandler;
1105
+ _sceneTransitionHandler;
1106
+ constructor(client, params) {
1107
+ this.dispatchRawUpdate = this.dispatchRawUpdate.bind(this);
1108
+ this.dispatchUpdate = this.dispatchUpdate.bind(this);
1109
+ let { storage, key, sceneName } = params ?? {};
1110
+ if (client) {
1111
+ this.bindToClient(client);
1112
+ if (storage) {
1113
+ this._storage = new StateService(storage);
1114
+ this._stateKeyDelegate = key ?? defaultStateKeyDelegate;
1115
+ }
1116
+ } else {
1117
+ if (storage) {
1118
+ this._customStorage = new StateService(storage);
1119
+ }
1120
+ if (key) {
1121
+ this._customStateKeyDelegate = key;
1122
+ }
1123
+ if (sceneName) {
1124
+ if (sceneName[0] === "$") {
1125
+ throw new core.MtArgumentError("Scene name cannot start with $");
1126
+ }
1127
+ this._scene = sceneName;
1128
+ }
1129
+ }
1130
+ }
1131
+ static for(client, params) {
1132
+ return new Dispatcher(client, params);
1133
+ }
1134
+ /**
1135
+ * Create a new child dispatcher.
1136
+ */
1137
+ static child(params) {
1138
+ return new Dispatcher(void 0, params);
1139
+ }
1140
+ /**
1141
+ * Create a new scene dispatcher
1142
+ */
1143
+ static scene(name, params) {
1144
+ return new Dispatcher(void 0, { sceneName: name, ...params });
1145
+ }
1146
+ /** For scene dispatchers, name of the scene */
1147
+ get sceneName() {
1148
+ return this._scene;
1149
+ }
1150
+ inject(name, value) {
1151
+ if (this._parent) {
1152
+ throw new core.MtArgumentError("Cannot inject dependencies to child dispatchers");
1153
+ }
1154
+ if (typeof name === "object") {
1155
+ for (const [k, v] of Object.entries(name)) {
1156
+ this._deps[k] = v;
1157
+ }
1158
+ } else {
1159
+ this._deps[name] = value;
1160
+ }
1161
+ }
1162
+ /**
1163
+ * Get the dependencies injected into this dispatcher.
1164
+ */
1165
+ get deps() {
1166
+ return this._deps;
1167
+ }
1168
+ /**
1169
+ * Bind the dispatcher to the client.
1170
+ * Called by the constructor automatically if
1171
+ * `client` was passed.
1172
+ *
1173
+ * Dispatcher also uses bound client to throw errors
1174
+ */
1175
+ bindToClient(client) {
1176
+ client.on("update", this.dispatchUpdate);
1177
+ client.on("raw_update", this.dispatchRawUpdate);
1178
+ this._client = client;
1179
+ }
1180
+ /**
1181
+ * Unbind a dispatcher from the client.
1182
+ */
1183
+ unbind() {
1184
+ if (this._client) {
1185
+ this._client.off("update", this.dispatchUpdate);
1186
+ this._client.off("raw_update", this.dispatchRawUpdate);
1187
+ this._client = void 0;
1188
+ }
1189
+ }
1190
+ /**
1191
+ * Destroy the dispatcher and all its children.
1192
+ *
1193
+ * When destroying, all the registered handlers are removed,
1194
+ * and the underlying storage is freed.
1195
+ */
1196
+ async destroy() {
1197
+ if (this._parent && this._customStorage) {
1198
+ await this._customStorage.destroy();
1199
+ } else if (!this._parent && this._storage) {
1200
+ await this._storage.destroy();
1201
+ }
1202
+ this.removeUpdateHandler("all");
1203
+ for (const child of this._children) {
1204
+ await child.destroy();
1205
+ }
1206
+ for (const scene of this._scenes?.values() ?? []) {
1207
+ await scene.destroy();
1208
+ }
1209
+ }
1210
+ /**
1211
+ * Process a raw update with this dispatcher.
1212
+ * Calling this method without bound client will not work.
1213
+ *
1214
+ * Under the hood asynchronously calls {@link dispatchRawUpdateNow}
1215
+ * with error handler set to client's one.
1216
+ *
1217
+ * @param update Update to process
1218
+ * @param peers Peers index
1219
+ */
1220
+ dispatchRawUpdate(update, peers) {
1221
+ if (!this._client) return;
1222
+ this.dispatchRawUpdateNow(update, peers).catch((err) => this._client.emitError(err));
1223
+ }
1224
+ /**
1225
+ * Process a raw update right now in the current stack.
1226
+ *
1227
+ * Unlike {@link dispatchRawUpdate}, this does not schedule
1228
+ * the update to be dispatched, but dispatches it immediately,
1229
+ * and after `await`ing this method you can be certain that the update
1230
+ * was fully processed by all the registered handlers, including children.
1231
+ *
1232
+ * @param update Update to process
1233
+ * @param peers Peers map
1234
+ * @returns Whether the update was handled
1235
+ */
1236
+ async dispatchRawUpdateNow(update, peers) {
1237
+ if (!this._client) return false;
1238
+ let handled = false;
1239
+ outer: for (const grp of this._groupsOrder) {
1240
+ const group = this._groups.get(grp);
1241
+ if (group.has("raw")) {
1242
+ const handlers = group.get("raw");
1243
+ for (const h of handlers) {
1244
+ let result;
1245
+ if (!h.check || await h.check(this._client, update, peers)) {
1246
+ result = await h.callback(this._client, update, peers);
1247
+ handled = true;
1248
+ } else {
1249
+ continue;
1250
+ }
1251
+ switch (result) {
1252
+ case "continue":
1253
+ continue;
1254
+ case "stop":
1255
+ break outer;
1256
+ case "stop-children":
1257
+ return handled;
1258
+ }
1259
+ break;
1260
+ }
1261
+ }
1262
+ }
1263
+ for (const child of this._children) {
1264
+ const childHandled = await child.dispatchRawUpdateNow(update, peers);
1265
+ handled ||= childHandled;
1266
+ }
1267
+ return handled;
1268
+ }
1269
+ /**
1270
+ * Process an update with this dispatcher.
1271
+ * Calling this method without bound client will not work.
1272
+ *
1273
+ * Under the hood asynchronously calls {@link dispatchUpdateNow}
1274
+ * with error handler set to client's one.
1275
+ *
1276
+ * @param update Update to process
1277
+ */
1278
+ dispatchUpdate(update) {
1279
+ if (!this._client) return;
1280
+ this.dispatchUpdateNow(update).catch((err) => this._client.emitError(err));
1281
+ }
1282
+ /**
1283
+ * Process an update right now in the current stack.
1284
+ *
1285
+ * Unlike {@link dispatchUpdate}, this does not schedule
1286
+ * the update to be dispatched, but dispatches it immediately,
1287
+ * and after `await`ing this method you can be certain that the update
1288
+ * was fully processed by all the registered handlers, including children.
1289
+ *
1290
+ * @param update Update to process
1291
+ * @returns Whether the update was handled
1292
+ */
1293
+ async dispatchUpdateNow(update) {
1294
+ return this._dispatchUpdateNowImpl(update);
1295
+ }
1296
+ async _dispatchUpdateNowImpl(update, parsedState, parsedScene, forceScene, parsedContext) {
1297
+ if (!this._client) return false;
1298
+ if (parsedScene === void 0) {
1299
+ if (this._storage && this._scenes && (update.name === "new_message" || update.name === "edit_message" || update.name === "callback_query" || update.name === "message_group" || update.name === "new_business_message" || update.name === "edit_business_message" || update.name === "business_message_group")) {
1300
+ if (!parsedContext) parsedContext = _parsedUpdateToContext(this._client, update);
1301
+ const key = await this._stateKeyDelegate(parsedContext);
1302
+ if (key) {
1303
+ parsedScene = await this._storage.getCurrentScene(key);
1304
+ } else {
1305
+ parsedScene = null;
1306
+ }
1307
+ } else {
1308
+ parsedScene = null;
1309
+ }
1310
+ }
1311
+ if (!forceScene && parsedScene !== null) {
1312
+ if (this._scene) {
1313
+ if (this._scene !== parsedScene) {
1314
+ return false;
1315
+ }
1316
+ } else {
1317
+ if (!this._scenes || !this._scenes.has(parsedScene)) {
1318
+ return false;
1319
+ }
1320
+ return this._scenes.get(parsedScene)._dispatchUpdateNowImpl(update, parsedState, parsedScene, true);
1321
+ }
1322
+ }
1323
+ if (parsedState === void 0) {
1324
+ if (this._storage && (update.name === "new_message" || update.name === "edit_message" || update.name === "callback_query" || update.name === "message_group" || update.name === "new_business_message" || update.name === "edit_business_message" || update.name === "business_message_group")) {
1325
+ if (!parsedContext) parsedContext = _parsedUpdateToContext(this._client, update);
1326
+ const key = await this._stateKeyDelegate(parsedContext);
1327
+ if (key) {
1328
+ let customKey;
1329
+ if (!this._customStateKeyDelegate || (customKey = await this._customStateKeyDelegate(parsedContext))) {
1330
+ parsedState = new UpdateState(
1331
+ this._storage,
1332
+ key,
1333
+ this._scene ?? null,
1334
+ this._sceneScoped,
1335
+ this._customStorage,
1336
+ customKey
1337
+ );
1338
+ }
1339
+ } else {
1340
+ parsedState = null;
1341
+ }
1342
+ } else {
1343
+ parsedState = null;
1344
+ }
1345
+ }
1346
+ let shouldDispatch = true;
1347
+ let shouldDispatchChildren = true;
1348
+ let handled = false;
1349
+ switch (await this._preUpdateHandler?.(update, parsedState)) {
1350
+ case "stop":
1351
+ shouldDispatch = false;
1352
+ break;
1353
+ case "stop-children":
1354
+ return false;
1355
+ }
1356
+ if (shouldDispatch) {
1357
+ outer: for (const grp of this._groupsOrder) {
1358
+ const group = this._groups.get(grp);
1359
+ if (group.has(update.name)) {
1360
+ const handlers = group.get(update.name);
1361
+ try {
1362
+ for (const h of handlers) {
1363
+ let result;
1364
+ if (!parsedContext) parsedContext = _parsedUpdateToContext(this._client, update);
1365
+ if (!h.check || await h.check(parsedContext, parsedState)) {
1366
+ result = await h.callback(parsedContext, parsedState);
1367
+ handled = true;
1368
+ } else {
1369
+ continue;
1370
+ }
1371
+ if (parsedState && this._scenes) {
1372
+ const newScene = parsedState.scene;
1373
+ if (parsedScene !== newScene) {
1374
+ const nextDp = newScene ? this._scenes.get(newScene) : this._parent;
1375
+ if (!nextDp) {
1376
+ throw new core.MtArgumentError(`Scene ${newScene} not found`);
1377
+ }
1378
+ if (nextDp._sceneTransitionHandler) {
1379
+ const transition = new SceneTransitionContext(parsedScene, parsedContext);
1380
+ const transitionResult = await nextDp._sceneTransitionHandler?.(
1381
+ transition,
1382
+ parsedState
1383
+ );
1384
+ switch (transitionResult) {
1385
+ case "stop":
1386
+ return true;
1387
+ case "continue":
1388
+ continue;
1389
+ case "scene": {
1390
+ const scene = parsedState.scene;
1391
+ const dp = scene ? nextDp._scenes.get(scene) : nextDp._parent;
1392
+ return dp._dispatchUpdateNowImpl(update, void 0, scene, true);
1393
+ }
1394
+ }
1395
+ }
1396
+ }
1397
+ }
1398
+ switch (result) {
1399
+ case "continue":
1400
+ continue;
1401
+ case "stop":
1402
+ break outer;
1403
+ case "stop-children":
1404
+ shouldDispatchChildren = false;
1405
+ break outer;
1406
+ case "scene": {
1407
+ if (!parsedState) {
1408
+ throw new core.MtArgumentError("Cannot use ToScene without state");
1409
+ }
1410
+ const scene = parsedState.scene;
1411
+ const dp = scene ? this._scenes.get(scene) : this._parent;
1412
+ return dp._dispatchUpdateNowImpl(update, void 0, scene, true);
1413
+ }
1414
+ }
1415
+ break;
1416
+ }
1417
+ } catch (e) {
1418
+ if (this._errorHandler) {
1419
+ const handled2 = await this._errorHandler(e, update, parsedState);
1420
+ if (!handled2) throw e;
1421
+ } else {
1422
+ throw e;
1423
+ }
1424
+ }
1425
+ }
1426
+ }
1427
+ }
1428
+ if (shouldDispatchChildren) {
1429
+ for (const child of this._children) {
1430
+ const childHandled = await child._dispatchUpdateNowImpl(update);
1431
+ handled ||= childHandled;
1432
+ }
1433
+ }
1434
+ await this._postUpdateHandler?.(handled, update, parsedState);
1435
+ return handled;
1436
+ }
1437
+ /**
1438
+ * Add an update handler to a given handlers group
1439
+ *
1440
+ * @param handler Update handler
1441
+ * @param group Handler group index
1442
+ */
1443
+ addUpdateHandler(handler, group = 0) {
1444
+ if (!this._groups.has(group)) {
1445
+ this._groups.set(group, /* @__PURE__ */ new Map());
1446
+ this._groupsOrder.push(group);
1447
+ this._groupsOrder.sort((a, b) => a - b);
1448
+ }
1449
+ if (!this._groups.get(group).has(handler.name)) {
1450
+ this._groups.get(group).set(handler.name, []);
1451
+ }
1452
+ this._groups.get(group).get(handler.name).push(handler);
1453
+ }
1454
+ /**
1455
+ * Remove an update handler (or handlers) from a given
1456
+ * handler group.
1457
+ *
1458
+ * @param handler Update handler to remove, its name or `'all'` to remove all
1459
+ * @param group Handler group index (null to affect all groups)
1460
+ */
1461
+ removeUpdateHandler(handler, group = 0) {
1462
+ if (group !== null && !this._groups.has(group)) {
1463
+ return;
1464
+ }
1465
+ if (typeof handler === "string") {
1466
+ if (handler === "all") {
1467
+ if (group === null) {
1468
+ this._groups = /* @__PURE__ */ new Map();
1469
+ } else {
1470
+ this._groups.delete(group);
1471
+ }
1472
+ } else if (group !== null) {
1473
+ this._groups.get(group).delete(handler);
1474
+ }
1475
+ return;
1476
+ }
1477
+ if (group === null) return;
1478
+ if (!this._groups.get(group).has(handler.name)) {
1479
+ return;
1480
+ }
1481
+ const idx = this._groups.get(group).get(handler.name).indexOf(handler);
1482
+ if (idx > -1) {
1483
+ this._groups.get(group).get(handler.name).splice(idx, 1);
1484
+ }
1485
+ }
1486
+ /**
1487
+ * Register an error handler.
1488
+ *
1489
+ * This is used locally within this dispatcher
1490
+ * (does not affect children/parent) whenever
1491
+ * an error is thrown inside an update handler.
1492
+ * Not used for raw update handlers
1493
+ *
1494
+ * When an error is thrown, but there is no error
1495
+ * handler, it is propagated to `TelegramClient`.
1496
+ *
1497
+ * There can be at most one error handler.
1498
+ * Pass `null` to remove it.
1499
+ *
1500
+ * @param handler Error handler
1501
+ */
1502
+ onError(handler) {
1503
+ if (handler) this._errorHandler = handler;
1504
+ else this._errorHandler = void 0;
1505
+ }
1506
+ /**
1507
+ * Register pre-update middleware.
1508
+ *
1509
+ * This is used locally within this dispatcher
1510
+ * (does not affect children/parent) before processing
1511
+ * an update, and can be used to skip this update.
1512
+ *
1513
+ * There can be at most one pre-update middleware.
1514
+ * Pass `null` to remove it.
1515
+ *
1516
+ * @param handler Pre-update middleware
1517
+ */
1518
+ onPreUpdate(handler) {
1519
+ if (handler) this._preUpdateHandler = handler;
1520
+ else this._preUpdateHandler = void 0;
1521
+ }
1522
+ /**
1523
+ * Register post-update middleware.
1524
+ *
1525
+ * This is used locally within this dispatcher
1526
+ * (does not affect children/parent) after successfully
1527
+ * processing an update, and can be used for stats.
1528
+ *
1529
+ * There can be at most one post-update middleware.
1530
+ * Pass `null` to remove it.
1531
+ *
1532
+ * @param handler Pre-update middleware
1533
+ */
1534
+ onPostUpdate(handler) {
1535
+ if (handler) this._postUpdateHandler = handler;
1536
+ else this._postUpdateHandler = void 0;
1537
+ }
1538
+ /**
1539
+ * Set error handler that will propagate
1540
+ * the error to the parent dispatcher
1541
+ */
1542
+ propagateErrorToParent(err, update, state2) {
1543
+ if (!this.parent) {
1544
+ throw new core.MtArgumentError("This dispatcher is not a child");
1545
+ }
1546
+ if (this.parent._errorHandler) {
1547
+ return this.parent._errorHandler(err, update, state2);
1548
+ }
1549
+ throw err;
1550
+ }
1551
+ // children //
1552
+ /**
1553
+ * Get parent dispatcher if current dispatcher is a child.
1554
+ * Otherwise, return `null`
1555
+ */
1556
+ get parent() {
1557
+ return this._parent ?? null;
1558
+ }
1559
+ _prepareChild(child) {
1560
+ if (child._client) {
1561
+ throw new core.MtArgumentError(
1562
+ `Provided dispatcher is ${child._parent ? "already a child. Use parent.removeChild() before calling addChild()" : "already bound to a client. Use unbind() before calling addChild()"}`
1563
+ );
1564
+ }
1565
+ child._parent = this;
1566
+ child._client = this._client;
1567
+ child._storage = this._storage;
1568
+ child._deps = this._deps;
1569
+ child._scenes = this._scenes;
1570
+ child._stateKeyDelegate = this._stateKeyDelegate;
1571
+ child._customStorage ??= this._customStorage;
1572
+ child._customStateKeyDelegate ??= this._customStateKeyDelegate;
1573
+ }
1574
+ /**
1575
+ * Add a child dispatcher.
1576
+ *
1577
+ * Child dispatchers are called when dispatching updates
1578
+ * just like normal, except they can be controlled
1579
+ * externally. Additionally, child dispatcher have their own
1580
+ * independent handler grouping that does not interfere with parent's,
1581
+ * including `StopPropagation` (i.e. returning `StopPropagation` will
1582
+ * still call children. To entirely stop, use `StopChildrenPropagation`)
1583
+ *
1584
+ * Note that child dispatchers share the same TelegramClient and
1585
+ * storage binding as the parent, don't bind them manually.
1586
+ *
1587
+ * @param child Other dispatcher
1588
+ */
1589
+ addChild(child) {
1590
+ if (this._children.includes(child)) return;
1591
+ this._prepareChild(child);
1592
+ this._children.push(child);
1593
+ }
1594
+ addScene(scene, scoped = true) {
1595
+ if (!this._scenes) this._scenes = /* @__PURE__ */ new Map();
1596
+ if (!scene._scene) {
1597
+ throw new core.MtArgumentError(
1598
+ "Non-scene dispatcher passed to addScene. Use `Dispatcher.scene()` to create one."
1599
+ );
1600
+ }
1601
+ if (this._scenes.has(scene._scene)) {
1602
+ throw new core.MtArgumentError(`Scene with name ${scene._scene} is already registered!`);
1603
+ }
1604
+ this._prepareChild(scene);
1605
+ scene._sceneScoped = scoped;
1606
+ this._scenes.set(scene._scene, scene);
1607
+ }
1608
+ /**
1609
+ * Remove a child dispatcher.
1610
+ *
1611
+ * Removing child dispatcher will also remove
1612
+ * child dispatcher's client binding.
1613
+ *
1614
+ * If the provided dispatcher is not a child of current,
1615
+ * this function will silently fail.
1616
+ *
1617
+ * @param child Other dispatcher
1618
+ */
1619
+ removeChild(child) {
1620
+ const idx = this._children.indexOf(child);
1621
+ if (idx > -1) {
1622
+ child._unparent();
1623
+ this._children.splice(idx, 1);
1624
+ }
1625
+ }
1626
+ _unparent() {
1627
+ this._parent = this._client = void 0;
1628
+ this._deps = {};
1629
+ this._stateKeyDelegate = void 0;
1630
+ this._storage = void 0;
1631
+ }
1632
+ /**
1633
+ * Extend current dispatcher by copying other dispatcher's
1634
+ * handlers and children to the current.
1635
+ *
1636
+ * This might be more efficient for simple cases, but do note that the handler
1637
+ * groups, children and scenes will get merged (unlike {@link addChild},
1638
+ * where they are independent). Also note that unlike with children,
1639
+ * when adding handlers to `other` *after* you extended
1640
+ * the current dispatcher, changes will not be applied.
1641
+ *
1642
+ * @param other Other dispatcher
1643
+ */
1644
+ extend(other) {
1645
+ if (other._customStorage || other._customStateKeyDelegate) {
1646
+ throw new core.MtArgumentError("Provided dispatcher has custom storage and cannot be extended from.");
1647
+ }
1648
+ other._groupsOrder.forEach((group) => {
1649
+ if (!this._groups.has(group)) {
1650
+ this._groups.set(group, other._groups.get(group));
1651
+ this._groupsOrder.push(group);
1652
+ } else {
1653
+ const otherGrp = other._groups.get(group);
1654
+ const selfGrp = this._groups.get(group);
1655
+ for (const typ of otherGrp.keys()) {
1656
+ if (!selfGrp.has(typ)) {
1657
+ selfGrp.set(typ, otherGrp.get(typ));
1658
+ } else {
1659
+ selfGrp.get(typ).push(...otherGrp.get(typ));
1660
+ }
1661
+ }
1662
+ }
1663
+ });
1664
+ other._children.forEach((it) => {
1665
+ it._unparent();
1666
+ this.addChild(it);
1667
+ });
1668
+ if (other._scenes) {
1669
+ const otherScenes = other._scenes;
1670
+ if (!this._scenes) this._scenes = /* @__PURE__ */ new Map();
1671
+ const myScenes = this._scenes;
1672
+ for (const key of otherScenes.keys()) {
1673
+ otherScenes.get(key)._unparent();
1674
+ if (myScenes.has(key)) {
1675
+ myScenes.delete(key);
1676
+ }
1677
+ this.addScene(otherScenes.get(key), otherScenes.get(key)._sceneScoped);
1678
+ }
1679
+ }
1680
+ this._groupsOrder.sort((a, b) => a - b);
1681
+ }
1682
+ /**
1683
+ * Create a clone of this dispatcher, that has the same handlers,
1684
+ * but is not bound to a client or to a parent dispatcher.
1685
+ *
1686
+ * Custom Storage and key delegate are copied too.
1687
+ *
1688
+ * By default, child dispatchers (and scenes) are ignored, since
1689
+ * that requires cloning every single one of them recursively
1690
+ * and then binding them back.
1691
+ *
1692
+ * @param children Whether to also clone children and scenes
1693
+ */
1694
+ clone(children = false) {
1695
+ const dp = new Dispatcher();
1696
+ for (const key of this._groups.keys()) {
1697
+ const idx = key;
1698
+ dp._groups.set(idx, /* @__PURE__ */ new Map());
1699
+ for (const type of this._groups.get(idx).keys()) {
1700
+ dp._groups.get(idx).set(type, [...this._groups.get(idx).get(type)]);
1701
+ }
1702
+ }
1703
+ dp._groupsOrder = [...this._groupsOrder];
1704
+ dp._errorHandler = this._errorHandler;
1705
+ dp._customStateKeyDelegate = this._customStateKeyDelegate;
1706
+ dp._customStorage = this._customStorage;
1707
+ if (children) {
1708
+ this._children.forEach((it) => {
1709
+ const child = it.clone(true);
1710
+ dp.addChild(child);
1711
+ });
1712
+ if (this._scenes) {
1713
+ for (const key of this._scenes.keys()) {
1714
+ const scene = this._scenes.get(key).clone(true);
1715
+ dp.addScene(scene, this._scenes.get(key)._sceneScoped);
1716
+ }
1717
+ }
1718
+ }
1719
+ return dp;
1720
+ }
1721
+ getState(object) {
1722
+ if (!this._storage) {
1723
+ throw new core.MtArgumentError("Cannot use getUpdateState() filter without state storage");
1724
+ }
1725
+ if (typeof object === "string") {
1726
+ return new UpdateState(this._storage, object, this._scene ?? null, this._sceneScoped, this._customStorage);
1727
+ }
1728
+ return Promise.resolve(this._stateKeyDelegate(object)).then((key) => {
1729
+ if (!key) {
1730
+ throw new core.MtArgumentError("Cannot derive key from given object");
1731
+ }
1732
+ if (!this._customStateKeyDelegate) {
1733
+ return new UpdateState(this._storage, key, this._scene ?? null, this._sceneScoped, this._customStorage);
1734
+ }
1735
+ return Promise.resolve(this._customStateKeyDelegate(object)).then((customKey) => {
1736
+ if (!customKey) {
1737
+ throw new core.MtArgumentError("Cannot derive custom key from given object");
1738
+ }
1739
+ return new UpdateState(
1740
+ this._storage,
1741
+ key,
1742
+ this._scene ?? null,
1743
+ this._sceneScoped,
1744
+ this._customStorage,
1745
+ customKey
1746
+ );
1747
+ });
1748
+ });
1749
+ }
1750
+ /**
1751
+ * Get global state.
1752
+ *
1753
+ * This will load the state for the given object
1754
+ * ignoring local custom storage, key delegate and scene scope.
1755
+ */
1756
+ getGlobalState(object) {
1757
+ if (!this._parent) {
1758
+ throw new core.MtArgumentError("This dispatcher does not have a parent");
1759
+ }
1760
+ return Promise.resolve(this._stateKeyDelegate(object)).then((key) => {
1761
+ if (!key) {
1762
+ throw new core.MtArgumentError("Cannot derive key from given object");
1763
+ }
1764
+ return new UpdateState(this._storage, key, this._scene ?? null, false);
1765
+ });
1766
+ }
1767
+ // addUpdateHandler convenience wrappers //
1768
+ _addKnownHandler(name, filter, handler, group) {
1769
+ if (typeof handler === "number" || typeof handler === "undefined") {
1770
+ this.addUpdateHandler(
1771
+ {
1772
+ name,
1773
+ callback: filter
1774
+ },
1775
+ handler
1776
+ );
1777
+ } else {
1778
+ this.addUpdateHandler(
1779
+ {
1780
+ name,
1781
+ callback: handler,
1782
+ check: filter
1783
+ },
1784
+ group
1785
+ );
1786
+ }
1787
+ }
1788
+ /** @internal */
1789
+ onRawUpdate(filter, handler, group) {
1790
+ this._addKnownHandler("raw", filter, handler, group);
1791
+ }
1792
+ /**
1793
+ * Register a scene transition handler
1794
+ *
1795
+ * This handler is called whenever a scene transition occurs
1796
+ * in the context of the scene that is being entered,
1797
+ * and before any of the its own handlers are called,
1798
+ * and can be used to customize the transition behavior:
1799
+ * - `Stop` to prevent dispatching the update any further **even if ToScene/ToRoot was used**
1800
+ * - `Continue` same as Stop, but still dispatch the update to children
1801
+ * - `ToScene` to prevent the transition and dispatch the update to the scene entered in the transition handler
1802
+ *
1803
+ * > **Note**: if multiple `state.enter()` calls were made within the same update,
1804
+ * > this handler will only be called for the last one.
1805
+ *
1806
+ * @param handler Raw update handler
1807
+ * @param group Handler group index
1808
+ */
1809
+ onSceneTransition(handler) {
1810
+ if (handler) this._sceneTransitionHandler = handler;
1811
+ else this._sceneTransitionHandler = void 0;
1812
+ }
1813
+ /** @internal */
1814
+ onAnyCallbackQuery(filter, handler, group) {
1815
+ this._addKnownHandler("callback_query", filter, handler, group);
1816
+ this._addKnownHandler("inline_callback_query", filter, handler, group);
1817
+ this._addKnownHandler("business_callback_query", filter, handler, group);
1818
+ }
1819
+ /** @internal */
1820
+ onNewMessage(filter, handler, group) {
1821
+ this._addKnownHandler("new_message", filter, handler, group);
1822
+ }
1823
+ /** @internal */
1824
+ onEditMessage(filter, handler, group) {
1825
+ this._addKnownHandler("edit_message", filter, handler, group);
1826
+ }
1827
+ /** @internal */
1828
+ onMessageGroup(filter, handler, group) {
1829
+ this._addKnownHandler("message_group", filter, handler, group);
1830
+ }
1831
+ /** @internal */
1832
+ onDeleteMessage(filter, handler, group) {
1833
+ this._addKnownHandler("delete_message", filter, handler, group);
1834
+ }
1835
+ /** @internal */
1836
+ onChatMemberUpdate(filter, handler, group) {
1837
+ this._addKnownHandler("chat_member", filter, handler, group);
1838
+ }
1839
+ /** @internal */
1840
+ onInlineQuery(filter, handler, group) {
1841
+ this._addKnownHandler("inline_query", filter, handler, group);
1842
+ }
1843
+ /** @internal */
1844
+ onChosenInlineResult(filter, handler, group) {
1845
+ this._addKnownHandler("chosen_inline_result", filter, handler, group);
1846
+ }
1847
+ /** @internal */
1848
+ onCallbackQuery(filter, handler, group) {
1849
+ this._addKnownHandler("callback_query", filter, handler, group);
1850
+ }
1851
+ /** @internal */
1852
+ onInlineCallbackQuery(filter, handler, group) {
1853
+ this._addKnownHandler("inline_callback_query", filter, handler, group);
1854
+ }
1855
+ /** @internal */
1856
+ onBusinessCallbackQuery(filter, handler, group) {
1857
+ this._addKnownHandler("business_callback_query", filter, handler, group);
1858
+ }
1859
+ /** @internal */
1860
+ onPollUpdate(filter, handler, group) {
1861
+ this._addKnownHandler("poll", filter, handler, group);
1862
+ }
1863
+ /** @internal */
1864
+ onPollVote(filter, handler, group) {
1865
+ this._addKnownHandler("poll_vote", filter, handler, group);
1866
+ }
1867
+ /** @internal */
1868
+ onUserStatusUpdate(filter, handler, group) {
1869
+ this._addKnownHandler("user_status", filter, handler, group);
1870
+ }
1871
+ /** @internal */
1872
+ onUserTyping(filter, handler, group) {
1873
+ this._addKnownHandler("user_typing", filter, handler, group);
1874
+ }
1875
+ /** @internal */
1876
+ onHistoryRead(filter, handler, group) {
1877
+ this._addKnownHandler("history_read", filter, handler, group);
1878
+ }
1879
+ /** @internal */
1880
+ onBotStopped(filter, handler, group) {
1881
+ this._addKnownHandler("bot_stopped", filter, handler, group);
1882
+ }
1883
+ /** @internal */
1884
+ onBotChatJoinRequest(filter, handler, group) {
1885
+ this._addKnownHandler("bot_chat_join_request", filter, handler, group);
1886
+ }
1887
+ /** @internal */
1888
+ onChatJoinRequest(filter, handler, group) {
1889
+ this._addKnownHandler("chat_join_request", filter, handler, group);
1890
+ }
1891
+ /** @internal */
1892
+ onPreCheckoutQuery(filter, handler, group) {
1893
+ this._addKnownHandler("pre_checkout_query", filter, handler, group);
1894
+ }
1895
+ /** @internal */
1896
+ onStoryUpdate(filter, handler, group) {
1897
+ this._addKnownHandler("story", filter, handler, group);
1898
+ }
1899
+ /** @internal */
1900
+ onDeleteStory(filter, handler, group) {
1901
+ this._addKnownHandler("delete_story", filter, handler, group);
1902
+ }
1903
+ /** @internal */
1904
+ onBotReactionUpdate(filter, handler, group) {
1905
+ this._addKnownHandler("bot_reaction", filter, handler, group);
1906
+ }
1907
+ /** @internal */
1908
+ onBotReactionCountUpdate(filter, handler, group) {
1909
+ this._addKnownHandler("bot_reaction_count", filter, handler, group);
1910
+ }
1911
+ /** @internal */
1912
+ onBusinessConnectionUpdate(filter, handler, group) {
1913
+ this._addKnownHandler("business_connection", filter, handler, group);
1914
+ }
1915
+ /** @internal */
1916
+ onNewBusinessMessage(filter, handler, group) {
1917
+ this._addKnownHandler("new_business_message", filter, handler, group);
1918
+ }
1919
+ /** @internal */
1920
+ onEditBusinessMessage(filter, handler, group) {
1921
+ this._addKnownHandler("edit_business_message", filter, handler, group);
1922
+ }
1923
+ /** @internal */
1924
+ onBusinessMessageGroup(filter, handler, group) {
1925
+ this._addKnownHandler("business_message_group", filter, handler, group);
1926
+ }
1927
+ /** @internal */
1928
+ onDeleteBusinessMessage(filter, handler, group) {
1929
+ this._addKnownHandler("delete_business_message", filter, handler, group);
1930
+ }
1931
+ // end-codegen
1932
+ }
1933
+ function chat(type) {
1934
+ return (msg) => msg.chat.chatType === type;
1935
+ }
1936
+ const chatId = (id) => {
1937
+ const indexId = /* @__PURE__ */ new Set();
1938
+ const indexUsername = /* @__PURE__ */ new Set();
1939
+ let matchSelf = false;
1940
+ if (!Array.isArray(id)) id = [id];
1941
+ id.forEach((id2) => {
1942
+ if (id2 === "me" || id2 === "self") {
1943
+ matchSelf = true;
1944
+ } else if (typeof id2 === "number") {
1945
+ indexId.add(id2);
1946
+ } else {
1947
+ indexUsername.add(id2);
1948
+ }
1949
+ });
1950
+ return (upd) => {
1951
+ switch (upd._name) {
1952
+ case "poll_vote": {
1953
+ const peer = upd.peer;
1954
+ return peer.type === "chat" && (indexId.has(peer.id) || Boolean(peer.usernames?.some((u) => indexUsername.has(u.username))));
1955
+ }
1956
+ case "history_read":
1957
+ case "user_typing": {
1958
+ const id2 = upd.chatId;
1959
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
1960
+ }
1961
+ }
1962
+ const chat2 = upd.chat;
1963
+ return matchSelf && chat2.isSelf || indexId.has(chat2.id) || Boolean(chat2.usernames?.some((u) => indexUsername.has(u.username)));
1964
+ };
1965
+ };
1966
+ const any = () => true;
1967
+ function not(fn) {
1968
+ return (upd, state2) => {
1969
+ const res = fn(upd, state2);
1970
+ if (typeof res === "boolean") return !res;
1971
+ return res.then((r) => !r);
1972
+ };
1973
+ }
1974
+ function and(...fns) {
1975
+ return (upd, state2) => {
1976
+ let i = 0;
1977
+ const max = fns.length;
1978
+ const next = () => {
1979
+ if (i === max) return true;
1980
+ const res = fns[i++](upd, state2);
1981
+ if (typeof res === "boolean") {
1982
+ if (!res) return false;
1983
+ return next();
1984
+ }
1985
+ return res.then((r) => {
1986
+ if (!r) return false;
1987
+ return next();
1988
+ });
1989
+ };
1990
+ return next();
1991
+ };
1992
+ }
1993
+ function or(...fns) {
1994
+ return (upd, state2) => {
1995
+ let i = 0;
1996
+ const max = fns.length;
1997
+ const next = () => {
1998
+ if (i === max) return false;
1999
+ const res = fns[i++](upd, state2);
2000
+ if (typeof res === "boolean") {
2001
+ if (res) return true;
2002
+ return next();
2003
+ }
2004
+ return res.then((r) => {
2005
+ if (r) return true;
2006
+ return next();
2007
+ });
2008
+ };
2009
+ return next();
2010
+ };
2011
+ }
2012
+ function command(commands, {
2013
+ prefixes = "/",
2014
+ caseSensitive = false
2015
+ } = {}) {
2016
+ if (!Array.isArray(commands)) commands = [commands];
2017
+ if (!caseSensitive) {
2018
+ commands = commands.map((i) => typeof i === "string" ? i.toLowerCase() : i);
2019
+ }
2020
+ const argumentsRe = /(["'])(.*?)(?<!\\)\1|(\S+)/g;
2021
+ const unescapeRe = /\\(['"])/;
2022
+ const commandsRe = [];
2023
+ commands.forEach((cmd) => {
2024
+ if (typeof cmd !== "string") cmd = cmd.source;
2025
+ commandsRe.push(new RegExp(`^(${cmd})(?:\\s|$|@([a-zA-Z0-9_]+?bot)(?:\\s|$))`, caseSensitive ? "" : "i"));
2026
+ });
2027
+ if (prefixes === null) prefixes = [];
2028
+ if (typeof prefixes === "string") prefixes = [prefixes];
2029
+ const _prefixes = prefixes;
2030
+ const check = (msg) => {
2031
+ if (msg.isMessageGroup) return check(msg.messages[0]);
2032
+ for (const pref of _prefixes) {
2033
+ if (!msg.text.startsWith(pref)) continue;
2034
+ const withoutPrefix = msg.text.slice(pref.length);
2035
+ for (const regex2 of commandsRe) {
2036
+ const m = withoutPrefix.match(regex2);
2037
+ if (!m) continue;
2038
+ const lastGroup = m[m.length - 1];
2039
+ if (lastGroup) {
2040
+ const self = msg.client.storage.self.getCached();
2041
+ if (self && self.isBot && !self.usernames.includes(lastGroup)) {
2042
+ return false;
2043
+ }
2044
+ }
2045
+ const match = m.slice(1, -1);
2046
+ if (!caseSensitive) match[0] = match[0].toLowerCase();
2047
+ withoutPrefix.slice(m[0].length).replace(argumentsRe, ($0, $1, $2, $3) => {
2048
+ match.push(($2 || $3 || "").replace(unescapeRe, "$1"));
2049
+ return "";
2050
+ });
2051
+ msg.command = match;
2052
+ return true;
2053
+ }
2054
+ }
2055
+ return false;
2056
+ };
2057
+ return check;
2058
+ }
2059
+ const start = and(chat("private"), command("start"));
2060
+ const startGroup = and(or(chat("supergroup"), chat("group")), command("start"));
2061
+ function deeplinkBase(base) {
2062
+ return (params) => {
2063
+ if (!Array.isArray(params)) {
2064
+ return and(start, (_msg) => {
2065
+ const msg = _msg;
2066
+ if (msg.command.length !== 2) return false;
2067
+ const p = msg.command[1];
2068
+ if (typeof params === "string" && p === params) return true;
2069
+ const m = p.match(params);
2070
+ if (!m) return false;
2071
+ msg.command.push(...m.slice(1));
2072
+ return true;
2073
+ });
2074
+ }
2075
+ return and(base, (_msg) => {
2076
+ const msg = _msg;
2077
+ if (msg.command.length !== 2) return false;
2078
+ const p = msg.command[1];
2079
+ for (const param of params) {
2080
+ if (typeof param === "string" && p === param) return true;
2081
+ const m = p.match(param);
2082
+ if (!m) continue;
2083
+ msg.command.push(...m.slice(1));
2084
+ return true;
2085
+ }
2086
+ return false;
2087
+ });
2088
+ };
2089
+ }
2090
+ const deeplink = deeplinkBase(start);
2091
+ const deeplinkGroup = deeplinkBase(startGroup);
2092
+ function every(filter) {
2093
+ return (ctx, state2) => {
2094
+ let i = 0;
2095
+ const upds = ctx.messages;
2096
+ const max = upds.length;
2097
+ const next = () => {
2098
+ if (i === max) return true;
2099
+ const res = filter(upds[i++], state2);
2100
+ if (typeof res === "boolean") {
2101
+ if (!res) return false;
2102
+ return next();
2103
+ }
2104
+ return res.then((r) => {
2105
+ if (!r) return false;
2106
+ return next();
2107
+ });
2108
+ };
2109
+ return next();
2110
+ };
2111
+ }
2112
+ function some(filter) {
2113
+ return (ctx, state2) => {
2114
+ let i = 0;
2115
+ const upds = ctx.messages;
2116
+ const max = upds.length;
2117
+ const next = () => {
2118
+ if (i === max) return false;
2119
+ const res = filter(upds[i++], state2);
2120
+ if (typeof res === "boolean") {
2121
+ if (res) return true;
2122
+ return next();
2123
+ }
2124
+ return res.then((r) => {
2125
+ if (r) return true;
2126
+ return next();
2127
+ });
2128
+ };
2129
+ return next();
2130
+ };
2131
+ }
2132
+ const incoming = (msg) => !msg.isOutgoing;
2133
+ const outgoing = (msg) => msg.isOutgoing;
2134
+ const scheduled = (msg) => msg.isScheduled;
2135
+ const reply = (msg) => msg.replyToMessage !== null;
2136
+ function replyOrigin(origin) {
2137
+ return (msg) => msg.replyToMessage?.originIs(origin) ?? false;
2138
+ }
2139
+ const media = (msg) => msg.media !== null;
2140
+ function mediaOf(type) {
2141
+ return (msg) => msg.media?.type === type;
2142
+ }
2143
+ const photo = mediaOf("photo");
2144
+ const dice = mediaOf("dice");
2145
+ const contact = mediaOf("contact");
2146
+ const audio = mediaOf("audio");
2147
+ const voice = mediaOf("voice");
2148
+ const sticker = mediaOf("sticker");
2149
+ const document = mediaOf("document");
2150
+ const anyVideo = mediaOf("video");
2151
+ const location = mediaOf("location");
2152
+ const liveLocation = mediaOf("live_location");
2153
+ const game = mediaOf("game");
2154
+ const webpage = mediaOf("webpage");
2155
+ const venue = mediaOf("venue");
2156
+ const poll = mediaOf("poll");
2157
+ const invoice = mediaOf("invoice");
2158
+ const anyLocation = (msg) => msg.media instanceof core.RawLocation;
2159
+ const anyDocument = (msg) => msg.media instanceof core.RawDocument;
2160
+ const video = (msg) => msg.media?.type === "video" && !msg.media.isAnimation && !msg.media.isRound;
2161
+ const animation = (msg) => msg.media?.type === "video" && msg.media.isAnimation && !msg.media.isRound;
2162
+ const roundMessage = (msg) => msg.media?.type === "video" && !msg.media.isAnimation && msg.media.isRound;
2163
+ function stickerByType(type) {
2164
+ return (msg) => msg.media?.type === "sticker" && msg.media.stickerType === type;
2165
+ }
2166
+ function stickerBySourceType(type) {
2167
+ return (msg) => msg.media?.type === "sticker" && msg.media.sourceType === type;
2168
+ }
2169
+ const text = (msg) => msg.media === null && !msg.isService;
2170
+ const service = (msg) => msg.isService;
2171
+ function action(type) {
2172
+ if (Array.isArray(type)) {
2173
+ const index = {};
2174
+ type.forEach((it) => index[it] = true);
2175
+ return (msg) => msg.action?.type in index;
2176
+ }
2177
+ return (msg) => msg.action?.type === type;
2178
+ }
2179
+ function sender(type) {
2180
+ return (msg) => msg.sender.type === type;
2181
+ }
2182
+ function replyTo(filter) {
2183
+ return async (msg, state2) => {
2184
+ if (!msg.replyToMessage?.id) return false;
2185
+ const reply2 = msg._name === "new_message" ? await msg.getReplyTo() : msg.replyTo;
2186
+ if (!reply2) return false;
2187
+ if (msg._name === "new_message") {
2188
+ msg.getReplyTo = () => Promise.resolve(reply2);
2189
+ }
2190
+ if (!filter) return true;
2191
+ return filter(reply2, state2);
2192
+ };
2193
+ }
2194
+ function withCompleteSender(filter) {
2195
+ return async (msg, state2) => {
2196
+ try {
2197
+ await msg.getCompleteSender();
2198
+ } catch {
2199
+ return false;
2200
+ }
2201
+ if (!filter) return true;
2202
+ return filter(msg, state2);
2203
+ };
2204
+ }
2205
+ function withCompleteChat(filter) {
2206
+ return async (msg, state2) => {
2207
+ try {
2208
+ await msg.getCompleteChat();
2209
+ } catch {
2210
+ return false;
2211
+ }
2212
+ if (!filter) return true;
2213
+ return filter(msg, state2);
2214
+ };
2215
+ }
2216
+ const stateEmpty = async (upd, state2) => {
2217
+ if (!state2) return false;
2218
+ return !await state2.get();
2219
+ };
2220
+ function state(predicate) {
2221
+ return async (upd, state2) => {
2222
+ if (!state2) return false;
2223
+ const data = await state2.get();
2224
+ if (!data) return false;
2225
+ return predicate(data);
2226
+ };
2227
+ }
2228
+ function extractText(obj) {
2229
+ switch (obj._name) {
2230
+ case "new_message":
2231
+ case "new_business_message":
2232
+ return obj.text;
2233
+ case "inline_query":
2234
+ return obj.query;
2235
+ case "chosen_inline_result":
2236
+ return obj.id;
2237
+ case "callback_query":
2238
+ case "inline_callback_query":
2239
+ case "business_callback_query":
2240
+ if (obj.raw.data) return obj.dataStr;
2241
+ }
2242
+ return null;
2243
+ }
2244
+ function regex(regex2) {
2245
+ return (obj) => {
2246
+ const txt = extractText(obj);
2247
+ if (!txt) return false;
2248
+ const m = txt.match(regex2);
2249
+ if (m) {
2250
+ obj.match = m;
2251
+ return true;
2252
+ }
2253
+ return false;
2254
+ };
2255
+ }
2256
+ function equals(str, ignoreCase = false) {
2257
+ if (ignoreCase) {
2258
+ str = str.toLowerCase();
2259
+ return (obj) => extractText(obj)?.toLowerCase() === str;
2260
+ }
2261
+ return (obj) => extractText(obj) === str;
2262
+ }
2263
+ function contains(str, ignoreCase = false) {
2264
+ if (ignoreCase) {
2265
+ str = str.toLowerCase();
2266
+ return (obj) => {
2267
+ const txt = extractText(obj);
2268
+ return txt != null && txt.toLowerCase().includes(str);
2269
+ };
2270
+ }
2271
+ return (obj) => {
2272
+ const txt = extractText(obj);
2273
+ return txt != null && txt.includes(str);
2274
+ };
2275
+ }
2276
+ function startsWith(str, ignoreCase = false) {
2277
+ if (ignoreCase) {
2278
+ str = str.toLowerCase();
2279
+ return (obj) => {
2280
+ const txt = extractText(obj);
2281
+ return txt != null && txt.toLowerCase().substring(0, str.length) === str;
2282
+ };
2283
+ }
2284
+ return (obj) => {
2285
+ const txt = extractText(obj);
2286
+ return txt != null && txt.substring(0, str.length) === str;
2287
+ };
2288
+ }
2289
+ function endsWith(str, ignoreCase = false) {
2290
+ if (ignoreCase) {
2291
+ str = str.toLowerCase();
2292
+ return (obj) => {
2293
+ const txt = extractText(obj);
2294
+ return txt != null && txt.toLowerCase().substring(0, str.length) === str;
2295
+ };
2296
+ }
2297
+ return (obj) => {
2298
+ const txt = extractText(obj);
2299
+ return txt != null && txt.substring(0, str.length) === str;
2300
+ };
2301
+ }
2302
+ const chatMember = (types) => {
2303
+ if (Array.isArray(types)) {
2304
+ const index = {};
2305
+ types.forEach((typ) => index[typ] = true);
2306
+ return (upd) => upd.type in index;
2307
+ }
2308
+ return (upd) => upd.type === types;
2309
+ };
2310
+ const userStatus = (statuses) => {
2311
+ if (Array.isArray(statuses)) {
2312
+ const index = {};
2313
+ statuses.forEach((typ) => index[typ] = true);
2314
+ return (upd) => upd.status in index;
2315
+ }
2316
+ return (upd) => upd.status === statuses;
2317
+ };
2318
+ const chatMemberSelf = (upd) => upd.isSelf;
2319
+ const me = (msg) => msg.sender.type === "user" && msg.sender.isSelf || msg.isOutgoing;
2320
+ const bot = (msg) => msg.sender.constructor === core.User && msg.sender.isBot;
2321
+ const userId = (id) => {
2322
+ const indexId = /* @__PURE__ */ new Set();
2323
+ const indexUsername = /* @__PURE__ */ new Set();
2324
+ let matchSelf = false;
2325
+ if (!Array.isArray(id)) id = [id];
2326
+ id.forEach((id2) => {
2327
+ if (id2 === "me" || id2 === "self") {
2328
+ matchSelf = true;
2329
+ } else if (typeof id2 === "string") {
2330
+ indexUsername.add(id2);
2331
+ } else {
2332
+ indexId.add(id2);
2333
+ }
2334
+ });
2335
+ return (upd) => {
2336
+ switch (upd._name) {
2337
+ case "new_message":
2338
+ case "edit_message":
2339
+ case "new_business_message":
2340
+ case "edit_business_message": {
2341
+ const sender2 = upd.sender;
2342
+ return matchSelf && sender2.isSelf || indexId.has(sender2.id) || indexUsername.has(sender2.username);
2343
+ }
2344
+ case "user_status":
2345
+ case "user_typing": {
2346
+ const id2 = upd.userId;
2347
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
2348
+ }
2349
+ case "poll_vote":
2350
+ case "story":
2351
+ case "delete_story": {
2352
+ const peer = upd.peer;
2353
+ if (peer.type !== "user") return false;
2354
+ return matchSelf && peer.isSelf || indexId.has(peer.id) || Boolean(peer.usernames?.some((u) => indexUsername.has(u.username)));
2355
+ }
2356
+ case "history_read": {
2357
+ const id2 = upd.chatId;
2358
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
2359
+ }
2360
+ }
2361
+ const user = upd.user;
2362
+ return matchSelf && user.isSelf || indexId.has(user.id) || Boolean(user.usernames?.some((u) => indexUsername.has(u.username)));
2363
+ };
2364
+ };
2365
+ const bundle = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2366
+ __proto__: null,
2367
+ action,
2368
+ and,
2369
+ animation,
2370
+ any,
2371
+ anyDocument,
2372
+ anyLocation,
2373
+ anyVideo,
2374
+ audio,
2375
+ bot,
2376
+ chat,
2377
+ chatId,
2378
+ chatMember,
2379
+ chatMemberSelf,
2380
+ command,
2381
+ contact,
2382
+ contains,
2383
+ deeplink,
2384
+ deeplinkGroup,
2385
+ dice,
2386
+ document,
2387
+ endsWith,
2388
+ equals,
2389
+ every,
2390
+ game,
2391
+ incoming,
2392
+ invoice,
2393
+ liveLocation,
2394
+ location,
2395
+ me,
2396
+ media,
2397
+ mediaOf,
2398
+ not,
2399
+ or,
2400
+ outgoing,
2401
+ photo,
2402
+ poll,
2403
+ regex,
2404
+ reply,
2405
+ replyOrigin,
2406
+ replyTo,
2407
+ roundMessage,
2408
+ scheduled,
2409
+ sender,
2410
+ service,
2411
+ some,
2412
+ start,
2413
+ startGroup,
2414
+ startsWith,
2415
+ state,
2416
+ stateEmpty,
2417
+ sticker,
2418
+ stickerBySourceType,
2419
+ stickerByType,
2420
+ text,
2421
+ userId,
2422
+ userStatus,
2423
+ venue,
2424
+ video,
2425
+ voice,
2426
+ webpage,
2427
+ withCompleteChat,
2428
+ withCompleteSender
2429
+ }, Symbol.toStringTag, { value: "Module" }));
2430
+ var PropagationAction = /* @__PURE__ */ ((PropagationAction2) => {
2431
+ PropagationAction2["Stop"] = "stop";
2432
+ PropagationAction2["StopChildren"] = "stop-children";
2433
+ PropagationAction2["Continue"] = "continue";
2434
+ PropagationAction2["ToScene"] = "scene";
2435
+ return PropagationAction2;
2436
+ })(PropagationAction || {});
2437
+ var WizardSceneAction = /* @__PURE__ */ ((WizardSceneAction2) => {
2438
+ WizardSceneAction2["Next"] = "next";
2439
+ WizardSceneAction2["Stay"] = "stay";
2440
+ WizardSceneAction2["Exit"] = "exit";
2441
+ return WizardSceneAction2;
2442
+ })(WizardSceneAction || {});
2443
+ class WizardScene extends Dispatcher {
2444
+ _steps = 0;
2445
+ _defaultState = {};
2446
+ constructor(name, params) {
2447
+ super(void 0, { sceneName: name, ...params });
2448
+ }
2449
+ setDefaultState(defaultState) {
2450
+ this._defaultState = defaultState;
2451
+ }
2452
+ /**
2453
+ * Get the total number of registered steps
2454
+ */
2455
+ get totalSteps() {
2456
+ return this._steps;
2457
+ }
2458
+ /**
2459
+ * Go to the Nth step
2460
+ */
2461
+ async goToStep(state2, step) {
2462
+ if (step >= this._steps) {
2463
+ await state2.exit();
2464
+ } else {
2465
+ await state2.merge({ $step: step }, this._defaultState);
2466
+ }
2467
+ }
2468
+ /**
2469
+ * Skip N steps
2470
+ */
2471
+ async skip(state2, count = 1) {
2472
+ const { $step } = await state2.get() || {};
2473
+ if ($step === void 0) throw new Error("Wizard state is not initialized");
2474
+ return this.goToStep(state2, $step + count);
2475
+ }
2476
+ /**
2477
+ * Filter that will only pass if the current step is `step`
2478
+ */
2479
+ // eslint-disable-next-line ts/no-empty-object-type
2480
+ static onNthStep(step) {
2481
+ const filter = state((it) => it.$step === step);
2482
+ if (step === 0) return or(stateEmpty, filter);
2483
+ return filter;
2484
+ }
2485
+ /**
2486
+ * Filter that will only pass if the current step is the one after last one added
2487
+ */
2488
+ // eslint-disable-next-line ts/no-empty-object-type
2489
+ onCurrentStep() {
2490
+ return WizardScene.onNthStep(this._steps);
2491
+ }
2492
+ /**
2493
+ * Add a step to the wizard
2494
+ */
2495
+ addStep(handler) {
2496
+ const step = this._steps++;
2497
+ this.onNewMessage(WizardScene.onNthStep(step), async (msg, state2) => {
2498
+ const result = await handler(msg, state2);
2499
+ if (typeof result === "number") {
2500
+ await this.goToStep(state2, result);
2501
+ return;
2502
+ }
2503
+ switch (result) {
2504
+ case "next": {
2505
+ await this.goToStep(state2, step + 1);
2506
+ break;
2507
+ }
2508
+ case "exit":
2509
+ await state2.exit();
2510
+ break;
2511
+ }
2512
+ });
2513
+ }
2514
+ }
2515
+ exports.BusinessCallbackQueryContext = BusinessCallbackQueryContext;
2516
+ exports.BusinessMessageContext = BusinessMessageContext;
2517
+ exports.CallbackDataBuilder = CallbackDataBuilder;
2518
+ exports.CallbackQueryContext = CallbackQueryContext;
2519
+ exports.ChatJoinRequestUpdateContext = ChatJoinRequestUpdateContext;
2520
+ exports.ChosenInlineResultContext = ChosenInlineResultContext;
2521
+ exports.Dispatcher = Dispatcher;
2522
+ exports.InlineCallbackQueryContext = InlineCallbackQueryContext;
2523
+ exports.InlineQueryContext = InlineQueryContext;
2524
+ exports.MemoryStateStorage = MemoryStateStorage;
2525
+ exports.MessageContext = MessageContext;
2526
+ exports.PreCheckoutQueryContext = PreCheckoutQueryContext;
2527
+ exports.PropagationAction = PropagationAction;
2528
+ exports.RateLimitError = RateLimitError;
2529
+ exports.SqliteStateStorage = SqliteStateStorage;
2530
+ exports.UpdateState = UpdateState;
2531
+ exports.WizardScene = WizardScene;
2532
+ exports.WizardSceneAction = WizardSceneAction;
2533
+ exports.defaultStateKeyDelegate = defaultStateKeyDelegate;
2534
+ exports.filters = bundle;