htmlxify 1.0.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.
@@ -0,0 +1,241 @@
1
+ """
2
+ Semantic Validator - Checks AST for errors and warnings
3
+ Security: Ensures no emoji identifiers, validates backend calls
4
+ """
5
+
6
+ import re
7
+ from typing import List, Dict, Any, Optional
8
+
9
+
10
+ class ValidationIssue:
11
+ """Represents an error or warning"""
12
+
13
+ def __init__(
14
+ self,
15
+ node: Dict[str, Any],
16
+ message: str,
17
+ severity: str = 'error',
18
+ line: Optional[int] = None
19
+ ):
20
+ self.node = node
21
+ self.message = message
22
+ self.severity = severity # 'error' or 'warning'
23
+ self.line = line or node.get('meta', {}).get('line', 0)
24
+
25
+ def __repr__(self):
26
+ return f"<{self.severity.upper()}: {self.message}>"
27
+
28
+
29
+ class SemanticValidator:
30
+ """
31
+ Validates the AST for:
32
+ - Invalid identifiers (emojis, special characters)
33
+ - Performance anti-patterns
34
+ - Security issues
35
+ - Component naming conventions
36
+ """
37
+
38
+ # Valid identifier pattern (JavaScript-compatible)
39
+ IDENTIFIER_PATTERN = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_-]*$')
40
+
41
+ # Component name pattern (must have hyphen)
42
+ COMPONENT_PATTERN = re.compile(r'^[a-z]+-[a-z-]+$')
43
+
44
+ def __init__(self, ast: Dict[str, Any], filename: str):
45
+ self.ast = ast
46
+ self.filename = filename
47
+ self.errors: List[ValidationIssue] = []
48
+ self.warnings: List[ValidationIssue] = []
49
+
50
+ def validate(self) -> bool:
51
+ """
52
+ Run all validation checks.
53
+ Returns True if valid, False if errors found.
54
+ Warnings don't prevent compilation.
55
+ """
56
+ self._walk_ast(self.ast)
57
+
58
+ # Report issues
59
+ if self.errors:
60
+ self._report_issues('ERRORS', self.errors)
61
+ return False
62
+
63
+ if self.warnings:
64
+ self._report_issues('WARNINGS', self.warnings)
65
+
66
+ return True
67
+
68
+ def _walk_ast(self, node: Any):
69
+ """Recursively walk AST and validate each node"""
70
+ if not isinstance(node, dict):
71
+ return
72
+
73
+ # Validate this node
74
+ if node.get('type') == 'Element':
75
+ self._validate_element(node)
76
+ elif node.get('type') == 'Text':
77
+ self._validate_text(node)
78
+
79
+ # Recurse into children
80
+ for child in node.get('children', []):
81
+ self._walk_ast(child)
82
+
83
+ def _validate_element(self, node: Dict[str, Any]):
84
+ """Validate element node"""
85
+
86
+ # 1. Validate ID (NO EMOJIS)
87
+ element_id = node.get('id')
88
+ if element_id:
89
+ if not self.IDENTIFIER_PATTERN.match(element_id):
90
+ self.errors.append(ValidationIssue(
91
+ node,
92
+ f"Invalid ID '{element_id}'. "
93
+ f"Use only alphanumeric characters, hyphens, and underscores. "
94
+ f"Emojis are NOT allowed in identifiers.",
95
+ severity='error'
96
+ ))
97
+
98
+ # 2. Validate class names
99
+ for cls in node.get('classes', []):
100
+ if not self.IDENTIFIER_PATTERN.match(cls):
101
+ self.errors.append(ValidationIssue(
102
+ node,
103
+ f"Invalid class name '{cls}'. "
104
+ f"No emojis or special characters allowed.",
105
+ severity='error'
106
+ ))
107
+
108
+ # 3. Check component naming
109
+ tag = node.get('tag', '')
110
+ if 'component' in tag.lower() or '-' in tag:
111
+ # This is a custom component
112
+ if not self.COMPONENT_PATTERN.match(tag):
113
+ self.errors.append(ValidationIssue(
114
+ node,
115
+ f"Component names must be lowercase with hyphen: '{tag}' → 'my-component'",
116
+ severity='error'
117
+ ))
118
+
119
+ # 4. Performance warnings
120
+ self._check_performance(node)
121
+
122
+ # 5. Security checks
123
+ self._check_security(node)
124
+
125
+ def _check_performance(self, node: Dict[str, Any]):
126
+ """Check for performance anti-patterns"""
127
+ attrs = node.get('attributes', {})
128
+
129
+ # Check if animating non-GPU properties
130
+ animate = attrs.get('animate')
131
+ if animate:
132
+ # Warn if animate is defined but might not use GPU
133
+ self.warnings.append(ValidationIssue(
134
+ node,
135
+ "Animation detected. Ensure you use 'transform' and 'opacity' "
136
+ "for GPU acceleration. Avoid animating 'left', 'top', 'width', 'height'.",
137
+ severity='warning'
138
+ ))
139
+
140
+ # Check inline styles for bad properties
141
+ style = attrs.get('style', '')
142
+ bad_props = ['left', 'top', 'width', 'height']
143
+
144
+ if isinstance(style, str):
145
+ for prop in bad_props:
146
+ if prop in style.lower():
147
+ self.warnings.append(ValidationIssue(
148
+ node,
149
+ f"Animating '{prop}' causes layout recalculation. "
150
+ f"Use 'transform' instead for better performance.",
151
+ severity='warning'
152
+ ))
153
+
154
+ def _check_security(self, node: Dict[str, Any]):
155
+ """Check security issues"""
156
+ attrs = node.get('attributes', {})
157
+
158
+ # Mark nodes with dynamic data for sanitization
159
+ if '⚡-data' in attrs:
160
+ node['_needs_sanitization'] = True
161
+ data_attr = attrs['⚡-data']
162
+ if isinstance(data_attr, dict):
163
+ data_attr = data_attr.get('key', 'unknown')
164
+ node['_sanitize_key'] = str(data_attr)
165
+
166
+ # Validate backend call endpoints
167
+ if '⚡-call' in attrs:
168
+ endpoint = attrs['⚡-call']
169
+ if isinstance(endpoint, dict):
170
+ endpoint = endpoint.get('endpoint', '')
171
+ endpoint = str(endpoint)
172
+
173
+ # Check for suspicious patterns
174
+ if any(char in endpoint for char in ['..', '/', '\\']):
175
+ self.warnings.append(ValidationIssue(
176
+ node,
177
+ f"Backend endpoint '{endpoint}' contains suspicious characters. "
178
+ f"Ensure this is intentional.",
179
+ severity='warning'
180
+ ))
181
+
182
+ def _validate_text(self, node: Dict[str, Any]):
183
+ """Validate text node"""
184
+ text = node.get('value', '')
185
+
186
+ # Check for extremely long text (might be a paste error)
187
+ if len(text) > 10000:
188
+ self.warnings.append(ValidationIssue(
189
+ node,
190
+ f"Text content is extremely long ({len(text)} chars). "
191
+ f"Consider moving to external content.",
192
+ severity='warning'
193
+ ))
194
+
195
+ def _report_issues(self, category: str, issues: List[ValidationIssue]):
196
+ """Pretty-print validation issues"""
197
+ symbol = '❌' if category == 'ERRORS' else '⚠️ '
198
+
199
+ print(f"\n{symbol} {category} in {self.filename}:\n")
200
+
201
+ for i, issue in enumerate(issues, 1):
202
+ print(f"{i}. {issue.message}")
203
+ if issue.line:
204
+ print(f" Line: {issue.line}")
205
+ print()
206
+
207
+
208
+ # Test
209
+ if __name__ == '__main__':
210
+ # Test with invalid code
211
+ test_ast = {
212
+ 'type': 'Document',
213
+ 'children': [
214
+ {
215
+ 'type': 'Element',
216
+ 'tag': 'div',
217
+ 'id': '🎨', # INVALID - emoji
218
+ 'classes': ['valid-class'],
219
+ 'attributes': {},
220
+ 'children': [],
221
+ 'meta': {'line': 1}
222
+ },
223
+ {
224
+ 'type': 'Element',
225
+ 'tag': 'MyComponent', # INVALID - should be my-component
226
+ 'id': 'test',
227
+ 'classes': [],
228
+ 'attributes': {
229
+ 'animate': 'fade 1s',
230
+ 'style': 'left: 100px' # WARNING - bad for animation
231
+ },
232
+ 'children': [],
233
+ 'meta': {'line': 5}
234
+ }
235
+ ]
236
+ }
237
+
238
+ validator = SemanticValidator(test_ast, 'test.htmlxify')
239
+ result = validator.validate()
240
+
241
+ print(f"\nValidation result: {'✅ PASSED' if result else '❌ FAILED'}")