@mtcute/dispatcher 0.17.2 → 0.18.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 (111) hide show
  1. package/callback-data-builder.cjs +126 -0
  2. package/callback-data-builder.d.cts +49 -0
  3. package/callback-data-builder.js +121 -0
  4. package/callback-data-builder.test.d.cts +1 -0
  5. package/context/base.d.cts +9 -0
  6. package/context/business-message.cjs +143 -0
  7. package/context/business-message.d.cts +60 -0
  8. package/context/business-message.js +138 -0
  9. package/context/callback-query.cjs +92 -0
  10. package/context/callback-query.d.cts +62 -0
  11. package/context/callback-query.js +87 -0
  12. package/context/chat-join-request.cjs +32 -0
  13. package/context/chat-join-request.d.cts +17 -0
  14. package/context/chat-join-request.d.ts +1 -1
  15. package/context/chat-join-request.js +27 -0
  16. package/context/chosen-inline-result.cjs +30 -0
  17. package/context/chosen-inline-result.d.cts +22 -0
  18. package/context/chosen-inline-result.d.ts +1 -1
  19. package/context/chosen-inline-result.js +25 -0
  20. package/context/index.d.cts +9 -0
  21. package/context/inline-query.cjs +20 -0
  22. package/context/inline-query.d.cts +15 -0
  23. package/context/inline-query.js +15 -0
  24. package/context/message.cjs +182 -0
  25. package/context/message.d.cts +82 -0
  26. package/context/message.d.ts +2 -2
  27. package/context/message.js +177 -0
  28. package/context/parse.cjs +45 -0
  29. package/context/parse.d.cts +13 -0
  30. package/context/parse.js +40 -0
  31. package/context/pre-checkout-query.cjs +24 -0
  32. package/context/pre-checkout-query.d.cts +17 -0
  33. package/context/pre-checkout-query.d.ts +1 -1
  34. package/context/pre-checkout-query.js +19 -0
  35. package/context/scene-transition.cjs +52 -0
  36. package/context/scene-transition.d.cts +24 -0
  37. package/context/scene-transition.d.ts +1 -1
  38. package/context/scene-transition.js +47 -0
  39. package/dispatcher.cjs +860 -0
  40. package/dispatcher.d.cts +880 -0
  41. package/dispatcher.d.ts +4 -4
  42. package/dispatcher.js +855 -0
  43. package/filters/bots.cjs +94 -0
  44. package/filters/bots.d.cts +62 -0
  45. package/filters/bots.d.ts +2 -4
  46. package/filters/bots.js +89 -0
  47. package/filters/bots.test.d.cts +1 -0
  48. package/filters/bundle.cjs +79 -0
  49. package/filters/bundle.d.cts +10 -0
  50. package/filters/bundle.js +74 -0
  51. package/filters/chat.cjs +43 -0
  52. package/filters/chat.d.cts +29 -0
  53. package/filters/chat.d.ts +8 -6
  54. package/filters/chat.js +38 -0
  55. package/filters/group.cjs +49 -0
  56. package/filters/group.d.cts +26 -0
  57. package/filters/group.js +44 -0
  58. package/filters/index.d.cts +4 -0
  59. package/filters/logic.cjs +57 -0
  60. package/filters/logic.d.cts +29 -0
  61. package/filters/logic.js +52 -0
  62. package/filters/logic.test.d.cts +1 -0
  63. package/filters/message.cjs +130 -0
  64. package/filters/message.d.cts +223 -0
  65. package/filters/message.d.ts +5 -1
  66. package/filters/message.js +125 -0
  67. package/filters/state.cjs +21 -0
  68. package/filters/state.d.cts +15 -0
  69. package/filters/state.js +16 -0
  70. package/filters/text.cjs +87 -0
  71. package/filters/text.d.cts +64 -0
  72. package/filters/text.d.ts +2 -2
  73. package/filters/text.js +82 -0
  74. package/filters/types.d.cts +91 -0
  75. package/filters/updates.cjs +27 -0
  76. package/filters/updates.d.cts +39 -0
  77. package/filters/updates.js +22 -0
  78. package/filters/user.cjs +57 -0
  79. package/filters/user.d.cts +24 -0
  80. package/filters/user.js +52 -0
  81. package/handler.d.cts +41 -0
  82. package/handler.d.ts +1 -1
  83. package/index.cjs +37 -2528
  84. package/index.js +16 -2507
  85. package/package.json +10 -9
  86. package/propagation.cjs +15 -0
  87. package/propagation.d.cts +22 -0
  88. package/propagation.js +10 -0
  89. package/state/index.d.cts +5 -0
  90. package/state/key.cjs +32 -0
  91. package/state/key.d.cts +24 -0
  92. package/state/key.js +27 -0
  93. package/state/provider.d.cts +5 -0
  94. package/state/providers/index.d.cts +2 -0
  95. package/state/providers/memory.cjs +79 -0
  96. package/state/providers/memory.d.cts +29 -0
  97. package/state/providers/memory.js +74 -0
  98. package/state/providers/sqlite.cjs +99 -0
  99. package/state/providers/sqlite.d.cts +28 -0
  100. package/state/providers/sqlite.js +94 -0
  101. package/state/repository.d.cts +62 -0
  102. package/state/service.cjs +69 -0
  103. package/state/service.d.cts +20 -0
  104. package/state/service.js +64 -0
  105. package/state/update-state.cjs +206 -0
  106. package/state/update-state.d.cts +151 -0
  107. package/state/update-state.d.ts +1 -1
  108. package/state/update-state.js +201 -0
  109. package/wizard.cjs +90 -0
  110. package/wizard.d.cts +64 -0
  111. package/wizard.js +85 -0
