@mtcute/dispatcher 0.1.0

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