@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/esm/dispatcher.js DELETED
@@ -1,904 +0,0 @@
1
- /* eslint-disable ts/no-unsafe-assignment */
2
- /* eslint-disable ts/no-unsafe-argument */
3
- /* eslint-disable ts/no-empty-object-type */
4
- // ^^ will be looked into in MTQ-29
5
- import { MtArgumentError, } from '@mtcute/core';
6
- import { _parsedUpdateToContext } from './context/parse.js';
7
- import { SceneTransitionContext } from './context/scene-transition.js';
8
- import { UpdateState, defaultStateKeyDelegate } from './state/index.js';
9
- import { StateService } from './state/service.js';
10
- /**
11
- * Updates dispatcher
12
- */
13
- export class Dispatcher {
14
- _groups = new Map();
15
- _groupsOrder = [];
16
- _client;
17
- _parent;
18
- _children = [];
19
- _scenes;
20
- _scene;
21
- _sceneScoped;
22
- _storage;
23
- _stateKeyDelegate;
24
- _customStateKeyDelegate;
25
- _customStorage;
26
- _deps = {};
27
- _errorHandler;
28
- _preUpdateHandler;
29
- _postUpdateHandler;
30
- _sceneTransitionHandler;
31
- constructor(client, params) {
32
- this.dispatchRawUpdate = this.dispatchRawUpdate.bind(this);
33
- this.dispatchUpdate = this.dispatchUpdate.bind(this);
34
- // eslint-disable-next-line prefer-const
35
- let { storage, key, sceneName } = params ?? {};
36
- if (client) {
37
- this.bindToClient(client);
38
- if (storage) {
39
- this._storage = new StateService(storage);
40
- this._stateKeyDelegate = key ?? defaultStateKeyDelegate;
41
- }
42
- }
43
- else {
44
- // child dispatcher without client
45
- if (storage) {
46
- this._customStorage = new StateService(storage);
47
- }
48
- if (key) {
49
- this._customStateKeyDelegate = key;
50
- }
51
- if (sceneName) {
52
- if (sceneName[0] === '$') {
53
- throw new MtArgumentError('Scene name cannot start with $');
54
- }
55
- this._scene = sceneName;
56
- }
57
- }
58
- }
59
- static for(client, params) {
60
- return new Dispatcher(client, params);
61
- }
62
- /**
63
- * Create a new child dispatcher.
64
- */
65
- static child(params) {
66
- return new Dispatcher(undefined, params);
67
- }
68
- /**
69
- * Create a new scene dispatcher
70
- */
71
- static scene(name, params) {
72
- return new Dispatcher(undefined, { sceneName: name, ...params });
73
- }
74
- /** For scene dispatchers, name of the scene */
75
- get sceneName() {
76
- return this._scene;
77
- }
78
- inject(name, value) {
79
- if (this._parent) {
80
- throw new MtArgumentError('Cannot inject dependencies to child dispatchers');
81
- }
82
- if (typeof name === 'object') {
83
- for (const [k, v] of Object.entries(name)) {
84
- this._deps[k] = v;
85
- }
86
- }
87
- else {
88
- this._deps[name] = value;
89
- }
90
- }
91
- /**
92
- * Get the dependencies injected into this dispatcher.
93
- */
94
- get deps() {
95
- return this._deps;
96
- }
97
- /**
98
- * Bind the dispatcher to the client.
99
- * Called by the constructor automatically if
100
- * `client` was passed.
101
- *
102
- * Dispatcher also uses bound client to throw errors
103
- */
104
- bindToClient(client) {
105
- client.on('update', this.dispatchUpdate);
106
- client.on('raw_update', this.dispatchRawUpdate);
107
- this._client = client;
108
- }
109
- /**
110
- * Unbind a dispatcher from the client.
111
- */
112
- unbind() {
113
- if (this._client) {
114
- this._client.off('update', this.dispatchUpdate);
115
- this._client.off('raw_update', this.dispatchRawUpdate);
116
- this._client = undefined;
117
- }
118
- }
119
- /**
120
- * Destroy the dispatcher and all its children.
121
- *
122
- * When destroying, all the registered handlers are removed,
123
- * and the underlying storage is freed.
124
- */
125
- async destroy() {
126
- if (this._parent && this._customStorage) {
127
- await this._customStorage.destroy();
128
- }
129
- else if (!this._parent && this._storage) {
130
- await this._storage.destroy();
131
- }
132
- this.removeUpdateHandler('all');
133
- for (const child of this._children) {
134
- await child.destroy();
135
- }
136
- for (const scene of this._scenes?.values() ?? []) {
137
- await scene.destroy();
138
- }
139
- }
140
- /**
141
- * Process a raw update with this dispatcher.
142
- * Calling this method without bound client will not work.
143
- *
144
- * Under the hood asynchronously calls {@link dispatchRawUpdateNow}
145
- * with error handler set to client's one.
146
- *
147
- * @param update Update to process
148
- * @param peers Peers index
149
- */
150
- dispatchRawUpdate(update, peers) {
151
- if (!this._client)
152
- return;
153
- // order does not matter in the dispatcher,
154
- // so we can handle each update in its own task
155
- this.dispatchRawUpdateNow(update, peers).catch(err => this._client.emitError(err));
156
- }
157
- /**
158
- * Process a raw update right now in the current stack.
159
- *
160
- * Unlike {@link dispatchRawUpdate}, this does not schedule
161
- * the update to be dispatched, but dispatches it immediately,
162
- * and after `await`ing this method you can be certain that the update
163
- * was fully processed by all the registered handlers, including children.
164
- *
165
- * @param update Update to process
166
- * @param peers Peers map
167
- * @returns Whether the update was handled
168
- */
169
- async dispatchRawUpdateNow(update, peers) {
170
- if (!this._client)
171
- return false;
172
- let handled = false;
173
- outer: for (const grp of this._groupsOrder) {
174
- const group = this._groups.get(grp);
175
- if (group.has('raw')) {
176
- const handlers = group.get('raw');
177
- for (const h of handlers) {
178
- let result;
179
- if (!h.check || (await h.check(this._client, update, peers))) {
180
- result = await h.callback(this._client, update, peers);
181
- handled = true;
182
- }
183
- else {
184
- continue;
185
- }
186
- switch (result) {
187
- case 'continue':
188
- continue;
189
- case 'stop':
190
- break outer;
191
- case 'stop-children':
192
- return handled;
193
- }
194
- break;
195
- }
196
- }
197
- }
198
- for (const child of this._children) {
199
- const childHandled = await child.dispatchRawUpdateNow(update, peers);
200
- handled ||= childHandled;
201
- }
202
- return handled;
203
- }
204
- /**
205
- * Process an update with this dispatcher.
206
- * Calling this method without bound client will not work.
207
- *
208
- * Under the hood asynchronously calls {@link dispatchUpdateNow}
209
- * with error handler set to client's one.
210
- *
211
- * @param update Update to process
212
- */
213
- dispatchUpdate(update) {
214
- if (!this._client)
215
- return;
216
- // order does not matter in the dispatcher,
217
- // so we can handle each update in its own task
218
- this.dispatchUpdateNow(update).catch(err => this._client.emitError(err));
219
- }
220
- /**
221
- * Process an update right now in the current stack.
222
- *
223
- * Unlike {@link dispatchUpdate}, this does not schedule
224
- * the update to be dispatched, but dispatches it immediately,
225
- * and after `await`ing this method you can be certain that the update
226
- * was fully processed by all the registered handlers, including children.
227
- *
228
- * @param update Update to process
229
- * @returns Whether the update was handled
230
- */
231
- async dispatchUpdateNow(update) {
232
- return this._dispatchUpdateNowImpl(update);
233
- }
234
- async _dispatchUpdateNowImpl(update,
235
- // this is getting a bit crazy lol
236
- parsedState, parsedScene, forceScene, parsedContext) {
237
- if (!this._client)
238
- return false;
239
- if (parsedScene === undefined) {
240
- if (this._storage
241
- && this._scenes
242
- && (update.name === 'new_message'
243
- || update.name === 'edit_message'
244
- || update.name === 'callback_query'
245
- || update.name === 'message_group'
246
- || update.name === 'new_business_message'
247
- || update.name === 'edit_business_message'
248
- || update.name === 'business_message_group')) {
249
- // no need to fetch scene if there are no registered scenes
250
- if (!parsedContext)
251
- parsedContext = _parsedUpdateToContext(this._client, update);
252
- const key = await this._stateKeyDelegate(parsedContext);
253
- if (key) {
254
- parsedScene = await this._storage.getCurrentScene(key);
255
- }
256
- else {
257
- parsedScene = null;
258
- }
259
- }
260
- else {
261
- parsedScene = null;
262
- }
263
- }
264
- if (!forceScene && parsedScene !== null) {
265
- if (this._scene) {
266
- if (this._scene !== parsedScene) {
267
- // should not happen, but just in case
268
- return false;
269
- }
270
- }
271
- else {
272
- if (!this._scenes || !this._scenes.has(parsedScene)) {
273
- // not registered scene
274
- return false;
275
- }
276
- return this._scenes.get(parsedScene)._dispatchUpdateNowImpl(update, parsedState, parsedScene, true);
277
- }
278
- }
279
- if (parsedState === undefined) {
280
- if (this._storage
281
- && (update.name === 'new_message'
282
- || update.name === 'edit_message'
283
- || update.name === 'callback_query'
284
- || update.name === 'message_group'
285
- || update.name === 'new_business_message'
286
- || update.name === 'edit_business_message'
287
- || update.name === 'business_message_group')) {
288
- if (!parsedContext)
289
- parsedContext = _parsedUpdateToContext(this._client, update);
290
- const key = await this._stateKeyDelegate(parsedContext);
291
- if (key) {
292
- let customKey;
293
- if (!this._customStateKeyDelegate
294
- || (customKey = await this._customStateKeyDelegate(parsedContext))) {
295
- parsedState = new UpdateState(this._storage, key, this._scene ?? null, this._sceneScoped, this._customStorage, customKey);
296
- }
297
- }
298
- else {
299
- parsedState = null;
300
- }
301
- }
302
- else {
303
- parsedState = null;
304
- }
305
- }
306
- let shouldDispatch = true;
307
- let shouldDispatchChildren = true;
308
- let handled = false;
309
- switch (await this._preUpdateHandler?.(update, parsedState)) {
310
- case 'stop':
311
- shouldDispatch = false;
312
- break;
313
- case 'stop-children':
314
- return false;
315
- }
316
- if (shouldDispatch) {
317
- outer: for (const grp of this._groupsOrder) {
318
- const group = this._groups.get(grp);
319
- if (group.has(update.name)) {
320
- // raw is not handled here, so we can safely assume this
321
- const handlers = group.get(update.name);
322
- try {
323
- for (const h of handlers) {
324
- let result;
325
- if (!parsedContext)
326
- parsedContext = _parsedUpdateToContext(this._client, update);
327
- if (!h.check || (await h.check(parsedContext, parsedState))) {
328
- result = await h.callback(parsedContext, parsedState);
329
- handled = true;
330
- }
331
- else {
332
- continue;
333
- }
334
- if (parsedState && this._scenes) {
335
- // check if scene transition was made
336
- const newScene = parsedState.scene;
337
- if (parsedScene !== newScene) {
338
- const nextDp = newScene ? this._scenes.get(newScene) : this._parent;
339
- if (!nextDp) {
340
- throw new MtArgumentError(`Scene ${newScene} not found`);
341
- }
342
- if (nextDp._sceneTransitionHandler) {
343
- const transition = new SceneTransitionContext(parsedScene, parsedContext);
344
- const transitionResult = await nextDp._sceneTransitionHandler?.(transition, parsedState);
345
- switch (transitionResult) {
346
- case 'stop':
347
- return true;
348
- case 'continue':
349
- continue;
350
- case 'scene': {
351
- const scene = parsedState.scene;
352
- const dp = scene ? nextDp._scenes.get(scene) : nextDp._parent;
353
- // eslint-disable-next-line ts/return-await
354
- return dp._dispatchUpdateNowImpl(update, undefined, scene, true);
355
- }
356
- }
357
- }
358
- }
359
- }
360
- switch (result) {
361
- case 'continue':
362
- continue;
363
- case 'stop':
364
- break outer;
365
- case 'stop-children':
366
- shouldDispatchChildren = false;
367
- break outer;
368
- case 'scene': {
369
- if (!parsedState) {
370
- throw new MtArgumentError('Cannot use ToScene without state');
371
- }
372
- const scene = parsedState.scene;
373
- const dp = scene ? this._scenes.get(scene) : this._parent;
374
- // eslint-disable-next-line ts/return-await
375
- return dp._dispatchUpdateNowImpl(update, undefined, scene, true);
376
- }
377
- }
378
- break;
379
- }
380
- }
381
- catch (e) {
382
- if (this._errorHandler) {
383
- const handled = await this._errorHandler(e, update, parsedState);
384
- if (!handled)
385
- throw e;
386
- }
387
- else {
388
- throw e;
389
- }
390
- }
391
- }
392
- }
393
- }
394
- if (shouldDispatchChildren) {
395
- for (const child of this._children) {
396
- const childHandled = await child._dispatchUpdateNowImpl(update);
397
- handled ||= childHandled;
398
- }
399
- }
400
- await this._postUpdateHandler?.(handled, update, parsedState);
401
- return handled;
402
- }
403
- /**
404
- * Add an update handler to a given handlers group
405
- *
406
- * @param handler Update handler
407
- * @param group Handler group index
408
- */
409
- addUpdateHandler(handler, group = 0) {
410
- if (!this._groups.has(group)) {
411
- this._groups.set(group, new Map());
412
- this._groupsOrder.push(group);
413
- this._groupsOrder.sort((a, b) => a - b);
414
- }
415
- if (!this._groups.get(group).has(handler.name)) {
416
- this._groups.get(group).set(handler.name, []);
417
- }
418
- this._groups.get(group).get(handler.name).push(handler);
419
- }
420
- /**
421
- * Remove an update handler (or handlers) from a given
422
- * handler group.
423
- *
424
- * @param handler Update handler to remove, its name or `'all'` to remove all
425
- * @param group Handler group index (null to affect all groups)
426
- */
427
- removeUpdateHandler(handler, group = 0) {
428
- if (group !== null && !this._groups.has(group)) {
429
- return;
430
- }
431
- if (typeof handler === 'string') {
432
- if (handler === 'all') {
433
- if (group === null) {
434
- this._groups = new Map();
435
- }
436
- else {
437
- this._groups.delete(group);
438
- }
439
- }
440
- else if (group !== null) {
441
- this._groups.get(group).delete(handler);
442
- }
443
- return;
444
- }
445
- if (group === null)
446
- return;
447
- if (!this._groups.get(group).has(handler.name)) {
448
- return;
449
- }
450
- const idx = this._groups.get(group).get(handler.name).indexOf(handler);
451
- if (idx > -1) {
452
- this._groups.get(group).get(handler.name).splice(idx, 1);
453
- }
454
- }
455
- /**
456
- * Register an error handler.
457
- *
458
- * This is used locally within this dispatcher
459
- * (does not affect children/parent) whenever
460
- * an error is thrown inside an update handler.
461
- * Not used for raw update handlers
462
- *
463
- * When an error is thrown, but there is no error
464
- * handler, it is propagated to `TelegramClient`.
465
- *
466
- * There can be at most one error handler.
467
- * Pass `null` to remove it.
468
- *
469
- * @param handler Error handler
470
- */
471
- onError(handler) {
472
- if (handler)
473
- this._errorHandler = handler;
474
- else
475
- this._errorHandler = undefined;
476
- }
477
- /**
478
- * Register pre-update middleware.
479
- *
480
- * This is used locally within this dispatcher
481
- * (does not affect children/parent) before processing
482
- * an update, and can be used to skip this update.
483
- *
484
- * There can be at most one pre-update middleware.
485
- * Pass `null` to remove it.
486
- *
487
- * @param handler Pre-update middleware
488
- */
489
- onPreUpdate(handler) {
490
- if (handler)
491
- this._preUpdateHandler = handler;
492
- else
493
- this._preUpdateHandler = undefined;
494
- }
495
- /**
496
- * Register post-update middleware.
497
- *
498
- * This is used locally within this dispatcher
499
- * (does not affect children/parent) after successfully
500
- * processing an update, and can be used for stats.
501
- *
502
- * There can be at most one post-update middleware.
503
- * Pass `null` to remove it.
504
- *
505
- * @param handler Pre-update middleware
506
- */
507
- onPostUpdate(handler) {
508
- if (handler)
509
- this._postUpdateHandler = handler;
510
- else
511
- this._postUpdateHandler = undefined;
512
- }
513
- /**
514
- * Set error handler that will propagate
515
- * the error to the parent dispatcher
516
- */
517
- propagateErrorToParent(err, update, state) {
518
- if (!this.parent) {
519
- throw new MtArgumentError('This dispatcher is not a child');
520
- }
521
- if (this.parent._errorHandler) {
522
- return this.parent._errorHandler(err, update, state);
523
- }
524
- throw err;
525
- }
526
- // children //
527
- /**
528
- * Get parent dispatcher if current dispatcher is a child.
529
- * Otherwise, return `null`
530
- */
531
- get parent() {
532
- return this._parent ?? null;
533
- }
534
- _prepareChild(child) {
535
- if (child._client) {
536
- throw new MtArgumentError(`Provided dispatcher is ${child._parent
537
- ? 'already a child. Use parent.removeChild() before calling addChild()'
538
- : 'already bound to a client. Use unbind() before calling addChild()'}`);
539
- }
540
- child._parent = this;
541
- child._client = this._client;
542
- child._storage = this._storage;
543
- child._deps = this._deps;
544
- child._scenes = this._scenes;
545
- child._stateKeyDelegate = this._stateKeyDelegate;
546
- child._customStorage ??= this._customStorage;
547
- child._customStateKeyDelegate ??= this._customStateKeyDelegate;
548
- }
549
- /**
550
- * Add a child dispatcher.
551
- *
552
- * Child dispatchers are called when dispatching updates
553
- * just like normal, except they can be controlled
554
- * externally. Additionally, child dispatcher have their own
555
- * independent handler grouping that does not interfere with parent's,
556
- * including `StopPropagation` (i.e. returning `StopPropagation` will
557
- * still call children. To entirely stop, use `StopChildrenPropagation`)
558
- *
559
- * Note that child dispatchers share the same TelegramClient and
560
- * storage binding as the parent, don't bind them manually.
561
- *
562
- * @param child Other dispatcher
563
- */
564
- addChild(child) {
565
- if (this._children.includes(child))
566
- return;
567
- this._prepareChild(child);
568
- this._children.push(child);
569
- }
570
- addScene(scene, scoped = true) {
571
- if (!this._scenes)
572
- this._scenes = new Map();
573
- if (!scene._scene) {
574
- throw new MtArgumentError('Non-scene dispatcher passed to addScene. Use `Dispatcher.scene()` to create one.');
575
- }
576
- if (this._scenes.has(scene._scene)) {
577
- throw new MtArgumentError(`Scene with name ${scene._scene} is already registered!`);
578
- }
579
- this._prepareChild(scene);
580
- scene._sceneScoped = scoped;
581
- this._scenes.set(scene._scene, scene);
582
- }
583
- /**
584
- * Remove a child dispatcher.
585
- *
586
- * Removing child dispatcher will also remove
587
- * child dispatcher's client binding.
588
- *
589
- * If the provided dispatcher is not a child of current,
590
- * this function will silently fail.
591
- *
592
- * @param child Other dispatcher
593
- */
594
- removeChild(child) {
595
- const idx = this._children.indexOf(child);
596
- if (idx > -1) {
597
- child._unparent();
598
- this._children.splice(idx, 1);
599
- }
600
- }
601
- _unparent() {
602
- this._parent = this._client = undefined;
603
- this._deps = {}; // to avoid dangling references
604
- this._stateKeyDelegate = undefined;
605
- this._storage = undefined;
606
- }
607
- /**
608
- * Extend current dispatcher by copying other dispatcher's
609
- * handlers and children to the current.
610
- *
611
- * This might be more efficient for simple cases, but do note that the handler
612
- * groups, children and scenes will get merged (unlike {@link addChild},
613
- * where they are independent). Also note that unlike with children,
614
- * when adding handlers to `other` *after* you extended
615
- * the current dispatcher, changes will not be applied.
616
- *
617
- * @param other Other dispatcher
618
- */
619
- extend(other) {
620
- if (other._customStorage || other._customStateKeyDelegate) {
621
- throw new MtArgumentError('Provided dispatcher has custom storage and cannot be extended from.');
622
- }
623
- other._groupsOrder.forEach((group) => {
624
- if (!this._groups.has(group)) {
625
- this._groups.set(group, other._groups.get(group));
626
- this._groupsOrder.push(group);
627
- }
628
- else {
629
- const otherGrp = other._groups.get(group);
630
- const selfGrp = this._groups.get(group);
631
- for (const typ of otherGrp.keys()) {
632
- if (!selfGrp.has(typ)) {
633
- selfGrp.set(typ, otherGrp.get(typ));
634
- }
635
- else {
636
- // selfGrp[typ].push(...otherGrp[typ])
637
- selfGrp.get(typ).push(...otherGrp.get(typ));
638
- }
639
- }
640
- }
641
- });
642
- other._children.forEach((it) => {
643
- it._unparent();
644
- this.addChild(it);
645
- });
646
- if (other._scenes) {
647
- const otherScenes = other._scenes;
648
- if (!this._scenes)
649
- this._scenes = new Map();
650
- const myScenes = this._scenes;
651
- for (const key of otherScenes.keys()) {
652
- otherScenes.get(key)._unparent();
653
- if (myScenes.has(key)) {
654
- // will be overwritten
655
- myScenes.delete(key);
656
- }
657
- this.addScene(otherScenes.get(key), otherScenes.get(key)._sceneScoped);
658
- }
659
- }
660
- this._groupsOrder.sort((a, b) => a - b);
661
- }
662
- /**
663
- * Create a clone of this dispatcher, that has the same handlers,
664
- * but is not bound to a client or to a parent dispatcher.
665
- *
666
- * Custom Storage and key delegate are copied too.
667
- *
668
- * By default, child dispatchers (and scenes) are ignored, since
669
- * that requires cloning every single one of them recursively
670
- * and then binding them back.
671
- *
672
- * @param children Whether to also clone children and scenes
673
- */
674
- clone(children = false) {
675
- const dp = new Dispatcher();
676
- // copy handlers.
677
- for (const key of this._groups.keys()) {
678
- const idx = key;
679
- dp._groups.set(idx, new Map());
680
- for (const type of this._groups.get(idx).keys()) {
681
- // dp._groups.get(idx)!.set(type, [...this._groups.get(idx)!].get(type)!])
682
- dp._groups.get(idx).set(type, [...this._groups.get(idx).get(type)]);
683
- }
684
- }
685
- dp._groupsOrder = [...this._groupsOrder];
686
- dp._errorHandler = this._errorHandler;
687
- dp._customStateKeyDelegate = this._customStateKeyDelegate;
688
- dp._customStorage = this._customStorage;
689
- if (children) {
690
- this._children.forEach((it) => {
691
- const child = it.clone(true);
692
- dp.addChild(child);
693
- });
694
- if (this._scenes) {
695
- for (const key of this._scenes.keys()) {
696
- const scene = this._scenes.get(key).clone(true);
697
- dp.addScene(scene, this._scenes.get(key)._sceneScoped);
698
- }
699
- }
700
- }
701
- return dp;
702
- }
703
- getState(object) {
704
- if (!this._storage) {
705
- throw new MtArgumentError('Cannot use getUpdateState() filter without state storage');
706
- }
707
- if (typeof object === 'string') {
708
- return new UpdateState(this._storage, object, this._scene ?? null, this._sceneScoped, this._customStorage);
709
- }
710
- return Promise.resolve(this._stateKeyDelegate(object)).then((key) => {
711
- if (!key) {
712
- throw new MtArgumentError('Cannot derive key from given object');
713
- }
714
- if (!this._customStateKeyDelegate) {
715
- return new UpdateState(this._storage, key, this._scene ?? null, this._sceneScoped, this._customStorage);
716
- }
717
- return Promise.resolve(this._customStateKeyDelegate(object)).then((customKey) => {
718
- if (!customKey) {
719
- throw new MtArgumentError('Cannot derive custom key from given object');
720
- }
721
- return new UpdateState(this._storage, key, this._scene ?? null, this._sceneScoped, this._customStorage, customKey);
722
- });
723
- });
724
- }
725
- /**
726
- * Get global state.
727
- *
728
- * This will load the state for the given object
729
- * ignoring local custom storage, key delegate and scene scope.
730
- */
731
- getGlobalState(object) {
732
- if (!this._parent) {
733
- throw new MtArgumentError('This dispatcher does not have a parent');
734
- }
735
- return Promise.resolve(this._stateKeyDelegate(object)).then((key) => {
736
- if (!key) {
737
- throw new MtArgumentError('Cannot derive key from given object');
738
- }
739
- return new UpdateState(this._storage, key, this._scene ?? null, false);
740
- });
741
- }
742
- // addUpdateHandler convenience wrappers //
743
- _addKnownHandler(name, filter, handler, group) {
744
- if (typeof handler === 'number' || typeof handler === 'undefined') {
745
- this.addUpdateHandler({
746
- name,
747
- callback: filter,
748
- }, handler);
749
- }
750
- else {
751
- this.addUpdateHandler({
752
- name,
753
- callback: handler,
754
- check: filter,
755
- }, group);
756
- }
757
- }
758
- /** @internal */
759
- onRawUpdate(filter, handler, group) {
760
- this._addKnownHandler('raw', filter, handler, group);
761
- }
762
- /**
763
- * Register a scene transition handler
764
- *
765
- * This handler is called whenever a scene transition occurs
766
- * in the context of the scene that is being entered,
767
- * and before any of the its own handlers are called,
768
- * and can be used to customize the transition behavior:
769
- * - `Stop` to prevent dispatching the update any further **even if ToScene/ToRoot was used**
770
- * - `Continue` same as Stop, but still dispatch the update to children
771
- * - `ToScene` to prevent the transition and dispatch the update to the scene entered in the transition handler
772
- *
773
- * > **Note**: if multiple `state.enter()` calls were made within the same update,
774
- * > this handler will only be called for the last one.
775
- *
776
- * @param handler Raw update handler
777
- * @param group Handler group index
778
- */
779
- onSceneTransition(handler) {
780
- if (handler)
781
- this._sceneTransitionHandler = handler;
782
- else
783
- this._sceneTransitionHandler = undefined;
784
- }
785
- /** @internal */
786
- onAnyCallbackQuery(filter, handler, group) {
787
- this._addKnownHandler('callback_query', filter, handler, group);
788
- this._addKnownHandler('inline_callback_query', filter, handler, group);
789
- this._addKnownHandler('business_callback_query', filter, handler, group);
790
- }
791
- /** @internal */
792
- onNewMessage(filter, handler, group) {
793
- this._addKnownHandler('new_message', filter, handler, group);
794
- }
795
- /** @internal */
796
- onEditMessage(filter, handler, group) {
797
- this._addKnownHandler('edit_message', filter, handler, group);
798
- }
799
- /** @internal */
800
- onMessageGroup(filter, handler, group) {
801
- this._addKnownHandler('message_group', filter, handler, group);
802
- }
803
- /** @internal */
804
- onDeleteMessage(filter, handler, group) {
805
- this._addKnownHandler('delete_message', filter, handler, group);
806
- }
807
- /** @internal */
808
- onChatMemberUpdate(filter, handler, group) {
809
- this._addKnownHandler('chat_member', filter, handler, group);
810
- }
811
- /** @internal */
812
- onInlineQuery(filter, handler, group) {
813
- this._addKnownHandler('inline_query', filter, handler, group);
814
- }
815
- /** @internal */
816
- onChosenInlineResult(filter, handler, group) {
817
- this._addKnownHandler('chosen_inline_result', filter, handler, group);
818
- }
819
- /** @internal */
820
- onCallbackQuery(filter, handler, group) {
821
- this._addKnownHandler('callback_query', filter, handler, group);
822
- }
823
- /** @internal */
824
- onInlineCallbackQuery(filter, handler, group) {
825
- this._addKnownHandler('inline_callback_query', filter, handler, group);
826
- }
827
- /** @internal */
828
- onBusinessCallbackQuery(filter, handler, group) {
829
- this._addKnownHandler('business_callback_query', filter, handler, group);
830
- }
831
- /** @internal */
832
- onPollUpdate(filter, handler, group) {
833
- this._addKnownHandler('poll', filter, handler, group);
834
- }
835
- /** @internal */
836
- onPollVote(filter, handler, group) {
837
- this._addKnownHandler('poll_vote', filter, handler, group);
838
- }
839
- /** @internal */
840
- onUserStatusUpdate(filter, handler, group) {
841
- this._addKnownHandler('user_status', filter, handler, group);
842
- }
843
- /** @internal */
844
- onUserTyping(filter, handler, group) {
845
- this._addKnownHandler('user_typing', filter, handler, group);
846
- }
847
- /** @internal */
848
- onHistoryRead(filter, handler, group) {
849
- this._addKnownHandler('history_read', filter, handler, group);
850
- }
851
- /** @internal */
852
- onBotStopped(filter, handler, group) {
853
- this._addKnownHandler('bot_stopped', filter, handler, group);
854
- }
855
- /** @internal */
856
- onBotChatJoinRequest(filter, handler, group) {
857
- this._addKnownHandler('bot_chat_join_request', filter, handler, group);
858
- }
859
- /** @internal */
860
- onChatJoinRequest(filter, handler, group) {
861
- this._addKnownHandler('chat_join_request', filter, handler, group);
862
- }
863
- /** @internal */
864
- onPreCheckoutQuery(filter, handler, group) {
865
- this._addKnownHandler('pre_checkout_query', filter, handler, group);
866
- }
867
- /** @internal */
868
- onStoryUpdate(filter, handler, group) {
869
- this._addKnownHandler('story', filter, handler, group);
870
- }
871
- /** @internal */
872
- onDeleteStory(filter, handler, group) {
873
- this._addKnownHandler('delete_story', filter, handler, group);
874
- }
875
- /** @internal */
876
- onBotReactionUpdate(filter, handler, group) {
877
- this._addKnownHandler('bot_reaction', filter, handler, group);
878
- }
879
- /** @internal */
880
- onBotReactionCountUpdate(filter, handler, group) {
881
- this._addKnownHandler('bot_reaction_count', filter, handler, group);
882
- }
883
- /** @internal */
884
- onBusinessConnectionUpdate(filter, handler, group) {
885
- this._addKnownHandler('business_connection', filter, handler, group);
886
- }
887
- /** @internal */
888
- onNewBusinessMessage(filter, handler, group) {
889
- this._addKnownHandler('new_business_message', filter, handler, group);
890
- }
891
- /** @internal */
892
- onEditBusinessMessage(filter, handler, group) {
893
- this._addKnownHandler('edit_business_message', filter, handler, group);
894
- }
895
- /** @internal */
896
- onBusinessMessageGroup(filter, handler, group) {
897
- this._addKnownHandler('business_message_group', filter, handler, group);
898
- }
899
- /** @internal */
900
- onDeleteBusinessMessage(filter, handler, group) {
901
- this._addKnownHandler('delete_business_message', filter, handler, group);
902
- }
903
- }
904
- //# sourceMappingURL=dispatcher.js.map