sdui-python 1.0.7__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.
bin/component-cli.js ADDED
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname, join } from 'path';
5
+
6
+ // Calculate the correct path to dist directory
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ const distPath = join(__dirname, '..', 'dist', 'python-package.esm.js');
10
+ const { getAvailableComponents, isValidComponentType, validateComponentStructure, getAllCommonProperties, getCategorizedCommonProperties, getAllThemes } = await import(distPath);
11
+
12
+ // Handle JSON input from stdin
13
+ async function readStdin() {
14
+ return new Promise((resolve) => {
15
+ let data = '';
16
+ process.stdin.setEncoding('utf8');
17
+ process.stdin.on('readable', () => {
18
+ let chunk;
19
+ while ((chunk = process.stdin.read()) !== null) {
20
+ data += chunk;
21
+ }
22
+ });
23
+ process.stdin.on('end', () => {
24
+ resolve(data);
25
+ });
26
+ });
27
+ }
28
+
29
+ async function main() {
30
+ const args = process.argv.slice(2);
31
+ const command = args[0];
32
+
33
+ try {
34
+ switch (command) {
35
+ case '--available':
36
+ // Return list of available components with their properties
37
+ const components = getAvailableComponents();
38
+ console.log(JSON.stringify(components));
39
+ break;
40
+
41
+ case '--validate':
42
+ // Validate component type
43
+ const componentType = args[1] || '';
44
+ const isValid = isValidComponentType(componentType);
45
+ console.log(JSON.stringify({ isValid }));
46
+ break;
47
+
48
+ case '--validate-structure':
49
+ // Validate component structure
50
+ const inputData = await readStdin();
51
+ if (!inputData.trim()) {
52
+ console.error('Component JSON is required');
53
+ process.exit(1);
54
+ }
55
+ const componentJson = JSON.parse(inputData);
56
+ const result = validateComponentStructure(componentJson);
57
+ console.log(JSON.stringify(result));
58
+ break;
59
+
60
+ case '--common-properties':
61
+ // Return all common properties
62
+ const commonProperties = getAllCommonProperties();
63
+ console.log(JSON.stringify(commonProperties));
64
+ break;
65
+
66
+ case '--categorized-common-properties':
67
+ // Return categorized common properties
68
+ const categorizedCommonProperties = getCategorizedCommonProperties();
69
+ console.log(JSON.stringify(categorizedCommonProperties));
70
+ break;
71
+
72
+ case '--themes':
73
+ // Return supported themes as key -> description
74
+ const themes = getAllThemes();
75
+ console.log(JSON.stringify(themes));
76
+ break;
77
+
78
+ default:
79
+ console.log('Usage:');
80
+ console.log(' component-cli.js --available');
81
+ console.log(' component-cli.js --validate <componentType>');
82
+ console.log(' component-cli.js --validate-structure < component.json');
83
+ console.log(' component-cli.js --common-properties');
84
+ console.log(' component-cli.js --categorized-common-properties');
85
+ console.log(' component-cli.js --themes');
86
+ process.exit(1);
87
+ }
88
+ } catch (error) {
89
+ console.error(JSON.stringify({ error: error.message }));
90
+ process.exit(1);
91
+ }
92
+ }
93
+
94
+ main();
bin/serialize-cli.js ADDED
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname, join } from 'path';
5
+
6
+ // Calculate the correct path to dist directory
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ const distPath = join(__dirname, '..', 'dist', 'python-package.esm.js');
10
+ const { SduiASTSerializer, validateComponentStructure } = await import(distPath);
11
+
12
+ // Handle JSON input from stdin
13
+ async function readStdin() {
14
+ return new Promise((resolve) => {
15
+ let data = '';
16
+ process.stdin.setEncoding('utf8');
17
+ process.stdin.on('readable', () => {
18
+ let chunk;
19
+ while ((chunk = process.stdin.read()) !== null) {
20
+ data += chunk;
21
+ }
22
+ });
23
+ process.stdin.on('end', () => {
24
+ resolve(data);
25
+ });
26
+ });
27
+ }
28
+
29
+ async function main() {
30
+ const args = process.argv.slice(2);
31
+ const command = args[0];
32
+
33
+ try {
34
+ switch (command) {
35
+ case '--source':
36
+ // Serialize from source code
37
+ const sourceData = await readStdin();
38
+ if (!sourceData.trim()) {
39
+ console.error('Source code is required');
40
+ process.exit(1);
41
+ }
42
+ const { component, errors } = SduiASTSerializer.serializeFromSourceWithErrorCollection(sourceData);
43
+ if (errors.length > 0) {
44
+ console.error(JSON.stringify({ error: errors.join('; ') }));
45
+ process.exit(1);
46
+ }
47
+ console.log(JSON.stringify(component));
48
+ break;
49
+
50
+ case '--file':
51
+ // Serialize component file
52
+ const fileData = await readStdin();
53
+ if (!fileData.trim()) {
54
+ console.error('File source code is required');
55
+ process.exit(1);
56
+ }
57
+ const fileResult = SduiASTSerializer.serializeComponentFile(fileData);
58
+ console.log(JSON.stringify(fileResult));
59
+ break;
60
+
61
+ case '--component':
62
+ // Serialize component JSON
63
+ const componentData = await readStdin();
64
+ if (!componentData.trim()) {
65
+ console.error('Component JSON is required');
66
+ process.exit(1);
67
+ }
68
+ const componentJson = JSON.parse(componentData);
69
+ // For component JSON, we can just return it as-is since it's already serialized
70
+ // But we'll validate it first to ensure it's a valid component structure
71
+ const validationResult = validateComponentStructure(componentJson);
72
+ if (!validationResult.isValid) {
73
+ throw new Error(`Invalid component structure: ${validationResult.errors.join(', ')}`);
74
+ }
75
+ console.log(JSON.stringify(componentJson));
76
+ break;
77
+
78
+ default:
79
+ console.log('Usage:');
80
+ console.log(' serialize-cli.js --source < source-code');
81
+ console.log(' serialize-cli.js --file < file-source-code');
82
+ console.log(' serialize-cli.js --component < component-json');
83
+ process.exit(1);
84
+ }
85
+ } catch (error) {
86
+ console.error(JSON.stringify({ error: error.message }));
87
+ process.exit(1);
88
+ }
89
+ }
90
+
91
+ main();
bin/type-check-cli.js ADDED
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname, join } from 'path';
5
+
6
+ // Calculate the correct path to dist directory
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ const distPath = join(__dirname, '..', 'dist', 'python-package.esm.js');
10
+
11
+ // Handle JSON input from stdin
12
+ async function readStdin() {
13
+ return new Promise((resolve) => {
14
+ let data = '';
15
+ process.stdin.setEncoding('utf8');
16
+ process.stdin.on('readable', () => {
17
+ let chunk;
18
+ while ((chunk = process.stdin.read()) !== null) {
19
+ data += chunk;
20
+ }
21
+ });
22
+ process.stdin.on('end', () => {
23
+ resolve(data);
24
+ });
25
+ });
26
+ }
27
+
28
+ async function main() {
29
+ const args = process.argv.slice(2);
30
+ const command = args[0];
31
+
32
+ try {
33
+ // Import the module and initialize TypeChecker
34
+ const module = await import(distPath);
35
+ if (module.SduiTypeChecker && module.ComponentDefinitions) {
36
+ // Use registerComponentSchemas with the ComponentDefinitions from the module
37
+ module.SduiTypeChecker.registerComponentSchemas(module.ComponentDefinitions);
38
+ }
39
+
40
+ const { SduiTypeChecker } = module;
41
+
42
+ switch (command) {
43
+ case '--component':
44
+ // Validate component JSON
45
+ const componentData = await readStdin();
46
+ if (!componentData.trim()) {
47
+ console.error('Component JSON is required');
48
+ process.exit(1);
49
+ }
50
+ const componentJson = JSON.parse(componentData);
51
+ const componentResult = SduiTypeChecker.validateComponent(componentJson);
52
+ console.log(JSON.stringify(componentResult));
53
+ break;
54
+
55
+ case '--code':
56
+ // Validate code string
57
+ const codeData = await readStdin();
58
+ if (!codeData.trim()) {
59
+ console.error('Code string is required');
60
+ process.exit(1);
61
+ }
62
+ const codeResult = SduiTypeChecker.validateCodeString(codeData);
63
+ console.log(JSON.stringify(codeResult));
64
+ break;
65
+
66
+ case '--component-auto':
67
+ // Validate component with auto-detection
68
+ const autoComponentData = await readStdin();
69
+ if (!autoComponentData.trim()) {
70
+ console.error('Component JSON is required');
71
+ process.exit(1);
72
+ }
73
+ const autoComponentJson = JSON.parse(autoComponentData);
74
+ const autoResult = SduiTypeChecker.validateComponentWithAutoDetection(autoComponentJson);
75
+ console.log(JSON.stringify(autoResult));
76
+ break;
77
+
78
+ case '--code-auto':
79
+ // Validate code string with auto-detection
80
+ const autoCodeData = await readStdin();
81
+ if (!autoCodeData.trim()) {
82
+ console.error('Code string is required');
83
+ process.exit(1);
84
+ }
85
+ const autoCodeResult = SduiTypeChecker.validateCodeStringWithAutoDetection(autoCodeData);
86
+ console.log(JSON.stringify(autoCodeResult));
87
+ break;
88
+
89
+ default:
90
+ console.log('Usage:');
91
+ console.log(' type-check-cli.js --component < component.json');
92
+ console.log(' type-check-cli.js --code < code-string');
93
+ console.log(' type-check-cli.js --component-auto < component.json');
94
+ console.log(' type-check-cli.js --code-auto < code-string');
95
+ process.exit(1);
96
+ }
97
+ } catch (error) {
98
+ console.error(JSON.stringify({ error: error.message }));
99
+ process.exit(1);
100
+ }
101
+ }
102
+
103
+ main();
examples/__init__.py ADDED
File without changes
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Example usage script for the SDUI Python package
4
+ """
5
+
6
+ import json
7
+ from sdui_python import (
8
+ get_available_components,
9
+ validate_from_source,
10
+ serialize_from_source,
11
+ get_all_common_properties
12
+ )
13
+
14
+ def example_component_operations():
15
+ print("=== Component Operations Example ===")
16
+
17
+ # Get available components
18
+ components = get_available_components()
19
+ print(f"Available components ({len(components)}):")
20
+ for component in components[:5]: # Show first 5
21
+ print(f" - {component}")
22
+ if len(components) > 5:
23
+ print(f" ... and {len(components) - 5} more")
24
+ print()
25
+
26
+ def example_component_validation():
27
+ print("=== Component Validation Example ===")
28
+
29
+ # Validate component structure
30
+ valid_component = """
31
+ function MyComponent() {
32
+ return <SduiText text="Hello World" />;
33
+ }
34
+ """
35
+
36
+ result = validate_from_source(valid_component)
37
+ print("Valid component structure validation:")
38
+ print(f" Is valid: {result['isValid']}")
39
+ print(f" Errors: {result['errors']}")
40
+ print()
41
+
42
+ # Test with invalid component
43
+ invalid_component = """
44
+ function MyComponent() {
45
+ return <SduiText />;
46
+ }
47
+ """
48
+
49
+ result = validate_from_source(invalid_component)
50
+ print("Invalid component structure validation:")
51
+ print(f" Is valid: {result['isValid']}")
52
+ print(f" Errors: {result['errors']}")
53
+ print()
54
+
55
+ def example_serialization():
56
+ print("=== Serialization Example ===")
57
+
58
+ # Serialize JSX source code with variant-driven styling
59
+ jsx_code = """
60
+ function MyComponent() {
61
+ return (
62
+ <SduiVStack spacing={16}>
63
+ <SduiText text="Welcome" variant="h1" />
64
+ <SduiButton text="Get Started" variant="default" size="lg" />
65
+ </SduiVStack>
66
+ );
67
+ }
68
+ """
69
+
70
+ result = serialize_from_source(jsx_code)
71
+ if result:
72
+ print("Serialized component successfully:")
73
+ print(f" Type: {result['type']}")
74
+ print(f" Props: {result['props']}")
75
+ if 'children' in result and result['children']:
76
+ print(f" Number of children: {len(result['children'])}")
77
+ else:
78
+ print("Failed to serialize component")
79
+ print()
80
+
81
+ def example_common_properties():
82
+ print("=== Common Properties Example ===")
83
+
84
+ # Get all common properties (now only 5 in variant-driven system)
85
+ common_properties = get_all_common_properties()
86
+ print(f"Common properties ({len(common_properties)}):")
87
+ for prop_name, prop_info in common_properties.items():
88
+ print(f" - {prop_name}: {prop_info['description']}")
89
+ print()
90
+
91
+ # Show variant-driven components
92
+ components = get_available_components()
93
+ print("=== Variant-Driven Components ===")
94
+
95
+ # Find components with variants
96
+ variant_components = []
97
+ for component in components:
98
+ if 'variant' in str(component['props']):
99
+ variant_components.append(component)
100
+
101
+ print(f"Components with variants ({len(variant_components)}):")
102
+ for component in variant_components[:5]: # Show first 5
103
+ print(f" - {component['name']}")
104
+ if 'variant' in component['props']:
105
+ print(f" Variant options: {component['props']['variant']['enumValues']}")
106
+ if 'size' in component['props']:
107
+ print(f" Size options: {component['props']['size']['enumValues']}")
108
+ print()
109
+
110
+ if __name__ == "__main__":
111
+ print("SDUI Python Package Usage Example")
112
+ print("=" * 35)
113
+ print()
114
+
115
+ try:
116
+ example_component_operations()
117
+ example_component_validation()
118
+ example_serialization()
119
+ example_common_properties()
120
+
121
+ print("Example completed successfully!")
122
+ except Exception as e:
123
+ print(f"Example failed with error: {e}")
124
+ print("Make sure Node.js is installed and the package is properly set up.")
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Variant-driven component examples for the SDUI Python package
4
+ """
5
+
6
+ import json
7
+ import subprocess
8
+ from sdui_python import get_available_components
9
+
10
+ def example_button_variants():
11
+ """Demonstrate different button variants"""
12
+ print("=== Button Variants Example ===")
13
+
14
+ # Get button component info
15
+ components = get_available_components()
16
+ button = next(c for c in components if c['name'] == 'SduiButton')
17
+
18
+ print("Button variants:")
19
+ if 'variant' in button['props']:
20
+ print(f" Available variants: {button['props']['variant']['enumValues']}")
21
+ if 'size' in button['props']:
22
+ print(f" Available sizes: {button['props']['size']['enumValues']}")
23
+
24
+ # Create buttons with different variants
25
+ button_examples = [
26
+ {
27
+ "type": "SduiButton",
28
+ "props": {
29
+ "text": "Primary Action",
30
+ "variant": "default",
31
+ "size": "lg"
32
+ }
33
+ },
34
+ {
35
+ "type": "SduiButton",
36
+ "props": {
37
+ "text": "Secondary Action",
38
+ "variant": "outline",
39
+ "size": "sm"
40
+ }
41
+ },
42
+ {
43
+ "type": "SduiButton",
44
+ "props": {
45
+ "text": "Danger",
46
+ "variant": "destructive",
47
+ "size": "default"
48
+ }
49
+ },
50
+ {
51
+ "type": "SduiButton",
52
+ "props": {
53
+ "text": "Link",
54
+ "variant": "link",
55
+ "size": "default"
56
+ }
57
+ }
58
+ ]
59
+
60
+ # Validate each button variant
61
+ for i, button in enumerate(button_examples, 1):
62
+ result = subprocess.run([
63
+ 'node', 'bin/component-cli.js', '--validate-structure'
64
+ ], input=json.dumps(button), capture_output=True, text=True)
65
+ validation_result = json.loads(result.stdout)
66
+ print(f" Button {i}: '{button['props']['text']}' with variant '{button['props']['variant']}' - Valid: {validation_result['isValid']}")
67
+
68
+ print()
69
+
70
+ def example_text_variants():
71
+ """Demonstrate different text variants"""
72
+ print("=== Text Variants Example ===")
73
+
74
+ # Get text component info
75
+ components = get_available_components()
76
+ text = next(c for c in components if c['name'] == 'SduiText')
77
+
78
+ print("Text variants:")
79
+ if 'variant' in text['props']:
80
+ print(f" Available variants: {text['props']['variant']['enumValues']}")
81
+
82
+ # Create text examples with different variants
83
+ text_examples = [
84
+ {
85
+ "type": "SduiText",
86
+ "props": {
87
+ "text": "Main Title",
88
+ "variant": "h1"
89
+ }
90
+ },
91
+ {
92
+ "type": "SduiText",
93
+ "props": {
94
+ "text": "Section Title",
95
+ "variant": "h2"
96
+ }
97
+ },
98
+ {
99
+ "type": "SduiText",
100
+ "props": {
101
+ "text": "Body text paragraph",
102
+ "variant": "p"
103
+ }
104
+ },
105
+ {
106
+ "type": "SduiText",
107
+ "props": {
108
+ "text": "Important quote",
109
+ "variant": "blockquote"
110
+ }
111
+ },
112
+ {
113
+ "type": "SduiText",
114
+ "props": {
115
+ "text": "code snippet",
116
+ "variant": "code"
117
+ }
118
+ }
119
+ ]
120
+
121
+ # Validate each text variant
122
+ for i, text in enumerate(text_examples, 1):
123
+ result = subprocess.run([
124
+ 'node', 'bin/component-cli.js', '--validate-structure'
125
+ ], input=json.dumps(text), capture_output=True, text=True)
126
+ validation_result = json.loads(result.stdout)
127
+ print(f" Text {i}: '{text['props']['text']}' with variant '{text['props']['variant']}' - Valid: {validation_result['isValid']}")
128
+
129
+ print()
130
+
131
+ def example_new_components():
132
+ """Demonstrate new components added in variant-driven system"""
133
+ print("=== New Components Example ===")
134
+
135
+ # SduiFloatingButton example
136
+ floating_button = {
137
+ "type": "SduiFloatingButton",
138
+ "props": {
139
+ "icon": "plus",
140
+ "variant": "default",
141
+ "size": "lg",
142
+ "floatingVariant": "bottomRight"
143
+ }
144
+ }
145
+
146
+ # SduiGrid example
147
+ grid_component = {
148
+ "type": "SduiGrid",
149
+ "props": {
150
+ "variant": "default",
151
+ "columnCount": 3,
152
+ "minimumItemWidth": 200
153
+ }
154
+ }
155
+
156
+ # Validate new components
157
+ new_components = [
158
+ ("SduiFloatingButton", floating_button),
159
+ ("SduiGrid", grid_component)
160
+ ]
161
+
162
+ for name, component in new_components:
163
+ result = subprocess.run([
164
+ 'node', 'bin/component-cli.js', '--validate-structure'
165
+ ], input=json.dumps(component), capture_output=True, text=True)
166
+ validation_result = json.loads(result.stdout)
167
+ print(f" {name}: {'Valid' if validation_result['isValid'] else 'Invalid'}")
168
+ if not validation_result['isValid']:
169
+ print(f" Errors: {validation_result['errors']}")
170
+
171
+ print()
172
+
173
+ def example_complex_variant_structure():
174
+ """Demonstrate complex component structure with variants"""
175
+ print("=== Complex Variant Structure Example ===")
176
+
177
+ complex_component = {
178
+ "type": "SduiVStack",
179
+ "props": {
180
+ "spacing": 20
181
+ },
182
+ "children": [
183
+ {
184
+ "type": "SduiText",
185
+ "props": {
186
+ "text": "Welcome to SDUI",
187
+ "variant": "h1"
188
+ }
189
+ },
190
+ {
191
+ "type": "SduiHStack",
192
+ "props": {
193
+ "spacing": 12
194
+ },
195
+ "children": [
196
+ {
197
+ "type": "SduiButton",
198
+ "props": {
199
+ "text": "Save",
200
+ "variant": "default",
201
+ "size": "lg"
202
+ }
203
+ },
204
+ {
205
+ "type": "SduiButton",
206
+ "props": {
207
+ "text": "Cancel",
208
+ "variant": "outline",
209
+ "size": "lg"
210
+ }
211
+ }
212
+ ]
213
+ },
214
+ {
215
+ "type": "SduiCard",
216
+ "props": {
217
+ "variant": "elevated"
218
+ },
219
+ "children": [
220
+ {
221
+ "type": "SduiText",
222
+ "props": {
223
+ "text": "Card content",
224
+ "variant": "p"
225
+ }
226
+ }
227
+ ]
228
+ }
229
+ ]
230
+ }
231
+
232
+ # Validate complex structure
233
+ result = subprocess.run([
234
+ 'node', 'bin/component-cli.js', '--validate-structure'
235
+ ], input=json.dumps(complex_component), capture_output=True, text=True)
236
+ validation_result = json.loads(result.stdout)
237
+ print(f"Complex structure validation: {'Valid' if validation_result['isValid'] else 'Invalid'}")
238
+ if validation_result['isValid']:
239
+ print(" Root component: SduiVStack")
240
+ print(" Children: 3 (SduiText, SduiHStack, SduiCard)")
241
+ else:
242
+ print(f" Errors: {validation_result['errors']}")
243
+
244
+ print()
245
+
246
+ if __name__ == "__main__":
247
+ print("Variant-Driven Component Examples")
248
+ print("=" * 35)
249
+ print()
250
+
251
+ try:
252
+ example_button_variants()
253
+ example_text_variants()
254
+ example_new_components()
255
+ example_complex_variant_structure()
256
+
257
+ print("All examples completed successfully!")
258
+ except Exception as e:
259
+ print(f"Example failed with error: {e}")
260
+ print("Make sure Node.js is installed and the package is properly set up.")