satori-python-core 1.3.0__tar.gz → 1.3.3__tar.gz
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.
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/.mina/core.toml +3 -5
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/PKG-INFO +6 -8
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/README.md +2 -2
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/pyproject.toml +15 -19
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/__init__.py +1 -1
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/element.py +125 -52
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/model.py +82 -43
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/parser.py +56 -16
- satori_python_core-1.3.3/src/satori/py.typed +0 -0
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/utils.py +6 -0
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/LICENSE +0 -0
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/_vendor/fleep.py +0 -0
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/const.py +0 -0
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/event.py +0 -0
- {satori_python_core-1.3.0 → satori_python_core-1.3.3}/src/satori/exception.py +0 -0
|
@@ -8,8 +8,6 @@ authors = [
|
|
|
8
8
|
{name = "RF-Tar-Railt", email = "rf_tar_railt@qq.com"}
|
|
9
9
|
]
|
|
10
10
|
dependencies = [
|
|
11
|
-
"loguru",
|
|
12
|
-
"yarl",
|
|
13
11
|
"typing-extensions",
|
|
14
12
|
]
|
|
15
13
|
description = "Satori Protocol SDK for python, specify common part"
|
|
@@ -18,13 +16,13 @@ readme = "README.md"
|
|
|
18
16
|
requires-python = ">=3.10,<4.0"
|
|
19
17
|
classifiers = [
|
|
20
18
|
"Typing :: Typed",
|
|
21
|
-
"Development Status ::
|
|
19
|
+
"Development Status :: 5 - Production/Stable",
|
|
22
20
|
"License :: OSI Approved :: MIT License",
|
|
23
|
-
"Programming Language :: Python :: 3.8",
|
|
24
|
-
"Programming Language :: Python :: 3.9",
|
|
25
21
|
"Programming Language :: Python :: 3.10",
|
|
26
22
|
"Programming Language :: Python :: 3.11",
|
|
27
23
|
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
28
26
|
"Operating System :: OS Independent",
|
|
29
27
|
]
|
|
30
28
|
|
|
@@ -1,24 +1,22 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: satori-python-core
|
|
3
|
-
Version: 1.3.
|
|
3
|
+
Version: 1.3.3
|
|
4
4
|
Summary: Satori Protocol SDK for python, specify common part
|
|
5
5
|
Home-page: https://github.com/RF-Tar-Railt/satori-python
|
|
6
6
|
Author-Email: RF-Tar-Railt <rf_tar_railt@qq.com>
|
|
7
7
|
License: MIT
|
|
8
8
|
Classifier: Typing :: Typed
|
|
9
|
-
Classifier: Development Status ::
|
|
9
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
10
10
|
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.9
|
|
13
11
|
Classifier: Programming Language :: Python :: 3.10
|
|
14
12
|
Classifier: Programming Language :: Python :: 3.11
|
|
15
13
|
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
16
|
Classifier: Operating System :: OS Independent
|
|
17
17
|
Project-URL: Homepage, https://github.com/RF-Tar-Railt/satori-python
|
|
18
18
|
Project-URL: Repository, https://github.com/RF-Tar-Railt/satori-python
|
|
19
19
|
Requires-Python: <4.0,>=3.10
|
|
20
|
-
Requires-Dist: loguru>=0.7.2
|
|
21
|
-
Requires-Dist: yarl>=1.9.4
|
|
22
20
|
Requires-Dist: typing-extensions>=4.7.0
|
|
23
21
|
Description-Content-Type: text/markdown
|
|
24
22
|
|
|
@@ -29,11 +27,11 @@ Description-Content-Type: text/markdown
|
|
|
29
27
|
[](https://pypi.org/project/satori-python)
|
|
30
28
|
[](https://www.python.org/)
|
|
31
29
|
|
|
32
|
-
基于 [Satori](https://satori.chat/zh-CN/) 协议的 Python 开发工具包
|
|
30
|
+
基于 [Satori](https://satori.chat/zh-CN/protocol) 协议的 Python 开发工具包
|
|
33
31
|
|
|
34
32
|
## 协议介绍
|
|
35
33
|
|
|
36
|
-
[Satori Protocol](https://satori.chat/zh-CN/)
|
|
34
|
+
[Satori Protocol](https://satori.chat/zh-CN/protocol)
|
|
37
35
|
|
|
38
36
|
### 协议端
|
|
39
37
|
|
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
[](https://pypi.org/project/satori-python)
|
|
6
6
|
[](https://www.python.org/)
|
|
7
7
|
|
|
8
|
-
基于 [Satori](https://satori.chat/zh-CN/) 协议的 Python 开发工具包
|
|
8
|
+
基于 [Satori](https://satori.chat/zh-CN/protocol) 协议的 Python 开发工具包
|
|
9
9
|
|
|
10
10
|
## 协议介绍
|
|
11
11
|
|
|
12
|
-
[Satori Protocol](https://satori.chat/zh-CN/)
|
|
12
|
+
[Satori Protocol](https://satori.chat/zh-CN/protocol)
|
|
13
13
|
|
|
14
14
|
### 协议端
|
|
15
15
|
|
|
@@ -5,8 +5,6 @@ authors = [
|
|
|
5
5
|
{ name = "RF-Tar-Railt", email = "rf_tar_railt@qq.com" },
|
|
6
6
|
]
|
|
7
7
|
dependencies = [
|
|
8
|
-
"loguru>=0.7.2",
|
|
9
|
-
"yarl>=1.9.4",
|
|
10
8
|
"typing-extensions>=4.7.0",
|
|
11
9
|
]
|
|
12
10
|
description = "Satori Protocol SDK for python, specify common part"
|
|
@@ -14,16 +12,16 @@ readme = "README.md"
|
|
|
14
12
|
requires-python = ">=3.10,<4.0"
|
|
15
13
|
classifiers = [
|
|
16
14
|
"Typing :: Typed",
|
|
17
|
-
"Development Status ::
|
|
15
|
+
"Development Status :: 5 - Production/Stable",
|
|
18
16
|
"License :: OSI Approved :: MIT License",
|
|
19
|
-
"Programming Language :: Python :: 3.8",
|
|
20
|
-
"Programming Language :: Python :: 3.9",
|
|
21
17
|
"Programming Language :: Python :: 3.10",
|
|
22
18
|
"Programming Language :: Python :: 3.11",
|
|
23
19
|
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Programming Language :: Python :: 3.14",
|
|
24
22
|
"Operating System :: OS Independent",
|
|
25
23
|
]
|
|
26
|
-
version = "1.3.
|
|
24
|
+
version = "1.3.3"
|
|
27
25
|
|
|
28
26
|
[project.license]
|
|
29
27
|
text = "MIT"
|
|
@@ -41,15 +39,14 @@ build-backend = "mina.backend"
|
|
|
41
39
|
|
|
42
40
|
[dependency-groups]
|
|
43
41
|
dev = [
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"ruff>=0.4.1",
|
|
42
|
+
"black>=26.3.0",
|
|
43
|
+
"ruff>=0.15.1",
|
|
47
44
|
"pre-commit>=3.7.0",
|
|
48
|
-
"fix-future-annotations>=0.5.0",
|
|
49
45
|
"mina-build<0.6,>=0.5.1",
|
|
50
46
|
"pdm-mina>=0.3.2",
|
|
51
47
|
"nonechat<0.7.0,>=0.6.0",
|
|
52
48
|
"uvicorn[standard]>=0.37.0",
|
|
49
|
+
"pydantic>=2.13.1",
|
|
53
50
|
]
|
|
54
51
|
|
|
55
52
|
[tool.pdm.build]
|
|
@@ -65,7 +62,7 @@ excludes = [
|
|
|
65
62
|
|
|
66
63
|
[tool.pdm.scripts.format]
|
|
67
64
|
composite = [
|
|
68
|
-
"
|
|
65
|
+
"ruff check --select I --fix ./src/ ./example/",
|
|
69
66
|
"black ./src/ ./example/",
|
|
70
67
|
"ruff check",
|
|
71
68
|
]
|
|
@@ -79,14 +76,6 @@ line-length = 120
|
|
|
79
76
|
include = "\\.pyi?$"
|
|
80
77
|
extend-exclude = ""
|
|
81
78
|
|
|
82
|
-
[tool.isort]
|
|
83
|
-
profile = "black"
|
|
84
|
-
line_length = 120
|
|
85
|
-
skip_gitignore = true
|
|
86
|
-
extra_standard_library = [
|
|
87
|
-
"typing_extensions",
|
|
88
|
-
]
|
|
89
|
-
|
|
90
79
|
[tool.ruff]
|
|
91
80
|
line-length = 120
|
|
92
81
|
target-version = "py310"
|
|
@@ -96,6 +85,7 @@ exclude = [
|
|
|
96
85
|
"exam2.py",
|
|
97
86
|
"src/satori/_vendor/*",
|
|
98
87
|
]
|
|
88
|
+
respect-gitignore = true
|
|
99
89
|
|
|
100
90
|
[tool.ruff.lint]
|
|
101
91
|
select = [
|
|
@@ -115,6 +105,12 @@ ignore = [
|
|
|
115
105
|
"T201",
|
|
116
106
|
]
|
|
117
107
|
|
|
108
|
+
[tool.ruff.lint.isort]
|
|
109
|
+
extra-standard-library = [
|
|
110
|
+
"typing_extensions",
|
|
111
|
+
]
|
|
112
|
+
force-sort-within-sections = false
|
|
113
|
+
|
|
118
114
|
[tool.pyright]
|
|
119
115
|
pythonPlatform = "All"
|
|
120
116
|
pythonVersion = "3.10"
|
|
@@ -4,7 +4,7 @@ from dataclasses import InitVar, dataclass, field
|
|
|
4
4
|
from io import BytesIO
|
|
5
5
|
from pathlib import Path
|
|
6
6
|
from types import UnionType
|
|
7
|
-
from typing import Any, ClassVar, Final, TypeVar, Union, final, get_args, get_origin, overload
|
|
7
|
+
from typing import Any, ClassVar, Final, Literal, TypeVar, Union, final, get_args, get_origin, overload
|
|
8
8
|
from typing_extensions import Self, override
|
|
9
9
|
|
|
10
10
|
from ._vendor.fleep import get
|
|
@@ -17,7 +17,7 @@ TE = TypeVar("TE", bound="Element")
|
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
def conv_bool(v: str) -> bool:
|
|
20
|
-
if v.lower() not in
|
|
20
|
+
if v.lower() not in {"true", "false"}:
|
|
21
21
|
raise ValueError(v)
|
|
22
22
|
return v.lower() == "true"
|
|
23
23
|
|
|
@@ -28,13 +28,17 @@ class Element:
|
|
|
28
28
|
_children: list["Element"] = field(init=False, default_factory=list)
|
|
29
29
|
|
|
30
30
|
__names__: ClassVar[tuple[str, ...]]
|
|
31
|
-
__convert_fields__: ClassVar[dict[str, Callable[[str], Any]]]
|
|
31
|
+
__convert_fields__: ClassVar[dict[str, Literal[True] | Callable[[str], Any]]]
|
|
32
|
+
__unpack_names__: ClassVar[frozenset[str]]
|
|
32
33
|
|
|
33
34
|
def __init_subclass__(cls, **kwargs):
|
|
34
|
-
|
|
35
|
+
convert_fields = {}
|
|
36
|
+
for base in cls.__mro__:
|
|
37
|
+
if hasattr(base, "__convert_fields__"):
|
|
38
|
+
convert_fields.update(base.__convert_fields__)
|
|
35
39
|
annotations = cls.__annotations__
|
|
36
40
|
for name, typ in annotations.items():
|
|
37
|
-
if name.startswith("_"):
|
|
41
|
+
if name.startswith("_") or isinstance(typ, InitVar):
|
|
38
42
|
continue
|
|
39
43
|
# _type = get_args(typ)[0] if hasattr(typ, "__origin__") else typ
|
|
40
44
|
orig = get_origin(typ)
|
|
@@ -46,39 +50,49 @@ class Element:
|
|
|
46
50
|
_type = args[0]
|
|
47
51
|
else:
|
|
48
52
|
_type = typ
|
|
49
|
-
if _type is
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
if _type is bool:
|
|
54
|
+
convert_fields[name] = conv_bool
|
|
55
|
+
elif _type in (list, dict):
|
|
56
|
+
convert_fields[name] = decode
|
|
57
|
+
else:
|
|
58
|
+
convert_fields[name] = True if _type is str else _type
|
|
59
|
+
cls.__convert_fields__ = convert_fields
|
|
60
|
+
names = getattr(cls, "__names__", None)
|
|
61
|
+
for base in cls.__mro__:
|
|
62
|
+
if parent_names := getattr(base, "__names__", None):
|
|
63
|
+
if names is None:
|
|
64
|
+
names = parent_names
|
|
54
65
|
else:
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
@property
|
|
58
|
-
def children(self) -> list["Element"]:
|
|
59
|
-
return self._children
|
|
60
|
-
|
|
61
|
-
@property
|
|
62
|
-
def tag(self) -> str:
|
|
63
|
-
return self.__class__.__name__.lower()
|
|
66
|
+
names = names + parent_names
|
|
67
|
+
cls.__unpack_names__ = frozenset(names if names is not None else annotations.keys())
|
|
64
68
|
|
|
65
69
|
@classmethod
|
|
66
70
|
def unpack(cls, attrs: dict[str, Any]):
|
|
67
71
|
data = {}
|
|
68
|
-
|
|
69
|
-
|
|
72
|
+
args = {}
|
|
73
|
+
convert_fields = cls.__convert_fields__
|
|
74
|
+
names = cls.__unpack_names__
|
|
75
|
+
for name in convert_fields:
|
|
70
76
|
if name not in attrs:
|
|
71
77
|
continue
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
else:
|
|
78
|
+
convert = convert_fields[name]
|
|
79
|
+
if convert is True:
|
|
75
80
|
data[name] = attrs[name]
|
|
76
|
-
|
|
81
|
+
else:
|
|
82
|
+
data[name] = convert(attrs[name])
|
|
83
|
+
if name in names:
|
|
84
|
+
args[name] = data[name]
|
|
85
|
+
obj = cls(**args) # type: ignore
|
|
77
86
|
obj._attrs.update(data)
|
|
78
87
|
return obj
|
|
79
88
|
|
|
80
|
-
|
|
81
|
-
|
|
89
|
+
@property
|
|
90
|
+
def children(self) -> list["Element"]:
|
|
91
|
+
return self._children
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def tag(self) -> str:
|
|
95
|
+
return self.__class__.__name__.lower()
|
|
82
96
|
|
|
83
97
|
def attributes(self) -> str:
|
|
84
98
|
def _attr(key: str, value: Any):
|
|
@@ -94,6 +108,8 @@ class Element:
|
|
|
94
108
|
return "".join(_attr(k, v) for k, v in self._attrs.items())
|
|
95
109
|
|
|
96
110
|
def dumps(self, strip: bool = False) -> str:
|
|
111
|
+
if not self._attrs:
|
|
112
|
+
self._attrs = {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
|
|
97
113
|
if self.tag == "text" and "text" in self._attrs:
|
|
98
114
|
return self._attrs["text"] if strip else escape(self._attrs["text"])
|
|
99
115
|
inner = "".join(c.dumps(strip) for c in self._children)
|
|
@@ -124,6 +140,9 @@ class Element:
|
|
|
124
140
|
def __getitem__(self, key: str) -> Any:
|
|
125
141
|
return self._attrs[key]
|
|
126
142
|
|
|
143
|
+
def raw(self) -> RawElement:
|
|
144
|
+
return RawElement(self.tag, self._attrs, [c.raw() for c in self._children])
|
|
145
|
+
|
|
127
146
|
|
|
128
147
|
@dataclass(repr=False)
|
|
129
148
|
class Text(Element):
|
|
@@ -131,6 +150,13 @@ class Text(Element):
|
|
|
131
150
|
|
|
132
151
|
text: str
|
|
133
152
|
|
|
153
|
+
@override
|
|
154
|
+
@classmethod
|
|
155
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
156
|
+
obj = cls(attrs["text"])
|
|
157
|
+
obj._attrs["text"] = attrs["text"]
|
|
158
|
+
return obj
|
|
159
|
+
|
|
134
160
|
@override
|
|
135
161
|
def dumps(self, strip: bool = False) -> str:
|
|
136
162
|
return self.text if strip else escape(self.text)
|
|
@@ -145,6 +171,12 @@ class At(Element):
|
|
|
145
171
|
role: str | None = None
|
|
146
172
|
type: str | None = None
|
|
147
173
|
|
|
174
|
+
@classmethod
|
|
175
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
176
|
+
obj = cls(attrs.get("id"), attrs.get("name"), attrs.get("role"), attrs.get("type"))
|
|
177
|
+
obj._attrs.update(attrs)
|
|
178
|
+
return obj
|
|
179
|
+
|
|
148
180
|
@staticmethod
|
|
149
181
|
def role_(
|
|
150
182
|
role: str,
|
|
@@ -164,6 +196,12 @@ class Emoji(Element):
|
|
|
164
196
|
id: str
|
|
165
197
|
name: str | None = None
|
|
166
198
|
|
|
199
|
+
@classmethod
|
|
200
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
201
|
+
obj = cls(attrs["id"], attrs.get("name"))
|
|
202
|
+
obj._attrs.update(attrs)
|
|
203
|
+
return obj
|
|
204
|
+
|
|
167
205
|
def to_model(self):
|
|
168
206
|
from .model import EmojiObject
|
|
169
207
|
|
|
@@ -177,6 +215,12 @@ class Sharp(Element):
|
|
|
177
215
|
id: str
|
|
178
216
|
name: str | None = None
|
|
179
217
|
|
|
218
|
+
@classmethod
|
|
219
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
220
|
+
obj = cls(attrs["id"], attrs.get("name"))
|
|
221
|
+
obj._attrs.update(attrs)
|
|
222
|
+
return obj
|
|
223
|
+
|
|
180
224
|
|
|
181
225
|
@dataclass(repr=False)
|
|
182
226
|
class Link(Element):
|
|
@@ -184,6 +228,12 @@ class Link(Element):
|
|
|
184
228
|
|
|
185
229
|
href: str
|
|
186
230
|
|
|
231
|
+
@classmethod
|
|
232
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
233
|
+
obj = cls(attrs["href"])
|
|
234
|
+
obj._attrs.update(attrs)
|
|
235
|
+
return obj
|
|
236
|
+
|
|
187
237
|
def __post_call__(self):
|
|
188
238
|
if not self._children:
|
|
189
239
|
return
|
|
@@ -255,7 +305,6 @@ class Resource(Element):
|
|
|
255
305
|
return cls(**data)
|
|
256
306
|
|
|
257
307
|
def __post_init__(self, extra: dict[str, Any] | None = None):
|
|
258
|
-
super().__post_init__()
|
|
259
308
|
if extra:
|
|
260
309
|
self._attrs.update(extra)
|
|
261
310
|
|
|
@@ -267,7 +316,7 @@ class Image(Resource):
|
|
|
267
316
|
width: int | None = None
|
|
268
317
|
height: int | None = None
|
|
269
318
|
|
|
270
|
-
__names__ = ("
|
|
319
|
+
__names__ = ("width", "height")
|
|
271
320
|
|
|
272
321
|
@property
|
|
273
322
|
@override
|
|
@@ -282,7 +331,7 @@ class Audio(Resource):
|
|
|
282
331
|
duration: float | None = None
|
|
283
332
|
poster: str | None = None
|
|
284
333
|
|
|
285
|
-
__names__ = ("
|
|
334
|
+
__names__ = ("duration", "poster")
|
|
286
335
|
|
|
287
336
|
|
|
288
337
|
@dataclass(repr=False)
|
|
@@ -294,7 +343,7 @@ class Video(Resource):
|
|
|
294
343
|
duration: float | None = None
|
|
295
344
|
poster: str | None = None
|
|
296
345
|
|
|
297
|
-
__names__ = ("
|
|
346
|
+
__names__ = ("width", "height", "duration", "poster")
|
|
298
347
|
|
|
299
348
|
|
|
300
349
|
@dataclass(repr=False)
|
|
@@ -303,7 +352,7 @@ class File(Resource):
|
|
|
303
352
|
|
|
304
353
|
poster: str | None = None
|
|
305
354
|
|
|
306
|
-
__names__ = ("
|
|
355
|
+
__names__ = ("poster",)
|
|
307
356
|
|
|
308
357
|
|
|
309
358
|
@dataclass(init=False, repr=False)
|
|
@@ -312,6 +361,12 @@ class Style(Element):
|
|
|
312
361
|
|
|
313
362
|
__names__ = ()
|
|
314
363
|
|
|
364
|
+
@classmethod
|
|
365
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
366
|
+
obj = cls()
|
|
367
|
+
obj._attrs.update(attrs)
|
|
368
|
+
return obj
|
|
369
|
+
|
|
315
370
|
def __init__(self, *text: "str | Text | Style"):
|
|
316
371
|
super().__init__()
|
|
317
372
|
self.__call__(*text)
|
|
@@ -422,6 +477,12 @@ class Message(Element):
|
|
|
422
477
|
id: str | None
|
|
423
478
|
forward: bool | None
|
|
424
479
|
|
|
480
|
+
@classmethod
|
|
481
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
482
|
+
obj = cls(attrs.get("id"), conv_bool(attrs["forward"]) if "forward" in attrs else None)
|
|
483
|
+
obj._attrs.update(attrs)
|
|
484
|
+
return obj
|
|
485
|
+
|
|
425
486
|
def __init__(
|
|
426
487
|
self,
|
|
427
488
|
id: str | None = None,
|
|
@@ -451,6 +512,12 @@ class Author(Element):
|
|
|
451
512
|
name: str | None = None
|
|
452
513
|
avatar: str | None = None
|
|
453
514
|
|
|
515
|
+
@classmethod
|
|
516
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
517
|
+
obj = cls(attrs["id"], attrs.get("name"), attrs.get("avatar"))
|
|
518
|
+
obj._attrs.update(attrs)
|
|
519
|
+
return obj
|
|
520
|
+
|
|
454
521
|
|
|
455
522
|
@dataclass(repr=False)
|
|
456
523
|
class Button(Element):
|
|
@@ -462,6 +529,12 @@ class Button(Element):
|
|
|
462
529
|
text: str | None = None
|
|
463
530
|
theme: str | None = None
|
|
464
531
|
|
|
532
|
+
@classmethod
|
|
533
|
+
def unpack(cls, attrs: dict[str, Any]):
|
|
534
|
+
obj = cls(attrs["type"], attrs.get("id"), attrs.get("href"), attrs.get("text"), attrs.get("theme"))
|
|
535
|
+
obj._attrs.update(attrs)
|
|
536
|
+
return obj
|
|
537
|
+
|
|
465
538
|
@classmethod
|
|
466
539
|
def action(cls, button_id: str, theme: str | None = None):
|
|
467
540
|
return Button("action", id=button_id, theme=theme)
|
|
@@ -533,7 +606,7 @@ class Raw(Element):
|
|
|
533
606
|
|
|
534
607
|
@override
|
|
535
608
|
def dumps(self, strip: bool = False):
|
|
536
|
-
return self.content
|
|
609
|
+
return self.content
|
|
537
610
|
|
|
538
611
|
|
|
539
612
|
def register_element(cls: type[TE], tag: str | None = None) -> type[TE]:
|
|
@@ -547,7 +620,7 @@ def register_element(cls: type[TE], tag: str | None = None) -> type[TE]:
|
|
|
547
620
|
return cls
|
|
548
621
|
|
|
549
622
|
|
|
550
|
-
|
|
623
|
+
COMMON_TYPE_MAP = {
|
|
551
624
|
"text": Text,
|
|
552
625
|
"at": At,
|
|
553
626
|
"emoji": Emoji,
|
|
@@ -558,6 +631,9 @@ ELEMENT_TYPE_MAP = {
|
|
|
558
631
|
"video": Video,
|
|
559
632
|
"file": File,
|
|
560
633
|
"author": Author,
|
|
634
|
+
"button": Button,
|
|
635
|
+
"a": Link,
|
|
636
|
+
"link": Link,
|
|
561
637
|
}
|
|
562
638
|
|
|
563
639
|
STYLE_TYPE_MAP = {
|
|
@@ -586,35 +662,32 @@ STYLE_TYPE_MAP = {
|
|
|
586
662
|
"br": Br,
|
|
587
663
|
}
|
|
588
664
|
|
|
665
|
+
ELEMENT_TYPE_MAP = {**COMMON_TYPE_MAP, **STYLE_TYPE_MAP}
|
|
666
|
+
|
|
589
667
|
|
|
590
668
|
def transform(elements: list[RawElement]) -> list[Element]:
|
|
591
669
|
msg = []
|
|
592
670
|
for elem in elements:
|
|
593
671
|
tag = elem.tag()
|
|
594
672
|
if tag in ELEMENT_TYPE_MAP:
|
|
595
|
-
|
|
596
|
-
msg.append(seg_cls.unpack(elem.attrs)(*transform(elem.children)))
|
|
597
|
-
elif tag in ("a", "link"):
|
|
598
|
-
link = Link.unpack(elem.attrs)
|
|
599
|
-
if elem.children:
|
|
600
|
-
link(*transform(elem.children))
|
|
601
|
-
msg.append(link)
|
|
602
|
-
elif tag == "button":
|
|
603
|
-
button = Button.unpack(elem.attrs)
|
|
673
|
+
seg = ELEMENT_TYPE_MAP[tag].unpack(elem.attrs)
|
|
604
674
|
if elem.children:
|
|
605
|
-
|
|
606
|
-
msg.append(
|
|
607
|
-
elif tag in STYLE_TYPE_MAP:
|
|
608
|
-
seg_cls = STYLE_TYPE_MAP[tag]
|
|
609
|
-
msg.append(seg_cls.unpack(elem.attrs)(*transform(elem.children)))
|
|
610
|
-
elif tag in ("br", "newline"):
|
|
611
|
-
msg.append(Br())
|
|
675
|
+
seg(*transform(elem.children))
|
|
676
|
+
msg.append(seg)
|
|
612
677
|
elif tag == "message":
|
|
613
678
|
msg.append(Message.unpack(elem.attrs)(*transform(elem.children)))
|
|
614
679
|
elif tag == "quote":
|
|
615
|
-
|
|
680
|
+
quot = Quote.unpack(elem.attrs)
|
|
681
|
+
if elem.children:
|
|
682
|
+
quot(*transform(elem.children))
|
|
683
|
+
msg.append(quot)
|
|
684
|
+
elif tag in ("br", "newline"):
|
|
685
|
+
msg.append(Br())
|
|
616
686
|
else:
|
|
617
|
-
|
|
687
|
+
custom = Custom(tag, elem.attrs)
|
|
688
|
+
if elem.children:
|
|
689
|
+
custom(*transform(elem.children))
|
|
690
|
+
msg.append(custom)
|
|
618
691
|
return msg
|
|
619
692
|
|
|
620
693
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import mimetypes
|
|
2
2
|
from collections.abc import AsyncIterable, Awaitable, Callable
|
|
3
|
-
from dataclasses import
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
4
|
from datetime import datetime
|
|
5
5
|
from enum import IntEnum
|
|
6
6
|
from os import PathLike
|
|
@@ -13,16 +13,20 @@ from .parser import Element as RawElement
|
|
|
13
13
|
from .parser import parse
|
|
14
14
|
|
|
15
15
|
|
|
16
|
-
@dataclass
|
|
16
|
+
@dataclass(slots=True)
|
|
17
17
|
class ModelBase:
|
|
18
18
|
__converter__: ClassVar[dict[str, Callable[[Any], Any]]] = {}
|
|
19
19
|
_raw_data: dict[str, Any] = field(init=False, default_factory=dict, repr=False, compare=False, hash=False)
|
|
20
20
|
|
|
21
|
+
@classmethod
|
|
22
|
+
def before_parse(cls, raw: dict):
|
|
23
|
+
pass
|
|
24
|
+
|
|
21
25
|
@classmethod
|
|
22
26
|
def parse(cls: type[Self], raw: dict) -> Self:
|
|
23
|
-
fs: dict[str, Field] = cls.__dataclass_fields__
|
|
24
27
|
data = {}
|
|
25
|
-
|
|
28
|
+
cls.before_parse(data)
|
|
29
|
+
for name in cls.__dataclass_fields__:
|
|
26
30
|
if name in raw:
|
|
27
31
|
if name in cls.__converter__:
|
|
28
32
|
data[name] = cls.__converter__[name](raw[name])
|
|
@@ -32,6 +36,42 @@ class ModelBase:
|
|
|
32
36
|
obj._raw_data = raw
|
|
33
37
|
return obj
|
|
34
38
|
|
|
39
|
+
def __init_subclass__(cls, **kwargs):
|
|
40
|
+
has_converter = False
|
|
41
|
+
keys = set()
|
|
42
|
+
for c in cls.__mro__:
|
|
43
|
+
if c is Generic:
|
|
44
|
+
Generic.__init_subclass__.__func__(cls, **kwargs)
|
|
45
|
+
if getattr(c, "__converter__", None):
|
|
46
|
+
has_converter = True
|
|
47
|
+
keys.update(getattr(c, "__annotations__", {}).keys())
|
|
48
|
+
keys = frozenset(k for k in keys if not k.startswith("_"))
|
|
49
|
+
|
|
50
|
+
def parse1(cls_: type[Self], raw: dict, _keys=keys) -> Self:
|
|
51
|
+
data = {k: v for k, v in raw.items() if k in _keys}
|
|
52
|
+
obj = cls_(**data) # type: ignore
|
|
53
|
+
obj._raw_data = raw
|
|
54
|
+
return obj
|
|
55
|
+
|
|
56
|
+
def parse2(cls_: type[Self], raw: dict, _keys=keys) -> Self:
|
|
57
|
+
data = {}
|
|
58
|
+
cls_.before_parse(data)
|
|
59
|
+
for name in _keys:
|
|
60
|
+
if name in raw:
|
|
61
|
+
if name in cls_.__converter__:
|
|
62
|
+
data[name] = cls_.__converter__[name](raw[name])
|
|
63
|
+
else:
|
|
64
|
+
data[name] = raw[name]
|
|
65
|
+
obj = cls_(**data) # type: ignore
|
|
66
|
+
obj._raw_data = raw
|
|
67
|
+
return obj
|
|
68
|
+
|
|
69
|
+
if "parse" not in cls.__dict__:
|
|
70
|
+
if has_converter:
|
|
71
|
+
cls.parse = classmethod(parse2) # type: ignore
|
|
72
|
+
else:
|
|
73
|
+
cls.parse = classmethod(parse1) # type: ignore
|
|
74
|
+
|
|
35
75
|
def dump(self) -> dict:
|
|
36
76
|
raise NotImplementedError
|
|
37
77
|
|
|
@@ -43,7 +83,7 @@ class ChannelType(IntEnum):
|
|
|
43
83
|
VOICE = 3
|
|
44
84
|
|
|
45
85
|
|
|
46
|
-
@dataclass
|
|
86
|
+
@dataclass(slots=True)
|
|
47
87
|
class Channel(ModelBase):
|
|
48
88
|
id: str
|
|
49
89
|
type: ChannelType = ChannelType.TEXT
|
|
@@ -61,7 +101,7 @@ class Channel(ModelBase):
|
|
|
61
101
|
return res
|
|
62
102
|
|
|
63
103
|
|
|
64
|
-
@dataclass
|
|
104
|
+
@dataclass(slots=True)
|
|
65
105
|
class Guild(ModelBase):
|
|
66
106
|
id: str
|
|
67
107
|
name: str | None = None
|
|
@@ -76,7 +116,7 @@ class Guild(ModelBase):
|
|
|
76
116
|
return res
|
|
77
117
|
|
|
78
118
|
|
|
79
|
-
@dataclass
|
|
119
|
+
@dataclass(slots=True)
|
|
80
120
|
class User(ModelBase):
|
|
81
121
|
id: str
|
|
82
122
|
name: str | None = None
|
|
@@ -97,7 +137,7 @@ class User(ModelBase):
|
|
|
97
137
|
return res
|
|
98
138
|
|
|
99
139
|
|
|
100
|
-
@dataclass
|
|
140
|
+
@dataclass(slots=True)
|
|
101
141
|
class Friend(ModelBase):
|
|
102
142
|
user: User | None = None
|
|
103
143
|
nick: str | None = None
|
|
@@ -117,11 +157,17 @@ class Friend(ModelBase):
|
|
|
117
157
|
return res
|
|
118
158
|
|
|
119
159
|
|
|
120
|
-
@dataclass
|
|
160
|
+
@dataclass(slots=True)
|
|
121
161
|
class Role(ModelBase):
|
|
122
162
|
id: str
|
|
123
163
|
name: str | None = None
|
|
124
164
|
|
|
165
|
+
@classmethod
|
|
166
|
+
def parse(cls, raw: str | dict):
|
|
167
|
+
if isinstance(raw, str):
|
|
168
|
+
return cls(id=raw)
|
|
169
|
+
return cls(raw["id"], raw.get("name"))
|
|
170
|
+
|
|
125
171
|
def dump(self):
|
|
126
172
|
res = {"id": self.id}
|
|
127
173
|
if self.name:
|
|
@@ -129,7 +175,7 @@ class Role(ModelBase):
|
|
|
129
175
|
return res
|
|
130
176
|
|
|
131
177
|
|
|
132
|
-
@dataclass
|
|
178
|
+
@dataclass(slots=True)
|
|
133
179
|
class Member(ModelBase):
|
|
134
180
|
user: User | None = None
|
|
135
181
|
nick: str | None = None
|
|
@@ -171,11 +217,11 @@ class LoginStatus(IntEnum):
|
|
|
171
217
|
"""正在重新连接"""
|
|
172
218
|
|
|
173
219
|
|
|
174
|
-
@dataclass
|
|
220
|
+
@dataclass(slots=True, kw_only=True)
|
|
175
221
|
class Login(ModelBase):
|
|
176
|
-
sn: int
|
|
177
|
-
status: LoginStatus
|
|
178
|
-
adapter: str
|
|
222
|
+
sn: int = 0
|
|
223
|
+
status: LoginStatus = LoginStatus.ONLINE
|
|
224
|
+
adapter: str = "satori"
|
|
179
225
|
platform: str
|
|
180
226
|
user: User
|
|
181
227
|
features: list[str] = field(default_factory=list)
|
|
@@ -197,29 +243,22 @@ class Login(ModelBase):
|
|
|
197
243
|
return res
|
|
198
244
|
|
|
199
245
|
@classmethod
|
|
200
|
-
def
|
|
246
|
+
def before_parse(cls, raw: dict):
|
|
201
247
|
if "self_id" in raw and "user" not in raw:
|
|
202
248
|
raw["user"] = {"id": raw["self_id"]}
|
|
203
|
-
if "sn" not in raw:
|
|
204
|
-
raw["sn"] = 0
|
|
205
|
-
if "adapter" not in raw:
|
|
206
|
-
raw["adapter"] = "satori"
|
|
207
|
-
if "status" not in raw:
|
|
208
|
-
raw["status"] = LoginStatus.ONLINE
|
|
209
|
-
return super().parse(raw)
|
|
210
249
|
|
|
211
250
|
@property
|
|
212
251
|
def id(self) -> str:
|
|
213
252
|
return self.user.id
|
|
214
253
|
|
|
215
254
|
|
|
216
|
-
@dataclass
|
|
255
|
+
@dataclass(slots=True)
|
|
217
256
|
class LoginPartial(Login):
|
|
218
257
|
platform: str | None = None
|
|
219
258
|
user: User | None = None
|
|
220
259
|
|
|
221
260
|
|
|
222
|
-
@dataclass
|
|
261
|
+
@dataclass(slots=True)
|
|
223
262
|
class ArgvInteraction(ModelBase):
|
|
224
263
|
name: str
|
|
225
264
|
arguments: list
|
|
@@ -229,7 +268,7 @@ class ArgvInteraction(ModelBase):
|
|
|
229
268
|
return {"name": self.name, "arguments": self.arguments, "options": self.options}
|
|
230
269
|
|
|
231
270
|
|
|
232
|
-
@dataclass
|
|
271
|
+
@dataclass(slots=True)
|
|
233
272
|
class ButtonInteraction(ModelBase):
|
|
234
273
|
id: str
|
|
235
274
|
data: str | None = None
|
|
@@ -256,7 +295,7 @@ class Opcode(IntEnum):
|
|
|
256
295
|
"""元信息更新 (接收)"""
|
|
257
296
|
|
|
258
297
|
|
|
259
|
-
@dataclass
|
|
298
|
+
@dataclass(slots=True)
|
|
260
299
|
class Identify(ModelBase):
|
|
261
300
|
token: str | None = None
|
|
262
301
|
sn: int | None = None
|
|
@@ -265,7 +304,7 @@ class Identify(ModelBase):
|
|
|
265
304
|
def parse(cls, raw: dict):
|
|
266
305
|
if "sequence" in raw and "sn" not in raw:
|
|
267
306
|
raw["sn"] = raw["sequence"]
|
|
268
|
-
return
|
|
307
|
+
return cls(token=raw.get("token"), sn=raw.get("sn"))
|
|
269
308
|
|
|
270
309
|
@property
|
|
271
310
|
def sequence(self) -> int | None:
|
|
@@ -275,7 +314,7 @@ class Identify(ModelBase):
|
|
|
275
314
|
return {k: v for k, v in (("token", self.token), ("sn", self.sn)) if v is not None}
|
|
276
315
|
|
|
277
316
|
|
|
278
|
-
@dataclass
|
|
317
|
+
@dataclass(slots=True)
|
|
279
318
|
class Ready(ModelBase):
|
|
280
319
|
logins: list[LoginPartial]
|
|
281
320
|
proxy_urls: list[str] = field(default_factory=list)
|
|
@@ -286,7 +325,7 @@ class Ready(ModelBase):
|
|
|
286
325
|
return {"logins": [login.dump() for login in self.logins], "proxy_urls": self.proxy_urls}
|
|
287
326
|
|
|
288
327
|
|
|
289
|
-
@dataclass
|
|
328
|
+
@dataclass(slots=True)
|
|
290
329
|
class MetaPayload(ModelBase):
|
|
291
330
|
"""Meta 信令"""
|
|
292
331
|
|
|
@@ -296,7 +335,7 @@ class MetaPayload(ModelBase):
|
|
|
296
335
|
return {"proxy_urls": self.proxy_urls}
|
|
297
336
|
|
|
298
337
|
|
|
299
|
-
@dataclass
|
|
338
|
+
@dataclass(slots=True)
|
|
300
339
|
class Meta(ModelBase):
|
|
301
340
|
"""Meta 数据"""
|
|
302
341
|
|
|
@@ -309,7 +348,7 @@ class Meta(ModelBase):
|
|
|
309
348
|
return {"logins": [login.dump() for login in self.logins], "proxy_urls": self.proxy_urls}
|
|
310
349
|
|
|
311
350
|
|
|
312
|
-
@dataclass
|
|
351
|
+
@dataclass(slots=True)
|
|
313
352
|
class EmojiObject(ModelBase):
|
|
314
353
|
id: str
|
|
315
354
|
name: str | None = None
|
|
@@ -324,7 +363,7 @@ class EmojiObject(ModelBase):
|
|
|
324
363
|
return Emoji(self.id, self.name)
|
|
325
364
|
|
|
326
365
|
|
|
327
|
-
@dataclass
|
|
366
|
+
@dataclass(slots=True)
|
|
328
367
|
class MessageObject(ModelBase):
|
|
329
368
|
id: str
|
|
330
369
|
content: str = ""
|
|
@@ -336,6 +375,8 @@ class MessageObject(ModelBase):
|
|
|
336
375
|
updated_at: datetime | None = None
|
|
337
376
|
referrer: dict | None = None
|
|
338
377
|
|
|
378
|
+
_parsed_message: list[Element] | None = field(init=False, default=None, repr=False, compare=False, hash=False)
|
|
379
|
+
|
|
339
380
|
@classmethod
|
|
340
381
|
def from_elements(
|
|
341
382
|
cls,
|
|
@@ -355,10 +396,10 @@ class MessageObject(ModelBase):
|
|
|
355
396
|
|
|
356
397
|
@property
|
|
357
398
|
def message(self) -> list[Element]:
|
|
358
|
-
if
|
|
399
|
+
if self._parsed_message is not None:
|
|
359
400
|
return self._parsed_message
|
|
360
|
-
self._parsed_message = transform(parse(self.content))
|
|
361
|
-
return
|
|
401
|
+
self._parsed_message = msg = transform(parse(self.content))
|
|
402
|
+
return msg
|
|
362
403
|
|
|
363
404
|
@message.setter
|
|
364
405
|
def message(self, value: list[Element]):
|
|
@@ -366,11 +407,10 @@ class MessageObject(ModelBase):
|
|
|
366
407
|
self.content = "".join(str(i) for i in value)
|
|
367
408
|
|
|
368
409
|
@classmethod
|
|
369
|
-
def
|
|
410
|
+
def before_parse(cls, raw: dict):
|
|
370
411
|
if "elements" in raw and "content" not in raw:
|
|
371
412
|
content = [RawElement(*item.values()) for item in raw["elements"]]
|
|
372
413
|
raw["content"] = "".join(str(i) for i in content)
|
|
373
|
-
return super().parse(raw)
|
|
374
414
|
|
|
375
415
|
__converter__ = {
|
|
376
416
|
"channel": Channel.parse,
|
|
@@ -400,7 +440,7 @@ class MessageObject(ModelBase):
|
|
|
400
440
|
return res
|
|
401
441
|
|
|
402
442
|
|
|
403
|
-
@dataclass
|
|
443
|
+
@dataclass(slots=True)
|
|
404
444
|
class Event(ModelBase):
|
|
405
445
|
type: str
|
|
406
446
|
timestamp: datetime
|
|
@@ -438,7 +478,7 @@ class Event(ModelBase):
|
|
|
438
478
|
}
|
|
439
479
|
|
|
440
480
|
@classmethod
|
|
441
|
-
def
|
|
481
|
+
def before_parse(cls, raw: dict):
|
|
442
482
|
if "id" in raw and "sn" not in raw:
|
|
443
483
|
raw["sn"] = raw["id"]
|
|
444
484
|
if "platform" in raw and "self_id" in raw and "login" not in raw:
|
|
@@ -452,7 +492,6 @@ class Event(ModelBase):
|
|
|
452
492
|
if "login" not in raw:
|
|
453
493
|
raw["login"] = {"sn": 0, "status": LoginStatus.ONLINE, "platform": raw.get("platform", "unknown")}
|
|
454
494
|
raw["login"]["user"] = {"id": raw["self_id"]}
|
|
455
|
-
return super().parse(raw)
|
|
456
495
|
|
|
457
496
|
@property
|
|
458
497
|
def platform(self):
|
|
@@ -503,7 +542,7 @@ class Event(ModelBase):
|
|
|
503
542
|
T = TypeVar("T", bound=ModelBase)
|
|
504
543
|
|
|
505
544
|
|
|
506
|
-
@dataclass
|
|
545
|
+
@dataclass(slots=True)
|
|
507
546
|
class PageResult(ModelBase, Generic[T]):
|
|
508
547
|
data: list[T]
|
|
509
548
|
next: str | None = None
|
|
@@ -520,7 +559,7 @@ class PageResult(ModelBase, Generic[T]):
|
|
|
520
559
|
return res
|
|
521
560
|
|
|
522
561
|
|
|
523
|
-
@dataclass
|
|
562
|
+
@dataclass(slots=True)
|
|
524
563
|
class PageDequeResult(PageResult[T]):
|
|
525
564
|
prev: str | None = None
|
|
526
565
|
|
|
@@ -563,7 +602,7 @@ Direction: TypeAlias = Literal["before", "after", "around"]
|
|
|
563
602
|
Order: TypeAlias = Literal["asc", "desc"]
|
|
564
603
|
|
|
565
604
|
|
|
566
|
-
@dataclass
|
|
605
|
+
@dataclass(slots=True)
|
|
567
606
|
class Upload:
|
|
568
607
|
file: bytes | IO[bytes] | PathLike
|
|
569
608
|
mimetype: str = "image/png"
|
|
@@ -12,27 +12,37 @@ def escape(text: str, inline: bool = False) -> str:
|
|
|
12
12
|
return result.replace('"', """) if inline else result
|
|
13
13
|
|
|
14
14
|
|
|
15
|
+
uc_escape_pat1 = re.compile(r"&#(\d+);")
|
|
16
|
+
uc_escape_pat2 = re.compile(r"&#x([0-9a-f]+);")
|
|
17
|
+
uc_escape_pat3 = re.compile(r"&(amp|#38|#x26);")
|
|
18
|
+
|
|
19
|
+
|
|
15
20
|
def unescape(text: str) -> str:
|
|
16
21
|
result = text.replace("<", "<").replace(">", ">").replace(""", '"')
|
|
17
|
-
result =
|
|
18
|
-
result =
|
|
19
|
-
return
|
|
22
|
+
result = uc_escape_pat1.sub(lambda m: m[0] if m[1] == "38" else chr(int(m[1])), result)
|
|
23
|
+
result = uc_escape_pat2.sub(lambda m: m[0] if m[1] == "26" else chr(int(m[1], 16)), result)
|
|
24
|
+
return uc_escape_pat3.sub("&", result)
|
|
20
25
|
|
|
21
26
|
|
|
22
27
|
def uncapitalize(source: str) -> str:
|
|
23
|
-
return source[
|
|
28
|
+
return source[:1].lower() + source[1:]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
camel_pat = re.compile(r"[_-][a-z]")
|
|
32
|
+
param_pat = re.compile(r".[A-Z]+")
|
|
33
|
+
snake_pat = re.compile(r".[A-Z]")
|
|
24
34
|
|
|
25
35
|
|
|
26
36
|
def camel_case(source: str) -> str:
|
|
27
|
-
return
|
|
37
|
+
return camel_pat.sub(lambda mat: mat[0][1:].upper(), source)
|
|
28
38
|
|
|
29
39
|
|
|
30
40
|
def param_case(source: str) -> str:
|
|
31
|
-
return
|
|
41
|
+
return param_pat.sub(lambda mat: mat[0][0] + "-" + mat[0][1:].lower(), uncapitalize(source).replace("_", "-"))
|
|
32
42
|
|
|
33
43
|
|
|
34
44
|
def snake_case(source: str) -> str:
|
|
35
|
-
return
|
|
45
|
+
return snake_pat.sub(lambda mat: mat[0][0] + "_" + mat[0][1:].lower(), uncapitalize(source).replace("-", "_"))
|
|
36
46
|
|
|
37
47
|
|
|
38
48
|
def ensure_list(value: T | list[T] | None) -> list[T]:
|
|
@@ -49,9 +59,9 @@ def make_element(content: Union[str, bool, int, float, "Element"]) -> Optional["
|
|
|
49
59
|
if isinstance(content, Element):
|
|
50
60
|
return content
|
|
51
61
|
if isinstance(content, (bool, int, float)):
|
|
52
|
-
return Element(type="text", attrs={"text": str(content)})
|
|
62
|
+
return Element.parse(type="text", attrs={"text": str(content)})
|
|
53
63
|
if isinstance(content, str) and content:
|
|
54
|
-
return Element(type="text", attrs={"text": content})
|
|
64
|
+
return Element.parse(type="text", attrs={"text": content})
|
|
55
65
|
if content is not None:
|
|
56
66
|
raise ValueError(f"Invalid content: {content!r}")
|
|
57
67
|
|
|
@@ -68,7 +78,9 @@ class Element:
|
|
|
68
78
|
type: str
|
|
69
79
|
attrs: dict[str, Any]
|
|
70
80
|
children: list["Element"]
|
|
71
|
-
source: str | None
|
|
81
|
+
source: str | None
|
|
82
|
+
|
|
83
|
+
__slots__ = ("type", "attrs", "children", "source")
|
|
72
84
|
|
|
73
85
|
def __init__(
|
|
74
86
|
self,
|
|
@@ -99,6 +111,31 @@ class Element:
|
|
|
99
111
|
elif not self.attrs:
|
|
100
112
|
self.attrs["text"] = ""
|
|
101
113
|
|
|
114
|
+
@classmethod
|
|
115
|
+
def parse(
|
|
116
|
+
cls, type: str, attrs: dict[str, Any], children: list["Element"] | None = None, source: str | None = None
|
|
117
|
+
) -> "Element":
|
|
118
|
+
elem = cls.__new__(cls)
|
|
119
|
+
elem.type = type
|
|
120
|
+
elem.attrs = {}
|
|
121
|
+
elem.children = []
|
|
122
|
+
elem.source = source
|
|
123
|
+
for k, v in attrs.items():
|
|
124
|
+
if v is None:
|
|
125
|
+
continue
|
|
126
|
+
if k == "children":
|
|
127
|
+
elem.children.extend(ensure_list(v))
|
|
128
|
+
else:
|
|
129
|
+
elem.attrs[camel_case(k)] = v
|
|
130
|
+
if children:
|
|
131
|
+
elem.children.extend(children)
|
|
132
|
+
if type == "text":
|
|
133
|
+
if "content" in elem.attrs:
|
|
134
|
+
elem.attrs["text"] = elem.attrs.pop("content")
|
|
135
|
+
elif not elem.attrs:
|
|
136
|
+
elem.attrs["text"] = ""
|
|
137
|
+
return elem
|
|
138
|
+
|
|
102
139
|
def tag(self):
|
|
103
140
|
if self.type == "component":
|
|
104
141
|
if is_ := self.attrs.get("is"):
|
|
@@ -234,6 +271,9 @@ tag_pat2 = re.compile(
|
|
|
234
271
|
attr_pat1 = re.compile(r"([^\s=]+)(?:=\"(?P<value1>[^\"]*)\"|='(?P<value2>[^']*)')?", re.S)
|
|
235
272
|
attr_pat2 = re.compile(r"([^\s=]+)(?:=\"(?P<value1>[^\"]*)\"|='(?P<value2>[^']*)'|=\{(?P<curly>[^\}]+)\})?", re.S)
|
|
236
273
|
|
|
274
|
+
space_pat1 = re.compile(r"^\s*\n\s*", re.MULTILINE)
|
|
275
|
+
space_pat2 = re.compile(r"\s*\n\s*$", re.MULTILINE)
|
|
276
|
+
|
|
237
277
|
|
|
238
278
|
class Position(IntEnum):
|
|
239
279
|
OPEN = 0
|
|
@@ -242,7 +282,7 @@ class Position(IntEnum):
|
|
|
242
282
|
CONTINUE = 3
|
|
243
283
|
|
|
244
284
|
|
|
245
|
-
@dataclass
|
|
285
|
+
@dataclass(slots=True)
|
|
246
286
|
class Token:
|
|
247
287
|
type: Literal["angle", "curly"]
|
|
248
288
|
name: str
|
|
@@ -299,7 +339,7 @@ def parse_tokens(tokens: list[str | Token], context: dict | None = None) -> list
|
|
|
299
339
|
result: list[Element] = []
|
|
300
340
|
for token in tokens:
|
|
301
341
|
if isinstance(token, str):
|
|
302
|
-
result.append(Element(type="text", attrs={"text": token}))
|
|
342
|
+
result.append(Element.parse(type="text", attrs={"text": token}))
|
|
303
343
|
elif token.type == "angle":
|
|
304
344
|
attrs = {}
|
|
305
345
|
attr_pat = attr_pat2 if context is not None else attr_pat1
|
|
@@ -318,10 +358,10 @@ def parse_tokens(tokens: list[str | Token], context: dict | None = None) -> list
|
|
|
318
358
|
attrs[key] = True
|
|
319
359
|
token.extra = token.extra[mat.end() :]
|
|
320
360
|
result.append(
|
|
321
|
-
Element(
|
|
361
|
+
Element.parse(
|
|
322
362
|
token.name,
|
|
323
363
|
attrs,
|
|
324
|
-
|
|
364
|
+
parse_tokens(token.children["default"], context) if token.children else [],
|
|
325
365
|
)
|
|
326
366
|
)
|
|
327
367
|
elif not token.name:
|
|
@@ -351,9 +391,9 @@ def parse(src: str, context: dict | None = None):
|
|
|
351
391
|
def parse_content(source: str, _start: bool, _end: bool):
|
|
352
392
|
source = unescape(source)
|
|
353
393
|
if _start:
|
|
354
|
-
source =
|
|
394
|
+
source = space_pat1.sub("", source)
|
|
355
395
|
if _end:
|
|
356
|
-
source =
|
|
396
|
+
source = space_pat2.sub("", source)
|
|
357
397
|
push_text(source)
|
|
358
398
|
|
|
359
399
|
tag_pat = tag_pat2 if context is not None else tag_pat1
|
|
File without changes
|
|
@@ -24,10 +24,16 @@ try:
|
|
|
24
24
|
def encode(obj):
|
|
25
25
|
return encoder.encode(obj).decode()
|
|
26
26
|
|
|
27
|
+
def encode_bytes(obj):
|
|
28
|
+
return encoder.encode(obj)
|
|
29
|
+
|
|
27
30
|
except ImportError:
|
|
28
31
|
import json
|
|
29
32
|
|
|
30
33
|
def encode(obj):
|
|
31
34
|
return json.dumps(obj, separators=(",", ":"), ensure_ascii=False)
|
|
32
35
|
|
|
36
|
+
def encode_bytes(obj):
|
|
37
|
+
return json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
38
|
+
|
|
33
39
|
decode = json.loads
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|