@@ -0,0 +1,21 @@
1
+ if (typeof globalThis !== "undefined" && !globalThis._MTCUTE_CJS_DEPRECATION_WARNED) {
2
+ globalThis._MTCUTE_CJS_DEPRECATION_WARNED = true;
3
+ console.warn("[mtcute-workspace] CommonJS support is deprecated and will be removed in 0.20.0. Please consider switching to ESM, it's " + (/* @__PURE__ */ new Date()).getFullYear() + " already.");
4
+ console.warn("[mtcute-workspace] 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 stateEmpty = async (upd, state2) => {
9
+ if (!state2) return false;
10
+ return !await state2.get();
11
+ };
12
+ function state(predicate) {
13
+ return async (upd, state2) => {
14
+ if (!state2) return false;
15
+ const data = await state2.get();
16
+ if (!data) return false;
17
+ return predicate(data);
18
+ };
19
+ }
20
+ exports.state = state;
21
+ exports.stateEmpty = stateEmpty;
@@ -0,0 +1,15 @@
1
+ import { MaybePromise } from '@mtcute/core';
2
+ import { UpdateFilter } from './types.js';
3
+ /**
4
+ * Create a filter for the cases when the state is empty
5
+ */
6
+ export declare const stateEmpty: UpdateFilter<any>;
7
+ /**
8
+ * Create a filter based on state predicate
9
+ *
10
+ * If state exists and matches `predicate`, update passes
11
+ * this filter, otherwise it doesn't
12
+ *
13
+ * @param predicate State predicate
14
+ */
15
+ export declare function state<T extends object>(predicate: (state: T) => MaybePromise<boolean>): UpdateFilter<any, {}, T>;
@@ -0,0 +1,16 @@
1
+ const stateEmpty = async (upd, state2) => {
2
+ if (!state2) return false;
3
+ return !await state2.get();
4
+ };
5
+ function state(predicate) {
6
+ return async (upd, state2) => {
7
+ if (!state2) return false;
8
+ const data = await state2.get();
9
+ if (!data) return false;
10
+ return predicate(data);
11
+ };
12
+ }
13
+ export {
14
+ state,
15
+ stateEmpty
16
+ };
@@ -0,0 +1,87 @@
1
+ if (typeof globalThis !== "undefined" && !globalThis._MTCUTE_CJS_DEPRECATION_WARNED) {
2
+ globalThis._MTCUTE_CJS_DEPRECATION_WARNED = true;
3
+ console.warn("[mtcute-workspace] CommonJS support is deprecated and will be removed in 0.20.0. Please consider switching to ESM, it's " + (/* @__PURE__ */ new Date()).getFullYear() + " already.");
4
+ console.warn("[mtcute-workspace] 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
+ function extractText(obj) {
10
+ if (obj instanceof core.Message || obj instanceof core.BusinessMessage) {
11
+ return obj.text;
12
+ }
13
+ switch (obj._name) {
14
+ case "inline_query":
15
+ return obj.query;
16
+ case "chosen_inline_result":
17
+ return obj.id;
18
+ case "callback_query":
19
+ case "inline_callback_query":
20
+ case "business_callback_query":
21
+ if (obj.raw.data) return obj.dataStr;
22
+ }
23
+ return null;
24
+ }
25
+ function regex(regex2) {
26
+ return (obj) => {
27
+ const txt = extractText(obj);
28
+ if (!txt) return false;
29
+ const m = txt.match(regex2);
30
+ if (m) {
31
+ obj.match = m;
32
+ return true;
33
+ }
34
+ return false;
35
+ };
36
+ }
37
+ function equals(str, ignoreCase = false) {
38
+ if (ignoreCase) {
39
+ str = str.toLowerCase();
40
+ return (obj) => extractText(obj)?.toLowerCase() === str;
41
+ }
42
+ return (obj) => extractText(obj) === str;
43
+ }
44
+ function contains(str, ignoreCase = false) {
45
+ if (ignoreCase) {
46
+ str = str.toLowerCase();
47
+ return (obj) => {
48
+ const txt = extractText(obj);
49
+ return txt != null && txt.toLowerCase().includes(str);
50
+ };
51
+ }
52
+ return (obj) => {
53
+ const txt = extractText(obj);
54
+ return txt != null && txt.includes(str);
55
+ };
56
+ }
57
+ function startsWith(str, ignoreCase = false) {
58
+ if (ignoreCase) {
59
+ str = str.toLowerCase();
60
+ return (obj) => {
61
+ const txt = extractText(obj);
62
+ return txt != null && txt.toLowerCase().substring(0, str.length) === str;
63
+ };
64
+ }
65
+ return (obj) => {
66
+ const txt = extractText(obj);
67
+ return txt != null && txt.substring(0, str.length) === str;
68
+ };
69
+ }
70
+ function endsWith(str, ignoreCase = false) {
71
+ if (ignoreCase) {
72
+ str = str.toLowerCase();
73
+ return (obj) => {
74
+ const txt = extractText(obj);
75
+ return txt != null && txt.toLowerCase().substring(0, str.length) === str;
76
+ };
77
+ }
78
+ return (obj) => {
79
+ const txt = extractText(obj);
80
+ return txt != null && txt.substring(0, str.length) === str;
81
+ };
82
+ }
83
+ exports.contains = contains;
84
+ exports.endsWith = endsWith;
85
+ exports.equals = equals;
86
+ exports.regex = regex;
87
+ exports.startsWith = startsWith;
@@ -0,0 +1,64 @@
1
+ import { BusinessCallbackQuery, CallbackQuery, ChosenInlineResult, InlineCallbackQuery, InlineQuery, BusinessMessage, Message } from '@mtcute/core';
2
+ import { UpdateContextDistributed } from '../context/base.js';
3
+ import { UpdateFilter } from './types.js';
4
+ type UpdatesWithText = Message | BusinessMessage | UpdateContextDistributed<InlineQuery | ChosenInlineResult | CallbackQuery | InlineCallbackQuery | BusinessCallbackQuery>;
5
+ /**
6
+ * Filter objects that match a given regular expression
7
+ * - for `Message`, `Message.text` is used
8
+ * - for `InlineQuery`, `InlineQuery.query` is used
9
+ * - for {@link ChosenInlineResult}, {@link ChosenInlineResult#id} is used
10
+ * - for callback queries, `dataStr` is used
11
+ *
12
+ * When a regex matches, the match array is stored in a
13
+ * type-safe extension field `.match` of the object
14
+ *
15
+ * @param regex Regex to be matched
16
+ */
17
+ export declare function regex(regex: RegExp): UpdateFilter<UpdatesWithText, {
18
+ match: RegExpMatchArray;
19
+ }>;
20
+ /**
21
+ * Filter objects which contain the exact text given
22
+ * - for `Message`, `Message.text` is used
23
+ * - for `InlineQuery`, `InlineQuery.query` is used
24
+ * - for {@link ChosenInlineResult}, {@link ChosenInlineResult.id} is used
25
+ * - for callback queries, `dataStr` is used
26
+ *
27
+ * @param str String to be matched
28
+ * @param ignoreCase Whether string case should be ignored
29
+ */
30
+ export declare function equals(str: string, ignoreCase?: boolean): UpdateFilter<UpdatesWithText>;
31
+ /**
32
+ * Filter objects which contain the text given (as a substring)
33
+ * - for `Message`, `Message.text` is used
34
+ * - for `InlineQuery`, `InlineQuery.query` is used
35
+ * - for {@link ChosenInlineResult}, {@link ChosenInlineResult.id} is used
36
+ * - for callback queries, `dataStr` is used
37
+ *
38
+ * @param str Substring to be matched
39
+ * @param ignoreCase Whether string case should be ignored
40
+ */
41
+ export declare function contains(str: string, ignoreCase?: boolean): UpdateFilter<UpdatesWithText>;
42
+ /**
43
+ * Filter objects which contain the text starting with a given string
44
+ * - for `Message`, `Message.text` is used
45
+ * - for `InlineQuery`, `InlineQuery.query` is used
46
+ * - for {@link ChosenInlineResult}, {@link ChosenInlineResult.id} is used
47
+ * - for callback queries, `dataStr` is used
48
+ *
49
+ * @param str Substring to be matched
50
+ * @param ignoreCase Whether string case should be ignored
51
+ */
52
+ export declare function startsWith(str: string, ignoreCase?: boolean): UpdateFilter<UpdatesWithText>;
53
+ /**
54
+ * Filter objects which contain the text ending with a given string
55
+ * - for `Message`, `Message.text` is used
56
+ * - for `InlineQuery`, `InlineQuery.query` is used
57
+ * - for {@link ChosenInlineResult}, {@link ChosenInlineResult.id} is used
58
+ * - for callback queries, `dataStr` is used
59
+ *
60
+ * @param str Substring to be matched
61
+ * @param ignoreCase Whether string case should be ignored
62
+ */
63
+ export declare function endsWith(str: string, ignoreCase?: boolean): UpdateFilter<UpdatesWithText>;
64
+ export {};
package/filters/text.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { BusinessCallbackQuery, BusinessMessage, CallbackQuery, ChosenInlineResult, InlineCallbackQuery, InlineQuery, Message } from '@mtcute/core';
1
+ import { BusinessCallbackQuery, CallbackQuery, ChosenInlineResult, InlineCallbackQuery, InlineQuery, BusinessMessage, Message } from '@mtcute/core';
2
2
  import { UpdateContextDistributed } from '../context/base.js';
3
3
  import { UpdateFilter } from './types.js';
4
- type UpdatesWithText = UpdateContextDistributed<Message | BusinessMessage | InlineQuery | ChosenInlineResult | CallbackQuery | InlineCallbackQuery | BusinessCallbackQuery>;
4
+ type UpdatesWithText = Message | BusinessMessage | UpdateContextDistributed<InlineQuery | ChosenInlineResult | CallbackQuery | InlineCallbackQuery | BusinessCallbackQuery>;
5
5
  /**
6
6
  * Filter objects that match a given regular expression
7
7
  * - for `Message`, `Message.text` is used
@@ -0,0 +1,82 @@
1
+ import { Message, BusinessMessage } from "@mtcute/core";
2
+ function extractText(obj) {
3
+ if (obj instanceof Message || obj instanceof BusinessMessage) {
4
+ return obj.text;
5
+ }
6
+ switch (obj._name) {
7
+ case "inline_query":
8
+ return obj.query;
9
+ case "chosen_inline_result":
10
+ return obj.id;
11
+ case "callback_query":
12
+ case "inline_callback_query":
13
+ case "business_callback_query":
14
+ if (obj.raw.data) return obj.dataStr;
15
+ }
16
+ return null;
17
+ }
18
+ function regex(regex2) {
19
+ return (obj) => {
20
+ const txt = extractText(obj);
21
+ if (!txt) return false;
22
+ const m = txt.match(regex2);
23
+ if (m) {
24
+ obj.match = m;
25
+ return true;
26
+ }
27
+ return false;
28
+ };
29
+ }
30
+ function equals(str, ignoreCase = false) {
31
+ if (ignoreCase) {
32
+ str = str.toLowerCase();
33
+ return (obj) => extractText(obj)?.toLowerCase() === str;
34
+ }
35
+ return (obj) => extractText(obj) === str;
36
+ }
37
+ function contains(str, ignoreCase = false) {
38
+ if (ignoreCase) {
39
+ str = str.toLowerCase();
40
+ return (obj) => {
41
+ const txt = extractText(obj);
42
+ return txt != null && txt.toLowerCase().includes(str);
43
+ };
44
+ }
45
+ return (obj) => {
46
+ const txt = extractText(obj);
47
+ return txt != null && txt.includes(str);
48
+ };
49
+ }
50
+ function startsWith(str, ignoreCase = false) {
51
+ if (ignoreCase) {
52
+ str = str.toLowerCase();
53
+ return (obj) => {
54
+ const txt = extractText(obj);
55
+ return txt != null && txt.toLowerCase().substring(0, str.length) === str;
56
+ };
57
+ }
58
+ return (obj) => {
59
+ const txt = extractText(obj);
60
+ return txt != null && txt.substring(0, str.length) === str;
61
+ };
62
+ }
63
+ function endsWith(str, ignoreCase = false) {
64
+ if (ignoreCase) {
65
+ str = str.toLowerCase();
66
+ return (obj) => {
67
+ const txt = extractText(obj);
68
+ return txt != null && txt.toLowerCase().substring(0, str.length) === str;
69
+ };
70
+ }
71
+ return (obj) => {
72
+ const txt = extractText(obj);
73
+ return txt != null && txt.substring(0, str.length) === str;
74
+ };
75
+ }
76
+ export {
77
+ contains,
78
+ endsWith,
79
+ equals,
80
+ regex,
81
+ startsWith
82
+ };
@@ -0,0 +1,91 @@
1
+ import { MaybePromise } from '@mtcute/core';
2
+ import { UpdateState } from '../state/update-state.js';
3
+ /**
4
+ * Type describing a primitive filter, which is a function taking some `Base`
5
+ * and a {@link TelegramClient}, checking it against some condition
6
+ * and returning a boolean.
7
+ *
8
+ * If `true` is returned, the filter is considered
9
+ * to be matched, and the appropriate update handler function is called,
10
+ * otherwise next registered handler is checked.
11
+ *
12
+ * Additionally, filter might contain a type modification
13
+ * to `Base` for better code insights. If it is present,
14
+ * it is used to overwrite types (!) of some of the `Base` fields
15
+ * to given (note that this is entirely compile-time! object is not modified)
16
+ *
17
+ * For parametrized filters (like {@link filters.regex}),
18
+ * type modification can also be used to add additional fields
19
+ * (in case of `regex`, its match array is added to `.match`)
20
+ *
21
+ * Example without type mod:
22
+ * ```typescript
23
+ *
24
+ * const hasPhoto: UpdateFilter<Message> = msg => msg.media?.type === 'photo'
25
+ *
26
+ * // ..later..
27
+ * tg.onNewMessage(hasPhoto, async (msg) => {
28
+ * // `hasPhoto` filter matched, so we can safely assume
29
+ * // that `msg.media` is a Photo.
30
+ * //
31
+ * // but it is very redundant, verbose and error-rome,
32
+ * // wonder if we could make typescript do this automagically and safely...
33
+ * await (msg.media as Photo).downloadToFile(`${msg.id}.jpg`)
34
+ * })
35
+ * ```
36
+ *
37
+ * Example with type mod:
38
+ * ```typescript
39
+ *
40
+ * const hasPhoto: UpdateFilter<Message, { media: Photo }> = msg => msg.media?.type === 'photo'
41
+ *
42
+ * // ..later..
43
+ * tg.onNewMessage(hasPhoto, async (msg) => {
44
+ * // since `hasPhoto` filter matched,
45
+ * // we have applied the modification to `msg`,
46
+ * // and `msg.media` now has type `Photo`
47
+ * //
48
+ * // no more redundancy and type casts!
49
+ * await msg.media.downloadToFile(`${msg.id}.jpg`)
50
+ * })
51
+ * ```
52
+ *
53
+ * > **Note**: Type modification can contain anything, even totally unrelated types
54
+ * > and it is *your* task to keep track that everything is correct.
55
+ * >
56
+ * > Bad example:
57
+ * > ```typescript
58
+ * > // we check for `Photo`, but type contains `Audio`. this will be a problem!
59
+ * > const hasPhoto: UpdateFilter<Message, { media: Audio }> = msg => msg.media?.type === 'photo'
60
+ * >
61
+ * > // ..later..
62
+ * > tg.onNewMessage(hasPhoto, async (msg) => {
63
+ * > // oops! `msg.media` is `Audio` and does not have `.width`!
64
+ * > console.log(msg.media.width)
65
+ * > })
66
+ * > ```
67
+ *
68
+ * > **Warning!** Do not use the generics provided in functions
69
+ * > like `and`, `or`, etc. Those are meant to be inferred by the compiler!
70
+ */
71
+ export type UpdateFilter<Base, Mod = {}, State extends object = never> = (update: Base, state?: UpdateState<State>) => MaybePromise<boolean>;
72
+ export type Modify<Base, Mod> = Omit<Base, keyof Mod> & Mod;
73
+ export type Invert<Base, Mod> = {
74
+ [P in keyof Mod & keyof Base]: Exclude<Base[P], Mod[P]>;
75
+ };
76
+ export type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
77
+ export type ExtractBase<Filter> = Filter extends UpdateFilter<infer I, any> ? I : never;
78
+ export type ExtractMod<Filter> = Filter extends UpdateFilter<any, infer I> ? I : never;
79
+ export type ExtractState<Filter> = Filter extends UpdateFilter<any, any, infer I> ? I : never;
80
+ export type TupleKeys<T extends any[]> = Exclude<keyof T, keyof []>;
81
+ export type WrapBase<T extends any[]> = {
82
+ [K in TupleKeys<T>]: {
83
+ base: ExtractBase<T[K]>;
84
+ };
85
+ };
86
+ export type Values<T> = T[keyof T];
87
+ export type UnwrapBase<T> = T extends {
88
+ base: any;
89
+ } ? T['base'] : never;
90
+ export type ExtractBaseMany<Filters extends any[]> = UnwrapBase<UnionToIntersection<Values<WrapBase<Filters>>>>;
91
+ export type EmptyObject = Record<never, never>;
@@ -0,0 +1,27 @@
1
+ if (typeof globalThis !== "undefined" && !globalThis._MTCUTE_CJS_DEPRECATION_WARNED) {
2
+ globalThis._MTCUTE_CJS_DEPRECATION_WARNED = true;
3
+ console.warn("[mtcute-workspace] CommonJS support is deprecated and will be removed in 0.20.0. Please consider switching to ESM, it's " + (/* @__PURE__ */ new Date()).getFullYear() + " already.");
4
+ console.warn("[mtcute-workspace] 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 chatMember = (types) => {
9
+ if (Array.isArray(types)) {
10
+ const index = {};
11
+ types.forEach((typ) => index[typ] = true);
12
+ return (upd) => upd.type in index;
13
+ }
14
+ return (upd) => upd.type === types;
15
+ };
16
+ const userStatus = (statuses) => {
17
+ if (Array.isArray(statuses)) {
18
+ const index = {};
19
+ statuses.forEach((typ) => index[typ] = true);
20
+ return (upd) => upd.status in index;
21
+ }
22
+ return (upd) => upd.status === statuses;
23
+ };
24
+ const chatMemberSelf = (upd) => upd.isSelf;
25
+ exports.chatMember = chatMember;
26
+ exports.chatMemberSelf = chatMemberSelf;
27
+ exports.userStatus = userStatus;
@@ -0,0 +1,39 @@
1
+ import { ChatMemberUpdate, ChatMemberUpdateType, UserStatus, UserStatusUpdate } from '@mtcute/core';
2
+ import { UpdateFilter } from './types.js';
3
+ /**
4
+ * Create a filter for {@link ChatMemberUpdate} by update type
5
+ *
6
+ * @param types Update type(s)
7
+ * @link ChatMemberUpdate.Type
8
+ */
9
+ export declare const chatMember: {
10
+ <T extends ChatMemberUpdateType>(type: T): UpdateFilter<ChatMemberUpdate, {
11
+ type: T;
12
+ }>;
13
+ <T extends ChatMemberUpdateType[]>(types: T): UpdateFilter<ChatMemberUpdate, {
14
+ type: T[number];
15
+ }>;
16
+ };
17
+ /**
18
+ * Create a filter for {@link UserStatusUpdate} by new user status
19
+ *
20
+ * @param statuses Update type(s)
21
+ * @link User.Status
22
+ */
23
+ export declare const userStatus: {
24
+ <T extends UserStatus>(status: T): UpdateFilter<UserStatusUpdate, {
25
+ type: T;
26
+ lastOnline: T extends 'offline' ? Date : null;
27
+ nextOffline: T extends 'online' ? Date : null;
28
+ }>;
29
+ <T extends UserStatus[]>(statuses: T): UpdateFilter<UserStatusUpdate, {
30
+ type: T[number];
31
+ }>;
32
+ };
33
+ /**
34
+ * Create a filter for {@link ChatMemberUpdate} for updates
35
+ * regarding current user
36
+ */
37
+ export declare const chatMemberSelf: UpdateFilter<ChatMemberUpdate, {
38
+ isSelf: true;
39
+ }>;
@@ -0,0 +1,22 @@
1
+ const chatMember = (types) => {
2
+ if (Array.isArray(types)) {
3
+ const index = {};
4
+ types.forEach((typ) => index[typ] = true);
5
+ return (upd) => upd.type in index;
6
+ }
7
+ return (upd) => upd.type === types;
8
+ };
9
+ const userStatus = (statuses) => {
10
+ if (Array.isArray(statuses)) {
11
+ const index = {};
12
+ statuses.forEach((typ) => index[typ] = true);
13
+ return (upd) => upd.status in index;
14
+ }
15
+ return (upd) => upd.status === statuses;
16
+ };
17
+ const chatMemberSelf = (upd) => upd.isSelf;
18
+ export {
19
+ chatMember,
20
+ chatMemberSelf,
21
+ userStatus
22
+ };
@@ -0,0 +1,57 @@
1
+ if (typeof globalThis !== "undefined" && !globalThis._MTCUTE_CJS_DEPRECATION_WARNED) {
2
+ globalThis._MTCUTE_CJS_DEPRECATION_WARNED = true;
3
+ console.warn("[mtcute-workspace] CommonJS support is deprecated and will be removed in 0.20.0. Please consider switching to ESM, it's " + (/* @__PURE__ */ new Date()).getFullYear() + " already.");
4
+ console.warn("[mtcute-workspace] 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 me = (msg) => msg.sender.type === "user" && msg.sender.isSelf || msg.isOutgoing;
10
+ const bot = (msg) => msg.sender.constructor === core.User && msg.sender.isBot;
11
+ const userId = (id) => {
12
+ const indexId = /* @__PURE__ */ new Set();
13
+ const indexUsername = /* @__PURE__ */ new Set();
14
+ let matchSelf = false;
15
+ if (!Array.isArray(id)) id = [id];
16
+ id.forEach((id2) => {
17
+ if (id2 === "me" || id2 === "self") {
18
+ matchSelf = true;
19
+ } else if (typeof id2 === "string") {
20
+ indexUsername.add(id2);
21
+ } else {
22
+ indexId.add(id2);
23
+ }
24
+ });
25
+ return (upd) => {
26
+ switch (upd._name) {
27
+ case "new_message":
28
+ case "edit_message":
29
+ case "new_business_message":
30
+ case "edit_business_message": {
31
+ const sender = upd.sender;
32
+ return matchSelf && sender.type === "user" && sender.isSelf || indexId.has(sender.id) || indexUsername.has(sender.username);
33
+ }
34
+ case "user_status":
35
+ case "user_typing": {
36
+ const id2 = upd.userId;
37
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
38
+ }
39
+ case "poll_vote":
40
+ case "story":
41
+ case "delete_story": {
42
+ const peer = upd.peer;
43
+ if (peer.type !== "user") return false;
44
+ return matchSelf && peer.isSelf || indexId.has(peer.id) || Boolean(peer.usernames?.some((u) => indexUsername.has(u.username)));
45
+ }
46
+ case "history_read": {
47
+ const id2 = upd.chatId;
48
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
49
+ }
50
+ }
51
+ const user = upd.user;
52
+ return matchSelf && user.isSelf || indexId.has(user.id) || Boolean(user.usernames?.some((u) => indexUsername.has(u.username)));
53
+ };
54
+ };
55
+ exports.bot = bot;
56
+ exports.me = me;
57
+ exports.userId = userId;
@@ -0,0 +1,24 @@
1
+ import { BotChatJoinRequestUpdate, BusinessCallbackQuery, BusinessMessage, CallbackQuery, ChatMemberUpdate, ChosenInlineResult, DeleteStoryUpdate, HistoryReadUpdate, InlineCallbackQuery, InlineQuery, MaybeArray, Message, PollVoteUpdate, StoryUpdate, UserStatusUpdate, UserTypingUpdate, User } from '@mtcute/core';
2
+ import { UpdateContextDistributed } from '../context/base.js';
3
+ import { UpdateFilter } from './types.js';
4
+ /**
5
+ * Filter messages generated by yourself (including Saved Messages)
6
+ */
7
+ export declare const me: UpdateFilter<Message, {
8
+ sender: User;
9
+ }>;
10
+ /**
11
+ * Filter messages sent by bots
12
+ */
13
+ export declare const bot: UpdateFilter<Message, {
14
+ sender: User;
15
+ }>;
16
+ /**
17
+ * Filter updates by user ID(s) or username(s)
18
+ *
19
+ * Note that only some updates support filtering by username.
20
+ */
21
+ export declare const userId: {
22
+ (id: MaybeArray<number>): UpdateFilter<UpdateContextDistributed<Message | BusinessMessage | StoryUpdate | DeleteStoryUpdate | InlineQuery | ChatMemberUpdate | ChosenInlineResult | CallbackQuery | InlineCallbackQuery | BusinessCallbackQuery | PollVoteUpdate | BotChatJoinRequestUpdate>>;
23
+ (id: MaybeArray<number | string>): UpdateFilter<UpdateContextDistributed<Message | BusinessMessage | UserStatusUpdate | UserTypingUpdate | StoryUpdate | HistoryReadUpdate | DeleteStoryUpdate | InlineQuery | ChatMemberUpdate | ChosenInlineResult | CallbackQuery | InlineCallbackQuery | BusinessCallbackQuery | PollVoteUpdate | BotChatJoinRequestUpdate>>;
24
+ };
@@ -0,0 +1,52 @@
1
+ import { User } from "@mtcute/core";
2
+ const me = (msg) => msg.sender.type === "user" && msg.sender.isSelf || msg.isOutgoing;
3
+ const bot = (msg) => msg.sender.constructor === User && msg.sender.isBot;
4
+ const userId = (id) => {
5
+ const indexId = /* @__PURE__ */ new Set();
6
+ const indexUsername = /* @__PURE__ */ new Set();
7
+ let matchSelf = false;
8
+ if (!Array.isArray(id)) id = [id];
9
+ id.forEach((id2) => {
10
+ if (id2 === "me" || id2 === "self") {
11
+ matchSelf = true;
12
+ } else if (typeof id2 === "string") {
13
+ indexUsername.add(id2);
14
+ } else {
15
+ indexId.add(id2);
16
+ }
17
+ });
18
+ return (upd) => {
19
+ switch (upd._name) {
20
+ case "new_message":
21
+ case "edit_message":
22
+ case "new_business_message":
23
+ case "edit_business_message": {
24
+ const sender = upd.sender;
25
+ return matchSelf && sender.type === "user" && sender.isSelf || indexId.has(sender.id) || indexUsername.has(sender.username);
26
+ }
27
+ case "user_status":
28
+ case "user_typing": {
29
+ const id2 = upd.userId;
30
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
31
+ }
32
+ case "poll_vote":
33
+ case "story":
34
+ case "delete_story": {
35
+ const peer = upd.peer;
36
+ if (peer.type !== "user") return false;
37
+ return matchSelf && peer.isSelf || indexId.has(peer.id) || Boolean(peer.usernames?.some((u) => indexUsername.has(u.username)));
38
+ }
39
+ case "history_read": {
40
+ const id2 = upd.chatId;
41
+ return matchSelf && id2 === upd.client.storage.self.getCached()?.userId || indexId.has(id2);
42
+ }
43
+ }
44
+ const user = upd.user;
45
+ return matchSelf && user.isSelf || indexId.has(user.id) || Boolean(user.usernames?.some((u) => indexUsername.has(u.username)));
46
+ };
47
+ };
48
+ export {
49
+ bot,
50
+ me,
51
+ userId
52
+ };
package/handler.d.cts ADDED
@@ -0,0 +1,41 @@
1
+ import { BotReactionCountUpdate, BotReactionUpdate, BotStoppedUpdate, BusinessConnection, ChatJoinRequestUpdate, ChatMemberUpdate, DeleteBusinessMessageUpdate, DeleteMessageUpdate, DeleteStoryUpdate, HistoryReadUpdate, MaybePromise, PeersIndex, PollUpdate, PollVoteUpdate, StoryUpdate, tl, UserStatusUpdate, UserTypingUpdate } from '@mtcute/core';
2
+ import { TelegramClient } from '@mtcute/core/client.js';
3
+ import { UpdateContext } from './context/base.js';
4
+ import { BusinessCallbackQueryContext, BusinessMessageContext, CallbackQueryContext, ChatJoinRequestUpdateContext, ChosenInlineResultContext, InlineCallbackQueryContext, InlineQueryContext, MessageContext, PreCheckoutQueryContext } from './context/index.js';
5
+ import { PropagationAction } from './propagation.js';
6
+ export interface BaseUpdateHandler<Name, Handler, Checker> {
7
+ name: Name;
8
+ callback: Handler;
9
+ check?: Checker;
10
+ }
11
+ export type ParsedUpdateHandler<Name, Update, State = never> = BaseUpdateHandler<Name, (update: Update, state: State) => MaybePromise<void | PropagationAction>, (update: Update, state: State) => MaybePromise<boolean>>;
12
+ export type RawUpdateHandler = BaseUpdateHandler<'raw', (client: TelegramClient, update: tl.TypeUpdate | tl.TypeMessage, peers: PeersIndex) => MaybePromise<void | PropagationAction>, (client: TelegramClient, update: tl.TypeUpdate | tl.TypeMessage, peers: PeersIndex) => MaybePromise<boolean>>;
13
+ export type NewMessageHandler<T = MessageContext, S = never> = ParsedUpdateHandler<'new_message', T, S>;
14
+ export type EditMessageHandler<T = MessageContext, S = never> = ParsedUpdateHandler<'edit_message', T, S>;
15
+ export type MessageGroupHandler<T = MessageContext, S = never> = ParsedUpdateHandler<'message_group', T, S>;
16
+ export type DeleteMessageHandler<T = UpdateContext<DeleteMessageUpdate>> = ParsedUpdateHandler<'delete_message', T>;
17
+ export type ChatMemberUpdateHandler<T = UpdateContext<ChatMemberUpdate>> = ParsedUpdateHandler<'chat_member', T>;
18
+ export type InlineQueryHandler<T = InlineQueryContext> = ParsedUpdateHandler<'inline_query', T>;
19
+ export type ChosenInlineResultHandler<T = ChosenInlineResultContext> = ParsedUpdateHandler<'chosen_inline_result', T>;
20
+ export type CallbackQueryHandler<T = CallbackQueryContext, S = never> = ParsedUpdateHandler<'callback_query', T, S>;
21
+ export type InlineCallbackQueryHandler<T = InlineCallbackQueryContext, S = never> = ParsedUpdateHandler<'inline_callback_query', T, S>;
22
+ export type BusinessCallbackQueryHandler<T = BusinessCallbackQueryContext, S = never> = ParsedUpdateHandler<'business_callback_query', T, S>;
23
+ export type PollUpdateHandler<T = UpdateContext<PollUpdate>> = ParsedUpdateHandler<'poll', T>;
24
+ export type PollVoteHandler<T = UpdateContext<PollVoteUpdate>> = ParsedUpdateHandler<'poll_vote', T>;
25
+ export type UserStatusUpdateHandler<T = UpdateContext<UserStatusUpdate>> = ParsedUpdateHandler<'user_status', T>;
26
+ export type UserTypingHandler<T = UpdateContext<UserTypingUpdate>> = ParsedUpdateHandler<'user_typing', T>;
27
+ export type HistoryReadHandler<T = UpdateContext<HistoryReadUpdate>> = ParsedUpdateHandler<'history_read', T>;
28
+ export type BotStoppedHandler<T = UpdateContext<BotStoppedUpdate>> = ParsedUpdateHandler<'bot_stopped', T>;
29
+ export type BotChatJoinRequestHandler<T = ChatJoinRequestUpdateContext> = ParsedUpdateHandler<'bot_chat_join_request', T>;
30
+ export type ChatJoinRequestHandler<T = UpdateContext<ChatJoinRequestUpdate>> = ParsedUpdateHandler<'chat_join_request', T>;
31
+ export type PreCheckoutQueryHandler<T = PreCheckoutQueryContext> = ParsedUpdateHandler<'pre_checkout_query', T>;
32
+ export type StoryUpdateHandler<T = UpdateContext<StoryUpdate>> = ParsedUpdateHandler<'story', T>;
33
+ export type DeleteStoryHandler<T = UpdateContext<DeleteStoryUpdate>> = ParsedUpdateHandler<'delete_story', T>;
34
+ export type BotReactionUpdateHandler<T = UpdateContext<BotReactionUpdate>> = ParsedUpdateHandler<'bot_reaction', T>;
35
+ export type BotReactionCountUpdateHandler<T = UpdateContext<BotReactionCountUpdate>> = ParsedUpdateHandler<'bot_reaction_count', T>;
36
+ export type BusinessConnectionUpdateHandler<T = UpdateContext<BusinessConnection>> = ParsedUpdateHandler<'business_connection', T>;
37
+ export type NewBusinessMessageHandler<T = BusinessMessageContext, S = never> = ParsedUpdateHandler<'new_business_message', T, S>;
38
+ export type EditBusinessMessageHandler<T = BusinessMessageContext, S = never> = ParsedUpdateHandler<'edit_business_message', T, S>;
39
+ export type BusinessMessageGroupHandler<T = BusinessMessageContext, S = never> = ParsedUpdateHandler<'business_message_group', T, S>;
40
+ export type DeleteBusinessMessageHandler<T = UpdateContext<DeleteBusinessMessageUpdate>> = ParsedUpdateHandler<'delete_business_message', T>;
41
+ export type UpdateHandler = RawUpdateHandler | NewMessageHandler | EditMessageHandler | MessageGroupHandler | DeleteMessageHandler | ChatMemberUpdateHandler | InlineQueryHandler | ChosenInlineResultHandler | CallbackQueryHandler | InlineCallbackQueryHandler | BusinessCallbackQueryHandler | PollUpdateHandler | PollVoteHandler | UserStatusUpdateHandler | UserTypingHandler | HistoryReadHandler | BotStoppedHandler | BotChatJoinRequestHandler | ChatJoinRequestHandler | PreCheckoutQueryHandler | StoryUpdateHandler | DeleteStoryHandler | BotReactionUpdateHandler | BotReactionCountUpdateHandler | BusinessConnectionUpdateHandler | NewBusinessMessageHandler | EditBusinessMessageHandler | BusinessMessageGroupHandler | DeleteBusinessMessageHandler;