transcript 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.
- transcript/__init__.py +112 -0
- transcript/builders/__init__.py +1 -0
- transcript/builders/html/__init__.py +6 -0
- transcript/builders/html/__init__.pyi +796 -0
- transcript/builders/html/args.py +25 -0
- transcript/builders/html/attrs.py +189 -0
- transcript/builders/html/html.py +81 -0
- transcript/builders/jinja.py +228 -0
- transcript/builders/js.py +280 -0
- transcript/builders/scss.py +393 -0
- transcript/builders/xml.py +166 -0
- transcript/core/__init__.py +14 -0
- transcript/core/ai.py +116 -0
- transcript/core/config.py +29 -0
- transcript/core/container.py +120 -0
- transcript/core/factory.py +180 -0
- transcript/core/fingerprint.py +265 -0
- transcript/core/meta.py +41 -0
- transcript/core/registers.py +53 -0
- transcript/core/stubs.py +19 -0
- transcript/io/__init__.py +12 -0
- transcript/io/file.py +40 -0
- transcript/io/hub.py +191 -0
- transcript/io/json_data.py +185 -0
- transcript/io/load.py +154 -0
- transcript/io/renderer.py +49 -0
- transcript/presets/__init__.py +63 -0
- transcript/presets/forms.py +108 -0
- transcript/presets/html.py +247 -0
- transcript/presets/jinja.py +119 -0
- transcript/presets/scss.py +221 -0
- transcript/presets/tailwind.py +392 -0
- transcript/project.py +223 -0
- transcript/purge.py +171 -0
- transcript/py.typed +0 -0
- transcript-0.4.0.dist-info/METADATA +201 -0
- transcript-0.4.0.dist-info/RECORD +40 -0
- transcript-0.4.0.dist-info/WHEEL +5 -0
- transcript-0.4.0.dist-info/licenses/LICENSE +21 -0
- transcript-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import string
|
|
4
|
+
from typing import Any, Iterable
|
|
5
|
+
|
|
6
|
+
FIRST_CHARS = string.ascii_lowercase # 26
|
|
7
|
+
SECOND_CHARS = string.ascii_lowercase + string.digits # 36
|
|
8
|
+
CODE_SPACE = len(FIRST_CHARS) * len(SECOND_CHARS) # 936
|
|
9
|
+
ENCODE_ALPHABET = string.ascii_lowercase + string.digits # base36
|
|
10
|
+
|
|
11
|
+
# Duża liczba pierwsza — utrzymuje stały rozmiar odcisku przy mieszaniu
|
|
12
|
+
FINGERPRINT_MODULUS = 2**61 - 1
|
|
13
|
+
|
|
14
|
+
# Pola instancji wpływające na wygenerowany kod (poza content/attrs/props)
|
|
15
|
+
_SIGNIFICANT_FIELDS: tuple[str, ...] = (
|
|
16
|
+
'expression', 'filters', 'statement', 'closing', 'text', 'template',
|
|
17
|
+
'selector', 'var_name', 'var_value', 'default', 'mixin_name', 'query',
|
|
18
|
+
'fn_name', 'args', 'arrow', 'async_', 'callee', 'class_name', 'element_name',
|
|
19
|
+
'modifier_name', 'block_name', 'header', 'condition', 'extends', 'method_name',
|
|
20
|
+
'clause', 'source', 'binding', 'semicolon', 'block', 'identifier', 'value',
|
|
21
|
+
'path', 'module', 'namespace', 'kind',
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _sieve_primes(limit: int) -> list[int]:
|
|
26
|
+
if limit < 2:
|
|
27
|
+
return []
|
|
28
|
+
marks = bytearray(b'\x01') * (limit + 1)
|
|
29
|
+
marks[0:2] = b'\x00\x00'
|
|
30
|
+
for i in range(2, int(limit**0.5) + 1):
|
|
31
|
+
if marks[i]:
|
|
32
|
+
for j in range(i * i, limit + 1, i):
|
|
33
|
+
marks[j] = 0
|
|
34
|
+
return [i for i in range(2, limit + 1) if marks[i]]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _nth_primes(count: int) -> list[int]:
|
|
38
|
+
limit = max(50, int(count * (count.bit_length() + 2)))
|
|
39
|
+
while True:
|
|
40
|
+
primes = _sieve_primes(limit)
|
|
41
|
+
if len(primes) >= count:
|
|
42
|
+
return primes[:count]
|
|
43
|
+
limit *= 2
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_PRIMES = _nth_primes(CODE_SPACE + 10_000)
|
|
47
|
+
ELEMENT_PRIMES = _PRIMES[:CODE_SPACE]
|
|
48
|
+
CONTENT_PRIMES = _PRIMES[CODE_SPACE:]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def index_to_code(index: int) -> str:
|
|
52
|
+
index %= CODE_SPACE
|
|
53
|
+
first = FIRST_CHARS[index // len(SECOND_CHARS)]
|
|
54
|
+
second = SECOND_CHARS[index % len(SECOND_CHARS)]
|
|
55
|
+
return f'{first}{second}'
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def code_to_index(code: str) -> int:
|
|
59
|
+
if len(code) != 2:
|
|
60
|
+
raise ValueError('Kod elementu musi mieć 2 znaki')
|
|
61
|
+
first, second = code[0], code[1]
|
|
62
|
+
if first not in FIRST_CHARS or second not in SECOND_CHARS:
|
|
63
|
+
raise ValueError(f'Nieprawidłowy kod elementu: {code!r}')
|
|
64
|
+
return FIRST_CHARS.index(first) * len(SECOND_CHARS) + SECOND_CHARS.index(second)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _stable_index(label: str, salt: bytes = b'') -> int:
|
|
68
|
+
h = 0xcbf29ce484222325
|
|
69
|
+
for byte in salt + label.encode('utf-8'):
|
|
70
|
+
h ^= byte
|
|
71
|
+
h = (h * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF
|
|
72
|
+
return h % CODE_SPACE
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def element_code(name: str) -> str:
|
|
76
|
+
"""2-znakowy kod podstawowego elementu (litera + litera/cyfra)."""
|
|
77
|
+
return index_to_code(_stable_index(name or 'anonymous', b'element:'))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def element_prime(name: str) -> int:
|
|
81
|
+
"""Liczba pierwsza przypisana do kodu elementu."""
|
|
82
|
+
return ELEMENT_PRIMES[code_to_index(element_code(name))]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def text_prime(value: Any) -> int:
|
|
86
|
+
"""Liczba pierwsza reprezentująca stałą treść / wartość."""
|
|
87
|
+
text = '' if value is None else str(value)
|
|
88
|
+
idx = _stable_index(text, b'text:')
|
|
89
|
+
slot = (_stable_index(text, b'text-slot:') + idx) % len(CONTENT_PRIMES)
|
|
90
|
+
return CONTENT_PRIMES[slot]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def mix(accumulator: int, value: int, position: int = 0) -> int:
|
|
94
|
+
"""Pozycyjne mieszanie liczb pierwszych (wielomian po module)."""
|
|
95
|
+
position_prime = CONTENT_PRIMES[position % len(CONTENT_PRIMES)]
|
|
96
|
+
return (accumulator * position_prime + int(value)) % FINGERPRINT_MODULUS
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def encode_fingerprint(value: int, *, minimum_length: int = 4) -> str:
|
|
100
|
+
"""Zapis odcisku w alfabecie [a-z0-9]."""
|
|
101
|
+
if value < 0:
|
|
102
|
+
value = -value
|
|
103
|
+
value %= FINGERPRINT_MODULUS
|
|
104
|
+
if value == 0:
|
|
105
|
+
digits = ['a']
|
|
106
|
+
else:
|
|
107
|
+
digits = []
|
|
108
|
+
n = value
|
|
109
|
+
base = len(ENCODE_ALPHABET)
|
|
110
|
+
while n:
|
|
111
|
+
n, rem = divmod(n, base)
|
|
112
|
+
digits.append(ENCODE_ALPHABET[rem])
|
|
113
|
+
digits.reverse()
|
|
114
|
+
encoded = ''.join(digits)
|
|
115
|
+
if len(encoded) < minimum_length:
|
|
116
|
+
encoded = encoded.rjust(minimum_length, 'a')
|
|
117
|
+
return encoded
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _attr_fingerprint(attr: Any) -> int:
|
|
121
|
+
name = getattr(attr, 'name', '')
|
|
122
|
+
raw = getattr(attr, 'value', None)
|
|
123
|
+
if raw is True or getattr(attr, '_boolean', False):
|
|
124
|
+
value: Any = True
|
|
125
|
+
else:
|
|
126
|
+
value = raw
|
|
127
|
+
acc = element_prime(f'attr:{name}')
|
|
128
|
+
return mix(acc, text_prime(value), 1)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _props_fingerprint(props: Iterable[Any]) -> int:
|
|
132
|
+
acc = element_prime('props')
|
|
133
|
+
for offset, prop in enumerate(props):
|
|
134
|
+
if not prop:
|
|
135
|
+
continue
|
|
136
|
+
name = getattr(prop, 'name', '')
|
|
137
|
+
value = getattr(prop, 'value', prop)
|
|
138
|
+
piece = mix(element_prime(f'prop:{name}'), text_prime(value), 1)
|
|
139
|
+
acc = mix(acc, piece, offset + 1)
|
|
140
|
+
return acc
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _fields_fingerprint(container: Any) -> int | None:
|
|
144
|
+
acc = element_prime('fields')
|
|
145
|
+
mixed = False
|
|
146
|
+
for offset, field in enumerate(_SIGNIFICANT_FIELDS):
|
|
147
|
+
if not hasattr(container, field):
|
|
148
|
+
continue
|
|
149
|
+
if field == 'selector':
|
|
150
|
+
# selektor jest obsługiwany osobno
|
|
151
|
+
continue
|
|
152
|
+
if field in {'name', 'content', 'attrs', 'props', 'uuid'}:
|
|
153
|
+
continue
|
|
154
|
+
value = getattr(container, field)
|
|
155
|
+
if value in (None, '', (), [], {}, False):
|
|
156
|
+
continue
|
|
157
|
+
if field == 'class_name' and getattr(container, 'name', '') in {'css_class', 'bem'}:
|
|
158
|
+
mixed = True
|
|
159
|
+
acc = mix(acc, text_prime(value), offset + 1)
|
|
160
|
+
continue
|
|
161
|
+
mixed = True
|
|
162
|
+
acc = mix(acc, text_prime(value), offset + 1)
|
|
163
|
+
return acc if mixed else None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def child_fingerprint(child: Any) -> int:
|
|
167
|
+
from transcript.core.container import ContainerBase
|
|
168
|
+
|
|
169
|
+
if isinstance(child, ContainerBase):
|
|
170
|
+
return structural_fingerprint(child)
|
|
171
|
+
if isinstance(child, tuple) and len(child) == 2:
|
|
172
|
+
return mix(text_prime(child[0]), text_prime(child[1]), 1)
|
|
173
|
+
if isinstance(child, dict):
|
|
174
|
+
acc = element_prime('mapping')
|
|
175
|
+
for offset, key in enumerate(sorted(child.keys(), key=str)):
|
|
176
|
+
piece = mix(text_prime(key), text_prime(child[key]), 1)
|
|
177
|
+
acc = mix(acc, piece, offset + 1)
|
|
178
|
+
return acc
|
|
179
|
+
build = getattr(child, 'build', None)
|
|
180
|
+
if callable(build):
|
|
181
|
+
try:
|
|
182
|
+
return text_prime(build())
|
|
183
|
+
except TypeError:
|
|
184
|
+
try:
|
|
185
|
+
return text_prime(build(depth=0))
|
|
186
|
+
except TypeError:
|
|
187
|
+
return text_prime(child)
|
|
188
|
+
return text_prime(child)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def structural_fingerprint(container: Any) -> int:
|
|
192
|
+
"""Liczbowy odcisk struktury kontenera (nazwa + atrybuty + ciało)."""
|
|
193
|
+
name = getattr(container, 'name', None) or container.__class__.__name__
|
|
194
|
+
acc = element_prime(str(name))
|
|
195
|
+
|
|
196
|
+
selector = getattr(container, 'selector', None)
|
|
197
|
+
if isinstance(selector, str) and selector:
|
|
198
|
+
acc = mix(acc, text_prime(selector), 1)
|
|
199
|
+
|
|
200
|
+
class_name = getattr(container, 'class_name', None)
|
|
201
|
+
if isinstance(class_name, str) and class_name:
|
|
202
|
+
acc = mix(acc, text_prime(class_name), 2)
|
|
203
|
+
|
|
204
|
+
fields = _fields_fingerprint(container)
|
|
205
|
+
if fields is not None:
|
|
206
|
+
acc = mix(acc, fields, 3)
|
|
207
|
+
|
|
208
|
+
attrs = getattr(container, 'attrs', None)
|
|
209
|
+
if attrs:
|
|
210
|
+
for offset, attr in enumerate(attrs):
|
|
211
|
+
if attr:
|
|
212
|
+
acc = mix(acc, _attr_fingerprint(attr), offset + 4)
|
|
213
|
+
|
|
214
|
+
props = getattr(container, 'props', None)
|
|
215
|
+
if props:
|
|
216
|
+
acc = mix(acc, _props_fingerprint(props), 12)
|
|
217
|
+
|
|
218
|
+
content = getattr(container, 'content', None) or []
|
|
219
|
+
for offset, child in enumerate(content):
|
|
220
|
+
acc = mix(acc, child_fingerprint(child), offset + 16)
|
|
221
|
+
|
|
222
|
+
return acc
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def is_atomic(container: Any) -> bool:
|
|
226
|
+
"""Sam znacznik/typ bez atrybutów, propsów, pól i ciała → kod 2-znakowy."""
|
|
227
|
+
if getattr(container, 'content', None):
|
|
228
|
+
return False
|
|
229
|
+
attrs = getattr(container, 'attrs', None)
|
|
230
|
+
if attrs and any(attrs):
|
|
231
|
+
return False
|
|
232
|
+
props = getattr(container, 'props', None)
|
|
233
|
+
if props and any(props):
|
|
234
|
+
return False
|
|
235
|
+
if _fields_fingerprint(container) is not None:
|
|
236
|
+
return False
|
|
237
|
+
selector = getattr(container, 'selector', None)
|
|
238
|
+
name = getattr(container, 'name', None) or ''
|
|
239
|
+
if isinstance(selector, str) and selector and selector not in {'', '&', name}:
|
|
240
|
+
# czysty SCSS('.x') / CSSClass — selektor różnicuje tożsamość, nie jest atomem tagu
|
|
241
|
+
return False
|
|
242
|
+
if getattr(container, 'class_name', None):
|
|
243
|
+
return False
|
|
244
|
+
return True
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def content_id(container: Any) -> str:
|
|
248
|
+
"""Publiczny identyfikator: 2 znaki dla atomu, dłuższy kod dla złożonych drzew."""
|
|
249
|
+
name = getattr(container, 'name', None) or container.__class__.__name__
|
|
250
|
+
if is_atomic(container):
|
|
251
|
+
return element_code(str(name))
|
|
252
|
+
return encode_fingerprint(structural_fingerprint(container), minimum_length=8)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def short_uuid(length: int = 8) -> str:
|
|
256
|
+
"""Alias wsteczny — stały kod z liczby pierwszej etykiety ``short-uuid``."""
|
|
257
|
+
return encode_fingerprint(element_prime('short-uuid'), minimum_length=max(6, min(8, length)))
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
__all__ = [
|
|
261
|
+
'FIRST_CHARS', 'SECOND_CHARS', 'CODE_SPACE', 'ELEMENT_PRIMES',
|
|
262
|
+
'element_code', 'element_prime', 'text_prime', 'mix',
|
|
263
|
+
'encode_fingerprint', 'structural_fingerprint', 'content_id',
|
|
264
|
+
'child_fingerprint', 'is_atomic', 'short_uuid',
|
|
265
|
+
]
|
transcript/core/meta.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
from typing import List, Protocol, Dict, Any, Tuple, Type
|
|
3
|
+
from transcript.core.config import Config, get_config
|
|
4
|
+
from abc import ABCMeta, ABC
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ContainerProtocol(Protocol):
|
|
8
|
+
|
|
9
|
+
def build(self, depth: int = 0) -> str: ...
|
|
10
|
+
|
|
11
|
+
def __lshift__(self, data: Any) -> ContainerProtocol: ...
|
|
12
|
+
|
|
13
|
+
def __rshift__(self, dest: Any) -> str: ...
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ContainerMeta(ABCMeta):
|
|
17
|
+
|
|
18
|
+
_config: Config | None = None
|
|
19
|
+
|
|
20
|
+
def __new__(mcls:Type[type], name:str, bases:Tuple[type, ...], attrs:Dict[str, Any]):
|
|
21
|
+
|
|
22
|
+
is_abstract_base = name.endswith(('Base', 'Abstract', 'Mixin')) and name not in ("Base", "Abstract")
|
|
23
|
+
|
|
24
|
+
class_name = name
|
|
25
|
+
inherited_name = any(hasattr(base, 'name') for base in bases)
|
|
26
|
+
if not is_abstract_base and 'name' not in attrs and not inherited_name:
|
|
27
|
+
raise TypeError('The construction class must contain a "name" attribute')
|
|
28
|
+
cls = ABCMeta.__new__(mcls, class_name, bases, attrs)
|
|
29
|
+
return cls
|
|
30
|
+
|
|
31
|
+
def __call__(cls, *args: Any, **kwds: Any) -> Any:
|
|
32
|
+
is_abstract_base = cls.__name__.endswith(('Base', 'Abstract'))
|
|
33
|
+
if is_abstract_base:
|
|
34
|
+
raise TypeError('You cannot create objects of abstract classes')
|
|
35
|
+
return super().__call__(*args, **kwds)
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def config(cls):
|
|
39
|
+
if cls._config is None:
|
|
40
|
+
cls._config = get_config()
|
|
41
|
+
return cls._config
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import weakref
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from functools import wraps
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Registry:
|
|
7
|
+
_instances = weakref.WeakValueDictionary()
|
|
8
|
+
|
|
9
|
+
@classmethod
|
|
10
|
+
def get(cls, path: Path):
|
|
11
|
+
return cls._instances.get(path.resolve())
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def set(cls, path:Path, instance):
|
|
15
|
+
cls._instances[path.resolve()] = instance
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RegistryDecorator:
|
|
19
|
+
"""Bazowy dekorator do tworzenia singletonów w obrębie rejestru."""
|
|
20
|
+
registry: Registry|None = None
|
|
21
|
+
key_func = None # funkcja wyciągająca klucz z argumentów __new__
|
|
22
|
+
|
|
23
|
+
def __init__(self, cls):
|
|
24
|
+
self.cls = cls
|
|
25
|
+
if self.registry is None:
|
|
26
|
+
raise ValueError("RegistryDecorator wymaga atrybutu 'registry'")
|
|
27
|
+
if self.key_func is None:
|
|
28
|
+
raise ValueError("RegistryDecorator wymaga atrybutu 'key_func'")
|
|
29
|
+
self._patch_new()
|
|
30
|
+
|
|
31
|
+
def _patch_new(self):
|
|
32
|
+
orig_new = self.cls.__new__
|
|
33
|
+
registry = self.registry
|
|
34
|
+
key_func = self.key_func
|
|
35
|
+
|
|
36
|
+
@wraps(orig_new)
|
|
37
|
+
def __new__(subcls, *args, **kwargs):
|
|
38
|
+
key:str|None = None
|
|
39
|
+
if key_func is not None and registry is not None:
|
|
40
|
+
key = key_func(*args, **kwargs)
|
|
41
|
+
existing = registry.get(key)
|
|
42
|
+
if existing:
|
|
43
|
+
return existing
|
|
44
|
+
instance = orig_new(subcls)
|
|
45
|
+
if registry is not None and key is not None:
|
|
46
|
+
registry.set(key, instance)
|
|
47
|
+
return instance
|
|
48
|
+
|
|
49
|
+
self.cls.__new__ = __new__
|
|
50
|
+
|
|
51
|
+
def __call__(self, *args, **kwargs):
|
|
52
|
+
# dekorator działa jak normalna klasa
|
|
53
|
+
return self.cls(*args, **kwargs)
|
transcript/core/stubs.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import weakref
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from functools import wraps
|
|
4
|
+
from transcript.core.registers import RegistryDecorator, Registry
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
stubs_registry = Registry()
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RegisterStubs(RegistryDecorator):
|
|
11
|
+
registry = stubs_registry
|
|
12
|
+
key_func = staticmethod(lambda path, *a, **kw: Path(path).resolve())
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@RegisterStubs
|
|
16
|
+
class Stubs:
|
|
17
|
+
|
|
18
|
+
def __init__(self, file_using_factory, pyi_path):
|
|
19
|
+
print('stubs:', file_using_factory)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Źródła i cele przepływu danych dla operatorów ``<<`` / ``>>``."""
|
|
2
|
+
|
|
3
|
+
from transcript.io.file import File
|
|
4
|
+
from transcript.io.hub import Hub, HubError
|
|
5
|
+
from transcript.io.json_data import JsonData
|
|
6
|
+
from transcript.io.load import data_to_container, html_to_data, load
|
|
7
|
+
from transcript.io.renderer import Renderer
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
'File', 'JsonData', 'Renderer', 'Hub', 'HubError',
|
|
11
|
+
'load', 'html_to_data', 'data_to_container',
|
|
12
|
+
]
|
transcript/io/file.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from transcript.core.container import ContainerBase
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class File:
|
|
11
|
+
"""Źródło lub cel plikowy dla operatorów ``<<`` / ``>>``.
|
|
12
|
+
|
|
13
|
+
``container << File('partial.html')`` — wczytuje treść pliku do ciała kontenera.
|
|
14
|
+
``container >> File('out.html')`` — zapisuje wygenerowany kod do pliku.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, path: str | Path, encoding: str = 'utf-8'):
|
|
18
|
+
self.path = Path(path)
|
|
19
|
+
self.encoding = encoding
|
|
20
|
+
|
|
21
|
+
def read(self) -> str:
|
|
22
|
+
return self.path.read_text(encoding=self.encoding)
|
|
23
|
+
|
|
24
|
+
def write(self, code: str) -> str:
|
|
25
|
+
if self.path.parent.as_posix() not in ('', '.'):
|
|
26
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
27
|
+
self.path.write_text(code, encoding=self.encoding)
|
|
28
|
+
return code
|
|
29
|
+
|
|
30
|
+
def inject_into(self, container: ContainerBase) -> None:
|
|
31
|
+
container._inject(self.read())
|
|
32
|
+
|
|
33
|
+
def export_from(self, container: ContainerBase, code: str) -> str:
|
|
34
|
+
return self.write(code)
|
|
35
|
+
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return f'{self.__class__.__name__}({str(self.path)!r})'
|
|
38
|
+
|
|
39
|
+
def __fspath__(self) -> str:
|
|
40
|
+
return str(self.path)
|
transcript/io/hub.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Mapping
|
|
8
|
+
from urllib.error import HTTPError, URLError
|
|
9
|
+
from urllib.parse import quote, urljoin
|
|
10
|
+
from urllib.request import Request, urlopen
|
|
11
|
+
|
|
12
|
+
from transcript.io.json_data import JsonData
|
|
13
|
+
|
|
14
|
+
ENV_URL_KEYS = ('TRANSCRIPT_HUB_URL', 'HUB_URL')
|
|
15
|
+
ENV_TOKEN_KEYS = ('TRANSCRIPT_HUB_TOKEN', 'HUB_TOKEN')
|
|
16
|
+
ENV_API_KEY_KEYS = ('TRANSCRIPT_HUB_API_KEY', 'HUB_API_KEY')
|
|
17
|
+
ENV_USER_KEYS = ('TRANSCRIPT_HUB_USERNAME', 'HUB_USERNAME')
|
|
18
|
+
ENV_PASSWORD_KEYS = ('TRANSCRIPT_HUB_PASSWORD', 'HUB_PASSWORD')
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HubError(RuntimeError):
|
|
22
|
+
"""Błąd komunikacji z hubem prebuildów."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, *, status: int | None = None, payload: Any = None):
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.status = status
|
|
27
|
+
self.payload = payload
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Hub:
|
|
31
|
+
"""Klient API huba/sklepu z prebuildami kodu.
|
|
32
|
+
|
|
33
|
+
Adres i dane uwierzytelniające można podać w konstruktorze albo przez ``.env``:
|
|
34
|
+
|
|
35
|
+
* ``TRANSCRIPT_HUB_URL`` / ``HUB_URL``
|
|
36
|
+
* ``TRANSCRIPT_HUB_TOKEN`` / ``HUB_TOKEN`` (Bearer)
|
|
37
|
+
* ``TRANSCRIPT_HUB_API_KEY`` / ``HUB_API_KEY``
|
|
38
|
+
* ``TRANSCRIPT_HUB_USERNAME`` / ``HUB_USERNAME``
|
|
39
|
+
* ``TRANSCRIPT_HUB_PASSWORD`` / ``HUB_PASSWORD``
|
|
40
|
+
|
|
41
|
+
Przykład::
|
|
42
|
+
|
|
43
|
+
hub = Hub() # z .env
|
|
44
|
+
data = hub.get('hero-card')
|
|
45
|
+
div << data
|
|
46
|
+
hub.post(page >> JsonData(), prebuild_id='my-page')
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
url: str | None = None,
|
|
52
|
+
token: str | None = None,
|
|
53
|
+
*,
|
|
54
|
+
api_key: str | None = None,
|
|
55
|
+
username: str | None = None,
|
|
56
|
+
password: str | None = None,
|
|
57
|
+
env_file: str | Path | None = '.env',
|
|
58
|
+
timeout: float = 30.0,
|
|
59
|
+
prebuilds_path: str = 'prebuilds',
|
|
60
|
+
):
|
|
61
|
+
self._load_env(env_file)
|
|
62
|
+
self.url = (url or self._env_first(ENV_URL_KEYS) or '').rstrip('/') + '/'
|
|
63
|
+
self.token = token if token is not None else self._env_first(ENV_TOKEN_KEYS)
|
|
64
|
+
self.api_key = api_key if api_key is not None else self._env_first(ENV_API_KEY_KEYS)
|
|
65
|
+
self.username = username if username is not None else self._env_first(ENV_USER_KEYS)
|
|
66
|
+
self.password = password if password is not None else self._env_first(ENV_PASSWORD_KEYS)
|
|
67
|
+
self.timeout = timeout
|
|
68
|
+
self.prebuilds_path = prebuilds_path.strip('/')
|
|
69
|
+
|
|
70
|
+
if not self.url.strip('/'):
|
|
71
|
+
raise HubError(
|
|
72
|
+
'Brak adresu huba — podaj url=... albo ustaw TRANSCRIPT_HUB_URL / HUB_URL w .env'
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
@staticmethod
|
|
76
|
+
def _load_env(env_file: str | Path | None) -> None:
|
|
77
|
+
if env_file is None:
|
|
78
|
+
return
|
|
79
|
+
path = Path(env_file)
|
|
80
|
+
if not path.is_file():
|
|
81
|
+
return
|
|
82
|
+
try:
|
|
83
|
+
from dotenv import load_dotenv
|
|
84
|
+
except ImportError:
|
|
85
|
+
return
|
|
86
|
+
load_dotenv(path, override=False)
|
|
87
|
+
|
|
88
|
+
@staticmethod
|
|
89
|
+
def _env_first(keys: tuple[str, ...]) -> str | None:
|
|
90
|
+
for key in keys:
|
|
91
|
+
value = os.environ.get(key)
|
|
92
|
+
if value:
|
|
93
|
+
return value
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
def _endpoint(self, *parts: str) -> str:
|
|
97
|
+
suffix = '/'.join(quote(part.strip('/'), safe='') for part in parts if part)
|
|
98
|
+
return urljoin(self.url, f'{self.prebuilds_path}/{suffix}'.rstrip('/'))
|
|
99
|
+
|
|
100
|
+
def _headers(self, *, json_body: bool = False) -> dict[str, str]:
|
|
101
|
+
headers = {'Accept': 'application/json'}
|
|
102
|
+
if json_body:
|
|
103
|
+
headers['Content-Type'] = 'application/json'
|
|
104
|
+
if self.token:
|
|
105
|
+
headers['Authorization'] = f'Bearer {self.token}'
|
|
106
|
+
elif self.api_key:
|
|
107
|
+
headers['X-API-Key'] = self.api_key
|
|
108
|
+
elif self.username is not None:
|
|
109
|
+
raw = f'{self.username}:{self.password or ""}'.encode('utf-8')
|
|
110
|
+
headers['Authorization'] = f'Basic {base64.b64encode(raw).decode("ascii")}'
|
|
111
|
+
return headers
|
|
112
|
+
|
|
113
|
+
def _request(
|
|
114
|
+
self,
|
|
115
|
+
method: str,
|
|
116
|
+
url: str,
|
|
117
|
+
*,
|
|
118
|
+
body: Mapping[str, Any] | list[Any] | None = None,
|
|
119
|
+
) -> Any:
|
|
120
|
+
data = None
|
|
121
|
+
headers = self._headers(json_body=body is not None)
|
|
122
|
+
if body is not None:
|
|
123
|
+
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
|
124
|
+
request = Request(url, data=data, headers=headers, method=method.upper())
|
|
125
|
+
try:
|
|
126
|
+
with urlopen(request, timeout=self.timeout) as response:
|
|
127
|
+
raw = response.read().decode('utf-8')
|
|
128
|
+
if not raw.strip():
|
|
129
|
+
return {}
|
|
130
|
+
return json.loads(raw)
|
|
131
|
+
except HTTPError as exc:
|
|
132
|
+
detail: Any = None
|
|
133
|
+
try:
|
|
134
|
+
detail = json.loads(exc.read().decode('utf-8'))
|
|
135
|
+
except Exception:
|
|
136
|
+
detail = None
|
|
137
|
+
raise HubError(
|
|
138
|
+
f'Hub {method.upper()} {url} zakończył się statusem {exc.code}',
|
|
139
|
+
status=exc.code,
|
|
140
|
+
payload=detail,
|
|
141
|
+
) from exc
|
|
142
|
+
except URLError as exc:
|
|
143
|
+
raise HubError(f'Nie udało się połączyć z hubem: {exc.reason}') from exc
|
|
144
|
+
except json.JSONDecodeError as exc:
|
|
145
|
+
raise HubError(f'Hub zwrócił niepoprawny JSON: {exc}') from exc
|
|
146
|
+
|
|
147
|
+
@staticmethod
|
|
148
|
+
def _as_json_data(payload: Any) -> JsonData:
|
|
149
|
+
if isinstance(payload, dict):
|
|
150
|
+
if 'data' in payload and isinstance(payload['data'], (dict, list)):
|
|
151
|
+
return JsonData(payload['data'])
|
|
152
|
+
if 'prebuild' in payload and isinstance(payload['prebuild'], (dict, list)):
|
|
153
|
+
return JsonData(payload['prebuild'])
|
|
154
|
+
return JsonData(payload)
|
|
155
|
+
if isinstance(payload, list):
|
|
156
|
+
return JsonData(payload)
|
|
157
|
+
raise HubError('Oczekiwano obiektu lub tablicy JSON z prebuildem', payload=payload)
|
|
158
|
+
|
|
159
|
+
def get(self, prebuild_id: str) -> JsonData:
|
|
160
|
+
"""Pobiera prebuild o podanym ``id`` i zwraca go jako ``JsonData``."""
|
|
161
|
+
if not prebuild_id:
|
|
162
|
+
raise HubError('prebuild_id nie może być puste')
|
|
163
|
+
payload = self._request('GET', self._endpoint(prebuild_id))
|
|
164
|
+
return self._as_json_data(payload)
|
|
165
|
+
|
|
166
|
+
def post(
|
|
167
|
+
self,
|
|
168
|
+
data: JsonData | Mapping[str, Any] | list[Any],
|
|
169
|
+
prebuild_id: str | None = None,
|
|
170
|
+
**meta: Any,
|
|
171
|
+
) -> JsonData:
|
|
172
|
+
"""Wysyła ``JsonData`` (prebuild) do huba.
|
|
173
|
+
|
|
174
|
+
Opcjonalne ``prebuild_id`` oraz dodatkowe pola ``meta`` trafiają do body żądania.
|
|
175
|
+
"""
|
|
176
|
+
if isinstance(data, JsonData):
|
|
177
|
+
content = data.data
|
|
178
|
+
else:
|
|
179
|
+
content = data
|
|
180
|
+
body: dict[str, Any] = {'data': content}
|
|
181
|
+
if prebuild_id:
|
|
182
|
+
body['id'] = prebuild_id
|
|
183
|
+
if meta:
|
|
184
|
+
body.update(meta)
|
|
185
|
+
url = self._endpoint(prebuild_id) if prebuild_id else self._endpoint()
|
|
186
|
+
payload = self._request('POST', url, body=body)
|
|
187
|
+
return self._as_json_data(payload)
|
|
188
|
+
|
|
189
|
+
def __repr__(self) -> str:
|
|
190
|
+
auth = 'token' if self.token else 'api_key' if self.api_key else 'basic' if self.username else 'none'
|
|
191
|
+
return f'{self.__class__.__name__}(url={self.url!r}, auth={auth!r})'
|