telegrinder 0.3.4__py3-none-any.whl → 0.4.0__py3-none-any.whl

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.

Potentially problematic release.


This version of telegrinder might be problematic. Click here for more details.

Files changed (192) hide show
  1. telegrinder/__init__.py +148 -149
  2. telegrinder/api/__init__.py +9 -8
  3. telegrinder/api/api.py +101 -93
  4. telegrinder/api/error.py +20 -16
  5. telegrinder/api/response.py +20 -20
  6. telegrinder/api/token.py +36 -36
  7. telegrinder/bot/__init__.py +72 -66
  8. telegrinder/bot/bot.py +83 -76
  9. telegrinder/bot/cute_types/__init__.py +19 -17
  10. telegrinder/bot/cute_types/base.py +184 -258
  11. telegrinder/bot/cute_types/callback_query.py +400 -385
  12. telegrinder/bot/cute_types/chat_join_request.py +62 -61
  13. telegrinder/bot/cute_types/chat_member_updated.py +157 -160
  14. telegrinder/bot/cute_types/inline_query.py +44 -43
  15. telegrinder/bot/cute_types/message.py +2590 -2637
  16. telegrinder/bot/cute_types/pre_checkout_query.py +42 -0
  17. telegrinder/bot/cute_types/update.py +112 -104
  18. telegrinder/bot/cute_types/utils.py +62 -95
  19. telegrinder/bot/dispatch/__init__.py +59 -55
  20. telegrinder/bot/dispatch/abc.py +76 -77
  21. telegrinder/bot/dispatch/context.py +96 -98
  22. telegrinder/bot/dispatch/dispatch.py +254 -202
  23. telegrinder/bot/dispatch/handler/__init__.py +13 -13
  24. telegrinder/bot/dispatch/handler/abc.py +23 -24
  25. telegrinder/bot/dispatch/handler/audio_reply.py +44 -44
  26. telegrinder/bot/dispatch/handler/base.py +57 -57
  27. telegrinder/bot/dispatch/handler/document_reply.py +44 -44
  28. telegrinder/bot/dispatch/handler/func.py +129 -135
  29. telegrinder/bot/dispatch/handler/media_group_reply.py +44 -43
  30. telegrinder/bot/dispatch/handler/message_reply.py +36 -36
  31. telegrinder/bot/dispatch/handler/photo_reply.py +44 -44
  32. telegrinder/bot/dispatch/handler/sticker_reply.py +37 -37
  33. telegrinder/bot/dispatch/handler/video_reply.py +44 -44
  34. telegrinder/bot/dispatch/middleware/__init__.py +3 -3
  35. telegrinder/bot/dispatch/middleware/abc.py +97 -22
  36. telegrinder/bot/dispatch/middleware/global_middleware.py +70 -0
  37. telegrinder/bot/dispatch/process.py +151 -157
  38. telegrinder/bot/dispatch/return_manager/__init__.py +15 -13
  39. telegrinder/bot/dispatch/return_manager/abc.py +104 -108
  40. telegrinder/bot/dispatch/return_manager/callback_query.py +20 -20
  41. telegrinder/bot/dispatch/return_manager/inline_query.py +15 -15
  42. telegrinder/bot/dispatch/return_manager/message.py +36 -36
  43. telegrinder/bot/dispatch/return_manager/pre_checkout_query.py +20 -0
  44. telegrinder/bot/dispatch/view/__init__.py +15 -13
  45. telegrinder/bot/dispatch/view/abc.py +45 -41
  46. telegrinder/bot/dispatch/view/base.py +231 -200
  47. telegrinder/bot/dispatch/view/box.py +140 -129
  48. telegrinder/bot/dispatch/view/callback_query.py +16 -17
  49. telegrinder/bot/dispatch/view/chat_join_request.py +11 -16
  50. telegrinder/bot/dispatch/view/chat_member.py +37 -39
  51. telegrinder/bot/dispatch/view/inline_query.py +16 -17
  52. telegrinder/bot/dispatch/view/message.py +43 -44
  53. telegrinder/bot/dispatch/view/pre_checkout_query.py +16 -0
  54. telegrinder/bot/dispatch/view/raw.py +116 -114
  55. telegrinder/bot/dispatch/waiter_machine/__init__.py +17 -17
  56. telegrinder/bot/dispatch/waiter_machine/actions.py +14 -13
  57. telegrinder/bot/dispatch/waiter_machine/hasher/__init__.py +8 -8
  58. telegrinder/bot/dispatch/waiter_machine/hasher/callback.py +55 -55
  59. telegrinder/bot/dispatch/waiter_machine/hasher/hasher.py +59 -57
  60. telegrinder/bot/dispatch/waiter_machine/hasher/message.py +51 -51
  61. telegrinder/bot/dispatch/waiter_machine/hasher/state.py +20 -19
  62. telegrinder/bot/dispatch/waiter_machine/machine.py +251 -172
  63. telegrinder/bot/dispatch/waiter_machine/middleware.py +94 -89
  64. telegrinder/bot/dispatch/waiter_machine/short_state.py +57 -68
  65. telegrinder/bot/polling/__init__.py +4 -4
  66. telegrinder/bot/polling/abc.py +25 -25
  67. telegrinder/bot/polling/polling.py +139 -131
  68. telegrinder/bot/rules/__init__.py +85 -62
  69. telegrinder/bot/rules/abc.py +213 -206
  70. telegrinder/bot/rules/callback_data.py +122 -163
  71. telegrinder/bot/rules/chat_join.py +45 -43
  72. telegrinder/bot/rules/command.py +126 -126
  73. telegrinder/bot/rules/enum_text.py +33 -36
  74. telegrinder/bot/rules/func.py +28 -26
  75. telegrinder/bot/rules/fuzzy.py +24 -24
  76. telegrinder/bot/rules/id.py +24 -0
  77. telegrinder/bot/rules/inline.py +58 -56
  78. telegrinder/bot/rules/integer.py +21 -20
  79. telegrinder/bot/rules/is_from.py +127 -127
  80. telegrinder/bot/rules/logic.py +18 -0
  81. telegrinder/bot/rules/markup.py +42 -43
  82. telegrinder/bot/rules/mention.py +14 -14
  83. telegrinder/bot/rules/message.py +15 -17
  84. telegrinder/bot/rules/message_entities.py +33 -35
  85. telegrinder/bot/rules/node.py +33 -27
  86. telegrinder/bot/rules/payload.py +81 -0
  87. telegrinder/bot/rules/payment_invoice.py +29 -0
  88. telegrinder/bot/rules/regex.py +36 -37
  89. telegrinder/bot/rules/rule_enum.py +72 -72
  90. telegrinder/bot/rules/start.py +42 -42
  91. telegrinder/bot/rules/state.py +35 -37
  92. telegrinder/bot/rules/text.py +38 -33
  93. telegrinder/bot/rules/update.py +15 -15
  94. telegrinder/bot/scenario/__init__.py +5 -5
  95. telegrinder/bot/scenario/abc.py +17 -19
  96. telegrinder/bot/scenario/checkbox.py +174 -176
  97. telegrinder/bot/scenario/choice.py +48 -51
  98. telegrinder/client/__init__.py +12 -4
  99. telegrinder/client/abc.py +100 -75
  100. telegrinder/client/aiohttp.py +134 -130
  101. telegrinder/client/form_data.py +31 -0
  102. telegrinder/client/sonic.py +212 -0
  103. telegrinder/model.py +208 -315
  104. telegrinder/modules.py +239 -237
  105. telegrinder/msgspec_json.py +14 -14
  106. telegrinder/msgspec_utils.py +478 -410
  107. telegrinder/node/__init__.py +86 -25
  108. telegrinder/node/attachment.py +163 -87
  109. telegrinder/node/base.py +288 -160
  110. telegrinder/node/callback_query.py +54 -53
  111. telegrinder/node/command.py +34 -33
  112. telegrinder/node/composer.py +163 -198
  113. telegrinder/node/container.py +33 -27
  114. telegrinder/node/either.py +82 -0
  115. telegrinder/node/event.py +54 -65
  116. telegrinder/node/file.py +51 -0
  117. telegrinder/node/me.py +15 -16
  118. telegrinder/node/payload.py +78 -0
  119. telegrinder/node/polymorphic.py +67 -48
  120. telegrinder/node/rule.py +72 -76
  121. telegrinder/node/scope.py +36 -38
  122. telegrinder/node/source.py +87 -71
  123. telegrinder/node/text.py +53 -41
  124. telegrinder/node/tools/__init__.py +3 -3
  125. telegrinder/node/tools/generator.py +36 -40
  126. telegrinder/py.typed +0 -0
  127. telegrinder/rules.py +1 -62
  128. telegrinder/tools/__init__.py +152 -93
  129. telegrinder/tools/adapter/__init__.py +19 -0
  130. telegrinder/tools/adapter/abc.py +49 -0
  131. telegrinder/tools/adapter/dataclass.py +56 -0
  132. telegrinder/{bot/rules → tools}/adapter/errors.py +5 -5
  133. telegrinder/{bot/rules → tools}/adapter/event.py +63 -65
  134. telegrinder/{bot/rules → tools}/adapter/node.py +46 -48
  135. telegrinder/{bot/rules → tools}/adapter/raw_event.py +27 -27
  136. telegrinder/{bot/rules → tools}/adapter/raw_update.py +30 -30
  137. telegrinder/tools/buttons.py +106 -80
  138. telegrinder/tools/callback_data_serilization/__init__.py +5 -0
  139. telegrinder/tools/callback_data_serilization/abc.py +51 -0
  140. telegrinder/tools/callback_data_serilization/json_ser.py +60 -0
  141. telegrinder/tools/callback_data_serilization/msgpack_ser.py +172 -0
  142. telegrinder/tools/error_handler/__init__.py +7 -7
  143. telegrinder/tools/error_handler/abc.py +30 -33
  144. telegrinder/tools/error_handler/error.py +9 -9
  145. telegrinder/tools/error_handler/error_handler.py +179 -193
  146. telegrinder/tools/formatting/__init__.py +83 -63
  147. telegrinder/tools/formatting/deep_links.py +541 -0
  148. telegrinder/tools/formatting/{html.py → html_formatter.py} +266 -294
  149. telegrinder/tools/formatting/spec_html_formats.py +71 -117
  150. telegrinder/tools/functional.py +8 -12
  151. telegrinder/tools/global_context/__init__.py +7 -7
  152. telegrinder/tools/global_context/abc.py +63 -63
  153. telegrinder/tools/global_context/global_context.py +387 -412
  154. telegrinder/tools/global_context/telegrinder_ctx.py +27 -27
  155. telegrinder/tools/i18n/__init__.py +7 -7
  156. telegrinder/tools/i18n/abc.py +30 -30
  157. telegrinder/tools/i18n/middleware/__init__.py +3 -3
  158. telegrinder/tools/i18n/middleware/abc.py +22 -25
  159. telegrinder/tools/i18n/simple.py +43 -43
  160. telegrinder/tools/input_file_directory.py +30 -0
  161. telegrinder/tools/keyboard.py +128 -128
  162. telegrinder/tools/lifespan.py +105 -0
  163. telegrinder/tools/limited_dict.py +32 -37
  164. telegrinder/tools/loop_wrapper/__init__.py +4 -4
  165. telegrinder/tools/loop_wrapper/abc.py +20 -15
  166. telegrinder/tools/loop_wrapper/loop_wrapper.py +169 -224
  167. telegrinder/tools/magic.py +307 -157
  168. telegrinder/tools/parse_mode.py +6 -6
  169. telegrinder/tools/state_storage/__init__.py +4 -4
  170. telegrinder/tools/state_storage/abc.py +31 -35
  171. telegrinder/tools/state_storage/memory.py +25 -25
  172. telegrinder/tools/strings.py +13 -0
  173. telegrinder/types/__init__.py +268 -260
  174. telegrinder/types/enums.py +711 -701
  175. telegrinder/types/input_file.py +51 -0
  176. telegrinder/types/methods.py +5055 -4633
  177. telegrinder/types/objects.py +7058 -6950
  178. telegrinder/verification_utils.py +30 -32
  179. {telegrinder-0.3.4.dist-info → telegrinder-0.4.0.dist-info}/LICENSE +22 -22
  180. telegrinder-0.4.0.dist-info/METADATA +144 -0
  181. telegrinder-0.4.0.dist-info/RECORD +182 -0
  182. {telegrinder-0.3.4.dist-info → telegrinder-0.4.0.dist-info}/WHEEL +1 -1
  183. telegrinder/bot/rules/adapter/__init__.py +0 -17
  184. telegrinder/bot/rules/adapter/abc.py +0 -31
  185. telegrinder/node/message.py +0 -14
  186. telegrinder/node/update.py +0 -15
  187. telegrinder/tools/formatting/links.py +0 -38
  188. telegrinder/tools/kb_set/__init__.py +0 -4
  189. telegrinder/tools/kb_set/base.py +0 -15
  190. telegrinder/tools/kb_set/yaml.py +0 -63
  191. telegrinder-0.3.4.dist-info/METADATA +0 -110
  192. telegrinder-0.3.4.dist-info/RECORD +0 -165
@@ -1,410 +1,478 @@
1
- import dataclasses
2
- import typing
3
- from contextlib import contextmanager
4
-
5
- import fntypes.option
6
- import fntypes.result
7
- import msgspec
8
- from fntypes.co import Error, Ok, Result, Variative
9
-
10
- if typing.TYPE_CHECKING:
11
- from datetime import datetime
12
-
13
- from fntypes.option import Option
14
-
15
- def get_class_annotations(obj: typing.Any) -> dict[str, type[typing.Any]]: ...
16
-
17
- def get_type_hints(obj: typing.Any) -> dict[str, type[typing.Any]]: ...
18
-
19
- else:
20
- from datetime import datetime as dt
21
-
22
- from msgspec._utils import get_class_annotations, get_type_hints
23
-
24
- Value = typing.TypeVar("Value")
25
- Err = typing.TypeVar("Err")
26
-
27
- datetime = type("datetime", (dt,), {})
28
-
29
- class OptionMeta(type):
30
- def __instancecheck__(cls, __instance: typing.Any) -> bool:
31
- return isinstance(__instance, fntypes.option.Some | fntypes.option.Nothing)
32
-
33
- class Option(typing.Generic[Value], metaclass=OptionMeta):
34
- pass
35
-
36
-
37
- T = typing.TypeVar("T")
38
-
39
- DecHook: typing.TypeAlias = typing.Callable[[type[T], typing.Any], typing.Any]
40
- EncHook: typing.TypeAlias = typing.Callable[[T], typing.Any]
41
-
42
- Nothing: typing.Final[fntypes.option.Nothing] = fntypes.option.Nothing()
43
-
44
-
45
- def get_origin(t: type[T]) -> type[T]:
46
- return typing.cast(T, typing.get_origin(t)) or t
47
-
48
-
49
- def repr_type(t: typing.Any) -> str:
50
- return getattr(t, "__name__", repr(get_origin(t)))
51
-
52
-
53
- def is_common_type(type_: typing.Any) -> typing.TypeGuard[type[typing.Any]]:
54
- if not isinstance(type_, type):
55
- return False
56
- return (
57
- type_ in (str, int, float, bool, None, Variative)
58
- or issubclass(type_, msgspec.Struct)
59
- or hasattr(type_, "__dataclass_fields__")
60
- )
61
-
62
-
63
- def type_check(obj: typing.Any, t: typing.Any) -> bool:
64
- return (
65
- isinstance(obj, t)
66
- if isinstance(t, type) and issubclass(t, msgspec.Struct)
67
- else type(obj) in t
68
- if isinstance(t, tuple)
69
- else type(obj) is t
70
- )
71
-
72
-
73
- def msgspec_convert(obj: typing.Any, t: type[T]) -> Result[T, str]:
74
- try:
75
- return Ok(decoder.convert(obj, type=t, strict=True))
76
- except msgspec.ValidationError:
77
- return Error(
78
- "Expected object of type `{}`, got `{}`.".format(
79
- repr_type(t),
80
- repr_type(type(obj)),
81
- )
82
- )
83
-
84
-
85
- def msgspec_to_builtins(
86
- obj: typing.Any,
87
- *,
88
- str_keys: bool = False,
89
- builtin_types: typing.Iterable[type[typing.Any]] | None = None,
90
- order: typing.Literal["deterministic", "sorted"] | None = None,
91
- ) -> fntypes.result.Result[typing.Any, msgspec.ValidationError]:
92
- try:
93
- return Ok(encoder.to_builtins(**locals()))
94
- except msgspec.ValidationError as exc:
95
- return Error(exc)
96
-
97
-
98
- def option_dec_hook(tp: type[Option[typing.Any]], obj: typing.Any) -> Option[typing.Any]:
99
- if obj is None or isinstance(obj, fntypes.Nothing):
100
- return Nothing
101
-
102
- (value_type,) = typing.get_args(tp) or (typing.Any,)
103
- orig_value_type = typing.get_origin(value_type) or value_type
104
- orig_obj = obj
105
-
106
- if not isinstance(orig_obj, dict | list) and is_common_type(orig_value_type):
107
- if orig_value_type is Variative:
108
- obj = value_type(orig_obj) # type: ignore
109
- orig_value_type = typing.get_args(value_type)
110
-
111
- if not type_check(orig_obj, orig_value_type):
112
- raise TypeError(f"Expected `{repr_type(orig_value_type)}`, got `{repr_type(type(orig_obj))}`.")
113
-
114
- return fntypes.option.Some(obj)
115
-
116
- return fntypes.option.Some(decoder.convert(orig_obj, type=value_type))
117
-
118
-
119
- def variative_dec_hook(tp: type[Variative], obj: typing.Any) -> Variative:
120
- union_types = typing.get_args(tp)
121
-
122
- if isinstance(obj, dict):
123
- models_struct_fields: dict[type[msgspec.Struct], int] = {
124
- m: sum(1 for k in obj if k in m.__struct_fields__)
125
- for m in union_types
126
- if issubclass(get_origin(m), msgspec.Struct)
127
- }
128
- union_types = tuple(t for t in union_types if t not in models_struct_fields)
129
- reverse = False
130
-
131
- if len(set(models_struct_fields.values())) != len(models_struct_fields.values()):
132
- models_struct_fields = {m: len(m.__struct_fields__) for m in models_struct_fields}
133
- reverse = True
134
-
135
- union_types = (
136
- *sorted(
137
- models_struct_fields,
138
- key=lambda k: models_struct_fields[k],
139
- reverse=reverse,
140
- ),
141
- *union_types,
142
- )
143
-
144
- for t in union_types:
145
- if not isinstance(obj, dict | list) and is_common_type(t) and type_check(obj, t):
146
- return tp(obj)
147
- match msgspec_convert(obj, t):
148
- case Ok(value):
149
- return tp(value)
150
-
151
- raise TypeError(
152
- "Object of type `{}` does not belong to types `{}`".format(
153
- repr_type(obj.__class__),
154
- " | ".join(map(repr_type, union_types)),
155
- )
156
- )
157
-
158
-
159
- @typing.runtime_checkable
160
- class DataclassInstance(typing.Protocol):
161
- __dataclass_fields__: typing.ClassVar[dict[str, dataclasses.Field[typing.Any]]]
162
-
163
-
164
- class Decoder:
165
- """Class `Decoder` for `msgspec` module with decode hook
166
- for objects with the specified type.
167
-
168
- ```
169
- import enum
170
-
171
- from datetime import datetime as dt
172
-
173
- class Digit(enum.IntEnum):
174
- ONE = 1
175
- TWO = 2
176
- THREE = 3
177
-
178
- decoder = Encoder()
179
- decoder.dec_hooks[dt] = lambda t, timestamp: t.fromtimestamp(timestamp)
180
-
181
- decoder.dec_hook(dt, 1713354732) #> datetime.datetime(2024, 4, 17, 14, 52, 12)
182
-
183
- decoder.convert("123", type=int, strict=False) #> 123
184
- decoder.convert(1, type=Digit) #> <Digit.ONE: 1>
185
-
186
- decoder.decode(b'{"digit":3}', type=dict[str, Digit]) #> {'digit': <Digit.THREE: 3>}
187
- ```
188
- """
189
-
190
- def __init__(self) -> None:
191
- self.dec_hooks: dict[typing.Any, DecHook[typing.Any]] = {
192
- Option: option_dec_hook,
193
- Variative: variative_dec_hook,
194
- datetime: lambda t, obj: t.fromtimestamp(obj),
195
- fntypes.option.Some: option_dec_hook,
196
- fntypes.option.Nothing: option_dec_hook,
197
- }
198
-
199
- def __repr__(self) -> str:
200
- return "<{}: dec_hooks={!r}>".format(
201
- self.__class__.__name__,
202
- self.dec_hooks,
203
- )
204
-
205
- @typing.overload
206
- def __call__(self, type: type[T]) -> typing.ContextManager[msgspec.json.Decoder[T]]: ...
207
-
208
- @typing.overload
209
- def __call__(self, type: typing.Any) -> typing.ContextManager[msgspec.json.Decoder[typing.Any]]: ...
210
-
211
- @typing.overload
212
- def __call__(
213
- self,
214
- type: type[T],
215
- *,
216
- strict: bool = True,
217
- ) -> typing.ContextManager[msgspec.json.Decoder[T]]: ...
218
-
219
- @typing.overload
220
- def __call__(
221
- self,
222
- type: typing.Any,
223
- *,
224
- strict: bool = True,
225
- ) -> typing.ContextManager[msgspec.json.Decoder[typing.Any]]: ...
226
-
227
- @contextmanager
228
- def __call__(self, type=object, *, strict=True):
229
- """Context manager returns the `msgspec.json.Decoder` object with the `dec_hook`."""
230
-
231
- dec_obj = msgspec.json.Decoder(
232
- type=typing.Any if type is object else type,
233
- strict=strict,
234
- dec_hook=self.dec_hook,
235
- )
236
- yield dec_obj
237
-
238
- def add_dec_hook(self, t: type[T]): # type: ignore
239
- def decorator(func: DecHook[T]) -> DecHook[T]:
240
- return self.dec_hooks.setdefault(get_origin(t), func) # type: ignore
241
-
242
- return decorator
243
-
244
- def dec_hook(self, tp: type[typing.Any], obj: object) -> object:
245
- origin_type = t if isinstance((t := get_origin(tp)), type) else type(t)
246
- if origin_type not in self.dec_hooks:
247
- raise TypeError(
248
- f"Unknown type `{repr_type(origin_type)}`. You can implement decode hook for this type."
249
- )
250
- return self.dec_hooks[origin_type](tp, obj)
251
-
252
- def convert(
253
- self,
254
- obj: object,
255
- *,
256
- type: type[T] = dict,
257
- strict: bool = True,
258
- from_attributes: bool = False,
259
- builtin_types: typing.Iterable[type[typing.Any]] | None = None,
260
- str_keys: bool = False,
261
- ) -> T:
262
- return msgspec.convert(
263
- obj,
264
- type,
265
- strict=strict,
266
- from_attributes=from_attributes,
267
- dec_hook=self.dec_hook,
268
- builtin_types=builtin_types,
269
- str_keys=str_keys,
270
- )
271
-
272
- @typing.overload
273
- def decode(self, buf: str | bytes) -> typing.Any: ...
274
-
275
- @typing.overload
276
- def decode(self, buf: str | bytes, *, type: type[T]) -> T: ...
277
-
278
- @typing.overload
279
- def decode(self, buf: str | bytes, *, type: typing.Any) -> typing.Any: ...
280
-
281
- @typing.overload
282
- def decode(
283
- self,
284
- buf: str | bytes,
285
- *,
286
- type: type[T],
287
- strict: bool = True,
288
- ) -> T: ...
289
-
290
- @typing.overload
291
- def decode(
292
- self,
293
- buf: str | bytes,
294
- *,
295
- type: typing.Any,
296
- strict: bool = True,
297
- ) -> typing.Any: ...
298
-
299
- def decode(self, buf, *, type=object, strict=True):
300
- return msgspec.json.decode(
301
- buf,
302
- type=typing.Any if type is object else type,
303
- strict=strict,
304
- dec_hook=self.dec_hook,
305
- )
306
-
307
-
308
- class Encoder:
309
- """Class `Encoder` for `msgspec` module with encode hooks for objects.
310
-
311
- ```
312
- from datetime import datetime as dt
313
-
314
- encoder = Encoder()
315
- encoder.enc_hooks[dt] = lambda d: int(d.timestamp())
316
-
317
- encoder.enc_hook(dt.now()) #> 1713354732
318
- encoder.encode({'digit': Digit.ONE}) #> '{"digit":1}'
319
- ```
320
- """
321
-
322
- def __init__(self) -> None:
323
- self.enc_hooks: dict[typing.Any, EncHook[typing.Any]] = {
324
- fntypes.option.Some: lambda opt: opt.value,
325
- fntypes.option.Nothing: lambda _: None,
326
- Variative: lambda variative: variative.v,
327
- datetime: lambda date: int(date.timestamp()),
328
- }
329
-
330
- def __repr__(self) -> str:
331
- return "<{}: enc_hooks={!r}>".format(
332
- self.__class__.__name__,
333
- self.enc_hooks,
334
- )
335
-
336
- @contextmanager
337
- def __call__(
338
- self,
339
- *,
340
- decimal_format: typing.Literal["string", "number"] = "string",
341
- uuid_format: typing.Literal["canonical", "hex"] = "canonical",
342
- order: typing.Literal[None, "deterministic", "sorted"] = None,
343
- ) -> typing.Generator[msgspec.json.Encoder, typing.Any, None]:
344
- """Context manager returns the `msgspec.json.Encoder` object with the `enc_hook`."""
345
-
346
- enc_obj = msgspec.json.Encoder(enc_hook=self.enc_hook)
347
- yield enc_obj
348
-
349
- def add_enc_hook(self, t: type[T]):
350
- def decorator(func: EncHook[T]) -> EncHook[T]:
351
- encode_hook = self.enc_hooks.setdefault(get_origin(t), func)
352
- return func if encode_hook is not func else encode_hook
353
-
354
- return decorator
355
-
356
- def enc_hook(self, obj: object) -> object:
357
- origin_type = get_origin(obj.__class__)
358
- if origin_type not in self.enc_hooks:
359
- raise NotImplementedError(
360
- f"Not implemented encode hook for object of type `{repr_type(origin_type)}`."
361
- )
362
- return self.enc_hooks[origin_type](obj)
363
-
364
- @typing.overload
365
- def encode(self, obj: typing.Any) -> str: ...
366
-
367
- @typing.overload
368
- def encode(self, obj: typing.Any, *, as_str: typing.Literal[True]) -> str: ...
369
-
370
- @typing.overload
371
- def encode(self, obj: typing.Any, *, as_str: typing.Literal[False]) -> bytes: ...
372
-
373
- def encode(self, obj: typing.Any, *, as_str: bool = True) -> str | bytes:
374
- buf = msgspec.json.encode(obj, enc_hook=self.enc_hook)
375
- return buf.decode() if as_str else buf
376
-
377
- def to_builtins(
378
- self,
379
- obj: typing.Any,
380
- *,
381
- str_keys: bool = False,
382
- builtin_types: typing.Iterable[type[typing.Any]] | None = None,
383
- order: typing.Literal["deterministic", "sorted"] | None = None,
384
- ) -> typing.Any:
385
- return msgspec.to_builtins(
386
- obj,
387
- str_keys=str_keys,
388
- builtin_types=builtin_types,
389
- enc_hook=self.enc_hook,
390
- order=order,
391
- )
392
-
393
-
394
- decoder: typing.Final[Decoder] = Decoder()
395
- encoder: typing.Final[Encoder] = Encoder()
396
-
397
-
398
- __all__ = (
399
- "Decoder",
400
- "Encoder",
401
- "Nothing",
402
- "Option",
403
- "datetime",
404
- "decoder",
405
- "encoder",
406
- "get_class_annotations",
407
- "get_type_hints",
408
- "msgspec_convert",
409
- "msgspec_to_builtins",
410
- )
1
+ import typing
2
+ from contextlib import contextmanager
3
+
4
+ import fntypes.option
5
+ import fntypes.result
6
+ import msgspec
7
+ from fntypes.co import Error, Ok, Variative
8
+
9
+ if typing.TYPE_CHECKING:
10
+ from datetime import datetime
11
+
12
+ from fntypes.option import Option
13
+
14
+ def get_class_annotations(obj: typing.Any, /) -> dict[str, typing.Any]: ...
15
+
16
+ def get_type_hints(obj: typing.Any, /) -> dict[str, typing.Any]: ...
17
+
18
+ else:
19
+ from datetime import datetime as dt
20
+
21
+ from msgspec._utils import get_class_annotations, get_type_hints
22
+
23
+ datetime = type("datetime", (dt,), {})
24
+
25
+ class OptionMeta(type):
26
+ def __instancecheck__(cls, __instance: typing.Any) -> bool:
27
+ return isinstance(__instance, (fntypes.option.Some | fntypes.option.Nothing, msgspec.UnsetType))
28
+
29
+ class Option[Value](metaclass=OptionMeta):
30
+ pass
31
+
32
+
33
+ type DecHook[T] = typing.Callable[typing.Concatenate[type[T], typing.Any, ...], typing.Any]
34
+ type EncHook[T] = typing.Callable[typing.Concatenate[T, ...], typing.Any]
35
+
36
+
37
+ def get_origin[T](t: type[T]) -> type[T]:
38
+ return typing.cast(T, typing.get_origin(t)) or t
39
+
40
+
41
+ def repr_type(t: typing.Any) -> str:
42
+ return getattr(t, "__name__", repr(get_origin(t)))
43
+
44
+
45
+ def is_common_type(type_: typing.Any) -> typing.TypeGuard[type[typing.Any]]:
46
+ if not isinstance(type_, type):
47
+ return False
48
+ return (
49
+ type_ in (str, int, float, bool, None, Variative)
50
+ or issubclass(type_, msgspec.Struct)
51
+ or hasattr(type_, "__dataclass_fields__")
52
+ )
53
+
54
+
55
+ def struct_as_dict(struct: msgspec.Struct, /) -> dict[str, typing.Any]:
56
+ return {
57
+ k: v
58
+ for k, v in msgspec.structs.asdict(struct).items()
59
+ if not isinstance(v, msgspec.UnsetType | type(None) | fntypes.option.Nothing)
60
+ }
61
+
62
+
63
+ def type_check(obj: typing.Any, t: typing.Any) -> bool:
64
+ return (
65
+ isinstance(obj, t)
66
+ if isinstance(t, type) and issubclass(t, msgspec.Struct)
67
+ else type(obj) in t
68
+ if isinstance(t, tuple)
69
+ else type(obj) is t
70
+ )
71
+
72
+
73
+ def msgspec_convert[T](obj: typing.Any, t: type[T]) -> fntypes.result.Result[T, str]:
74
+ try:
75
+ return Ok(decoder.convert(obj, type=t, strict=True))
76
+ except msgspec.ValidationError:
77
+ return Error(
78
+ "Expected object of type `{}`, got `{}`.".format(
79
+ repr_type(t),
80
+ repr_type(type(obj)),
81
+ )
82
+ )
83
+
84
+
85
+ def msgspec_to_builtins(
86
+ obj: typing.Any,
87
+ *,
88
+ str_keys: bool = False,
89
+ builtin_types: typing.Iterable[type[typing.Any]] | None = None,
90
+ order: typing.Literal["deterministic", "sorted"] | None = None,
91
+ ) -> fntypes.result.Result[typing.Any, msgspec.ValidationError]:
92
+ try:
93
+ return Ok(encoder.to_builtins(**locals()))
94
+ except msgspec.ValidationError as exc:
95
+ return Error(exc)
96
+
97
+
98
+ def option_dec_hook(
99
+ tp: type[Option[typing.Any]],
100
+ obj: typing.Any,
101
+ ) -> fntypes.option.Option[typing.Any] | msgspec.UnsetType:
102
+ if obj is msgspec.UNSET:
103
+ return obj
104
+
105
+ if obj is None or isinstance(obj, fntypes.option.Nothing):
106
+ return fntypes.option.Nothing()
107
+
108
+ (value_type,) = typing.get_args(tp) or (typing.Any,)
109
+ orig_value_type = typing.get_origin(value_type) or value_type
110
+ orig_obj = obj
111
+
112
+ if not isinstance(orig_obj, dict | list) and is_common_type(orig_value_type):
113
+ if orig_value_type is Variative:
114
+ obj = value_type(orig_obj) # type: ignore
115
+ orig_value_type = typing.get_args(value_type)
116
+
117
+ if not type_check(orig_obj, orig_value_type):
118
+ raise TypeError(f"Expected `{repr_type(orig_value_type)}`, got `{repr_type(type(orig_obj))}`.")
119
+
120
+ return fntypes.option.Some(obj)
121
+
122
+ return fntypes.option.Some(decoder.convert(orig_obj, type=value_type))
123
+
124
+
125
+ def variative_dec_hook(tp: type[Variative], obj: typing.Any) -> Variative:
126
+ union_types = typing.get_args(tp)
127
+
128
+ if isinstance(obj, dict):
129
+ models_struct_fields: dict[type[msgspec.Struct], int] = {
130
+ m: sum(1 for k in obj if k in m.__struct_fields__)
131
+ for m in union_types
132
+ if issubclass(get_origin(m), msgspec.Struct)
133
+ }
134
+ union_types = tuple(t for t in union_types if t not in models_struct_fields)
135
+ reverse = False
136
+
137
+ if len(set(models_struct_fields.values())) != len(models_struct_fields.values()):
138
+ models_struct_fields = {m: len(m.__struct_fields__) for m in models_struct_fields}
139
+ reverse = True
140
+
141
+ union_types = (
142
+ *sorted(
143
+ models_struct_fields,
144
+ key=lambda k: models_struct_fields[k],
145
+ reverse=reverse,
146
+ ),
147
+ *union_types,
148
+ )
149
+
150
+ for t in union_types:
151
+ if not isinstance(obj, dict | list) and is_common_type(t) and type_check(obj, t):
152
+ return tp(obj)
153
+ match msgspec_convert(obj, t):
154
+ case Ok(value):
155
+ return tp(value)
156
+
157
+ raise TypeError(
158
+ "Object of type `{}` does not belong to types `{}`".format(
159
+ repr_type(obj.__class__),
160
+ " | ".join(map(repr_type, union_types)),
161
+ )
162
+ )
163
+
164
+
165
+ class Decoder:
166
+ """Class `Decoder` for `msgspec` module with decode hook
167
+ for objects with the specified type.
168
+
169
+ ```
170
+ import enum
171
+
172
+ from datetime import datetime as dt
173
+
174
+ class Digit(enum.IntEnum):
175
+ ONE = 1
176
+ TWO = 2
177
+ THREE = 3
178
+
179
+ decoder = Decoder()
180
+ decoder.dec_hooks[dt] = lambda t, timestamp: t.fromtimestamp(timestamp)
181
+
182
+ decoder.dec_hook(dt, 1713354732) #> datetime.datetime(2024, 4, 17, 14, 52, 12)
183
+
184
+ decoder.convert("123", type=int, strict=False) #> 123
185
+ decoder.convert(1, type=Digit) #> <Digit.ONE: 1>
186
+
187
+ decoder.decode(b'{"digit":3}', type=dict[str, Digit]) #> {'digit': <Digit.THREE: 3>}
188
+ ```
189
+ """
190
+
191
+ def __init__(self) -> None:
192
+ self.dec_hooks: dict[typing.Any, DecHook[typing.Any]] = {
193
+ Option: option_dec_hook,
194
+ Variative: variative_dec_hook,
195
+ datetime: lambda t, obj: t.fromtimestamp(obj),
196
+ fntypes.option.Some: option_dec_hook,
197
+ fntypes.option.Nothing: option_dec_hook,
198
+ }
199
+
200
+ def __repr__(self) -> str:
201
+ return "<{}: dec_hooks={!r}>".format(
202
+ self.__class__.__name__,
203
+ self.dec_hooks,
204
+ )
205
+
206
+ @typing.overload
207
+ def __call__[T](
208
+ self,
209
+ type: type[T],
210
+ context: dict[str, typing.Any] | None = None,
211
+ ) -> typing.ContextManager[msgspec.json.Decoder[T]]: ...
212
+
213
+ @typing.overload
214
+ def __call__(
215
+ self,
216
+ type: typing.Any,
217
+ context: dict[str, typing.Any] | None = None,
218
+ ) -> typing.ContextManager[msgspec.json.Decoder[typing.Any]]: ...
219
+
220
+ @typing.overload
221
+ def __call__[T](
222
+ self,
223
+ type: type[T],
224
+ *,
225
+ strict: bool = True,
226
+ context: dict[str, typing.Any] | None = None,
227
+ ) -> typing.ContextManager[msgspec.json.Decoder[T]]: ...
228
+
229
+ @typing.overload
230
+ def __call__(
231
+ self,
232
+ type: typing.Any,
233
+ *,
234
+ strict: bool = True,
235
+ context: dict[str, typing.Any] | None = None,
236
+ ) -> typing.ContextManager[msgspec.json.Decoder[typing.Any]]: ...
237
+
238
+ @contextmanager
239
+ def __call__(self, type=object, *, strict=True, context=None):
240
+ """Context manager returns an `msgspec.json.Decoder` object with the `dec_hook`."""
241
+ dec_obj = msgspec.json.Decoder(
242
+ type=typing.Any if type is object else type,
243
+ strict=strict,
244
+ dec_hook=self.dec_hook(context),
245
+ )
246
+ yield dec_obj
247
+
248
+ def add_dec_hook[T](self, t: type[T], /):
249
+ def decorator(func: DecHook[T]) -> DecHook[T]:
250
+ return self.dec_hooks.setdefault(get_origin(t), func)
251
+
252
+ return decorator
253
+
254
+ def dec_hook(self, context: dict[str, typing.Any] | None = None):
255
+ from telegrinder.tools.magic import magic_bundle
256
+
257
+ def inner(tp: type[typing.Any], obj: object) -> typing.Any:
258
+ origin_type = t if isinstance((t := get_origin(tp)), type) else type(t)
259
+ if origin_type not in self.dec_hooks:
260
+ raise TypeError(
261
+ f"Unknown type `{repr_type(origin_type)}`. You can implement decode hook for this type."
262
+ )
263
+ dec_hook_func = self.dec_hooks[origin_type]
264
+ kwargs = magic_bundle(dec_hook_func, context or {}, start_idx=2, bundle_ctx=False)
265
+ return dec_hook_func(tp, obj, **kwargs)
266
+
267
+ return inner
268
+
269
+ def convert[T](
270
+ self,
271
+ obj: object,
272
+ *,
273
+ type: type[T] = dict,
274
+ strict: bool = True,
275
+ from_attributes: bool = False,
276
+ builtin_types: typing.Iterable[type[typing.Any]] | None = None,
277
+ str_keys: bool = False,
278
+ context: dict[str, typing.Any] | None = None,
279
+ ) -> T:
280
+ return msgspec.convert(
281
+ obj,
282
+ type,
283
+ strict=strict,
284
+ from_attributes=from_attributes,
285
+ dec_hook=self.dec_hook(context),
286
+ builtin_types=builtin_types,
287
+ str_keys=str_keys,
288
+ )
289
+
290
+ @typing.overload
291
+ def decode(
292
+ self,
293
+ buf: str | bytes,
294
+ *,
295
+ context: dict[str, typing.Any] | None = None,
296
+ ) -> typing.Any: ...
297
+
298
+ @typing.overload
299
+ def decode[T](
300
+ self,
301
+ buf: str | bytes,
302
+ *,
303
+ type: type[T],
304
+ context: dict[str, typing.Any] | None = None,
305
+ ) -> T: ...
306
+
307
+ @typing.overload
308
+ def decode(
309
+ self,
310
+ buf: str | bytes,
311
+ *,
312
+ type: typing.Any,
313
+ context: dict[str, typing.Any] | None = None,
314
+ ) -> typing.Any: ...
315
+
316
+ @typing.overload
317
+ def decode[T](
318
+ self,
319
+ buf: str | bytes,
320
+ *,
321
+ type: type[T],
322
+ strict: bool = True,
323
+ context: dict[str, typing.Any] | None = None,
324
+ ) -> T: ...
325
+
326
+ @typing.overload
327
+ def decode(
328
+ self,
329
+ buf: str | bytes,
330
+ *,
331
+ type: typing.Any,
332
+ strict: bool = True,
333
+ context: dict[str, typing.Any] | None = None,
334
+ ) -> typing.Any: ...
335
+
336
+ def decode(self, buf, *, type=object, strict=True, context=None):
337
+ return msgspec.json.decode(
338
+ buf,
339
+ type=typing.Any if type is object else type,
340
+ strict=strict,
341
+ dec_hook=self.dec_hook(context),
342
+ )
343
+
344
+
345
+ class Encoder:
346
+ """Class `Encoder` for `msgspec` module with encode hooks for objects.
347
+
348
+ ```
349
+ from datetime import datetime as dt
350
+
351
+ encoder = Encoder()
352
+ encoder.enc_hooks[dt] = lambda d: int(d.timestamp())
353
+
354
+ encoder.enc_hook(dt.now()) #> 1713354732
355
+ encoder.encode({'digit': Digit.ONE}) #> '{"digit":1}'
356
+ ```
357
+ """
358
+
359
+ def __init__(self) -> None:
360
+ self.enc_hooks: dict[typing.Any, EncHook[typing.Any]] = {
361
+ fntypes.option.Some: lambda opt: opt.value,
362
+ fntypes.option.Nothing: lambda _: None,
363
+ Variative: lambda variative: variative.v,
364
+ datetime: lambda date: int(date.timestamp()),
365
+ }
366
+
367
+ def __repr__(self) -> str:
368
+ return "<{}: enc_hooks={!r}>".format(
369
+ self.__class__.__name__,
370
+ self.enc_hooks,
371
+ )
372
+
373
+ @contextmanager
374
+ def __call__(
375
+ self,
376
+ *,
377
+ decimal_format: typing.Literal["string", "number"] = "string",
378
+ uuid_format: typing.Literal["canonical", "hex"] = "canonical",
379
+ order: typing.Literal[None, "deterministic", "sorted"] = None,
380
+ context: dict[str, typing.Any] | None = None,
381
+ ) -> typing.Generator[msgspec.json.Encoder, typing.Any, None]:
382
+ """Context manager returns an `msgspec.json.Encoder` object with the `enc_hook`."""
383
+ enc_obj = msgspec.json.Encoder(enc_hook=self.enc_hook(context))
384
+ yield enc_obj
385
+
386
+ def add_enc_hook[T](self, t: type[T], /):
387
+ def decorator(func: EncHook[T]) -> EncHook[T]:
388
+ encode_hook = self.enc_hooks.setdefault(get_origin(t), func)
389
+ return func if encode_hook is not func else encode_hook
390
+
391
+ return decorator
392
+
393
+ def enc_hook(self, context: dict[str, typing.Any] | None = None):
394
+ from telegrinder.tools.magic import magic_bundle
395
+
396
+ def inner(obj: typing.Any) -> typing.Any:
397
+ origin_type = get_origin(obj.__class__)
398
+ if origin_type not in self.enc_hooks:
399
+ raise NotImplementedError(
400
+ f"Not implemented encode hook for object of type `{repr_type(origin_type)}`.",
401
+ )
402
+ enc_hook_func = self.enc_hooks[origin_type]
403
+ kwargs = magic_bundle(enc_hook_func, context or {}, start_idx=1, bundle_ctx=False)
404
+ return enc_hook_func(obj, **kwargs)
405
+
406
+ return inner
407
+
408
+ @typing.overload
409
+ def encode(
410
+ self,
411
+ obj: typing.Any,
412
+ *,
413
+ context: dict[str, typing.Any] | None = None,
414
+ ) -> str: ...
415
+
416
+ @typing.overload
417
+ def encode(
418
+ self,
419
+ obj: typing.Any,
420
+ *,
421
+ as_str: typing.Literal[True],
422
+ context: dict[str, typing.Any] | None = None,
423
+ ) -> str: ...
424
+
425
+ @typing.overload
426
+ def encode(
427
+ self,
428
+ obj: typing.Any,
429
+ *,
430
+ as_str: typing.Literal[False],
431
+ context: dict[str, typing.Any] | None = None,
432
+ ) -> bytes: ...
433
+
434
+ def encode(
435
+ self,
436
+ obj: typing.Any,
437
+ *,
438
+ as_str: bool = True,
439
+ context: dict[str, typing.Any] | None = None,
440
+ ) -> str | bytes:
441
+ buf = msgspec.json.encode(obj, enc_hook=self.enc_hook(context))
442
+ return buf.decode() if as_str else buf
443
+
444
+ def to_builtins(
445
+ self,
446
+ obj: typing.Any,
447
+ *,
448
+ str_keys: bool = False,
449
+ builtin_types: typing.Iterable[type[typing.Any]] | None = None,
450
+ order: typing.Literal["deterministic", "sorted"] | None = None,
451
+ context: dict[str, typing.Any] | None = None,
452
+ ) -> typing.Any:
453
+ return msgspec.to_builtins(
454
+ obj,
455
+ str_keys=str_keys,
456
+ builtin_types=builtin_types,
457
+ enc_hook=self.enc_hook(context),
458
+ order=order,
459
+ )
460
+
461
+
462
+ decoder: typing.Final[Decoder] = Decoder()
463
+ encoder: typing.Final[Encoder] = Encoder()
464
+
465
+
466
+ __all__ = (
467
+ "Decoder",
468
+ "Encoder",
469
+ "Option",
470
+ "datetime",
471
+ "decoder",
472
+ "encoder",
473
+ "get_class_annotations",
474
+ "get_type_hints",
475
+ "msgspec_convert",
476
+ "msgspec_to_builtins",
477
+ "struct_as_dict",
478
+ )