juxscript 1.1.0 → 1.1.2

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,136 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { glob } from 'glob';
4
+
5
+ /**
6
+ * Generate documentation from TypeScript component files
7
+ *
8
+ * @param {string} juxLibPath - Absolute path to jux/lib directory
9
+ */
10
+ export async function generateDocs(juxLibPath) {
11
+ const componentsDir = path.join(juxLibPath, 'components');
12
+
13
+ if (!fs.existsSync(componentsDir)) {
14
+ throw new Error(`Components directory not found: ${componentsDir}`);
15
+ }
16
+
17
+ console.log(` Scanning: ${componentsDir}`);
18
+
19
+ // Find all component TypeScript files
20
+ const componentFiles = glob.sync('*.ts', {
21
+ cwd: componentsDir,
22
+ absolute: true,
23
+ ignore: ['reactivity.ts', 'error-handler.ts']
24
+ });
25
+
26
+ console.log(` Found ${componentFiles.length} component files`);
27
+
28
+ const components = [];
29
+
30
+ for (const filePath of componentFiles) {
31
+ const content = fs.readFileSync(filePath, 'utf-8');
32
+ const componentDoc = parseComponentFile(content, filePath);
33
+
34
+ if (componentDoc) {
35
+ components.push(componentDoc);
36
+ console.log(` ✓ ${componentDoc.name}`);
37
+ }
38
+ }
39
+
40
+ // Sort by category and name
41
+ components.sort((a, b) => {
42
+ const categoryCompare = (a.category || 'ZZZ').localeCompare(b.category || 'ZZZ');
43
+ if (categoryCompare !== 0) return categoryCompare;
44
+ return a.name.localeCompare(b.name);
45
+ });
46
+
47
+ // Generate the docs data
48
+ const docsData = {
49
+ components,
50
+ version: '1.0.0',
51
+ lastUpdated: new Date().toISOString()
52
+ };
53
+
54
+ // Write to JSON file
55
+ const outputPath = path.join(componentsDir, 'docs-data.json');
56
+ fs.writeFileSync(outputPath, JSON.stringify(docsData, null, 2));
57
+
58
+ console.log(` Generated: ${outputPath}`);
59
+
60
+ return docsData;
61
+ }
62
+
63
+ /**
64
+ * Parse a single component file
65
+ */
66
+ function parseComponentFile(content, filePath) {
67
+ const fileName = path.basename(filePath, '.ts');
68
+ const className = fileName.charAt(0).toUpperCase() + fileName.slice(1);
69
+
70
+ const category = inferCategory(className, content);
71
+ const descMatch = content.match(/\/\*\*\s*\n\s*\*\s*([^\n*]+)/);
72
+ const description = descMatch ? descMatch[1].trim() : `${className} component`;
73
+ const factoryMatch = content.match(/export function\s+\w+\(([^)]*)\)/);
74
+ const constructorSig = factoryMatch
75
+ ? `jux.${fileName}(${factoryMatch[1]})`
76
+ : `new ${className}()`;
77
+ const fluentMethods = extractFluentMethods(content, className);
78
+ const exampleMatch = content.match(/\*\s+Usage:\s*\n\s*\*\s+(.+?)(?:\n|$)/);
79
+ let example = exampleMatch
80
+ ? exampleMatch[1].trim()
81
+ : `jux.${fileName}('id').render()`;
82
+
83
+ return {
84
+ name: className,
85
+ category,
86
+ description,
87
+ constructor: constructorSig,
88
+ fluentMethods,
89
+ example
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Extract fluent API methods from class
95
+ */
96
+ function extractFluentMethods(content, className) {
97
+ const methods = [];
98
+ const methodRegex = /^\s*(\w+)\(([^)]*)\):\s*this\s*\{/gm;
99
+ let match;
100
+
101
+ while ((match = methodRegex.exec(content)) !== null) {
102
+ const methodName = match[1];
103
+ const params = match[2];
104
+ if (methodName.startsWith('_') || methodName === 'constructor') continue;
105
+ const cleanParams = params.split(',').map(p => p.trim().split(':')[0].trim()).filter(p => p).join(', ');
106
+ methods.push({
107
+ name: methodName,
108
+ params: cleanParams ? `(${cleanParams})` : '()',
109
+ returns: 'this',
110
+ description: `Set ${methodName}`
111
+ });
112
+ }
113
+
114
+ const renderMatch = content.match(/^\s*render\(([^)]*)\):\s*(\w+)/m);
115
+ if (renderMatch && !methods.find(m => m.name === 'render')) {
116
+ methods.push({
117
+ name: 'render',
118
+ params: renderMatch[1] ? `(${renderMatch[1]})` : '()',
119
+ returns: renderMatch[2],
120
+ description: 'Render component to DOM'
121
+ });
122
+ }
123
+
124
+ return methods;
125
+ }
126
+
127
+ /**
128
+ * Infer category from component name or content
129
+ */
130
+ function inferCategory(name, content) {
131
+ const dataComponents = ['Table', 'List', 'Chart', 'Data'];
132
+ const coreComponents = ['App', 'Layout', 'Theme', 'Style', 'Script', 'Import'];
133
+ if (dataComponents.some(dc => name.includes(dc))) return 'Data Components';
134
+ if (coreComponents.includes(name)) return 'Core';
135
+ return 'UI Components';
136
+ }
@@ -0,0 +1,155 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = path.dirname(__filename);
7
+ const REGISTRY_PATH = path.join(__dirname, '../lib/registry/packages.json');
8
+
9
+ /**
10
+ * Load package registry
11
+ */
12
+ function loadRegistry() {
13
+ if (!fs.existsSync(REGISTRY_PATH)) {
14
+ return {};
15
+ }
16
+ return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf-8'));
17
+ }
18
+
19
+ /**
20
+ * Parse @import directives from Jux code
21
+ */
22
+ export function parseImports(juxCode) {
23
+ const imports = [];
24
+ const lines = juxCode.split('\n');
25
+
26
+ for (let i = 0; i < lines.length; i++) {
27
+ const line = lines[i].trim();
28
+
29
+ // Stop parsing when we hit actual code (non-directive, non-comment)
30
+ if (line && !line.startsWith('@') && !line.startsWith('//') && !line.startsWith('/*')) {
31
+ break;
32
+ }
33
+
34
+ // Match @import directive
35
+ const importMatch = line.match(/^@import\s+(.+)$/);
36
+ if (importMatch) {
37
+ const importSpec = importMatch[1].trim();
38
+ imports.push({
39
+ line: i + 1,
40
+ raw: importSpec,
41
+ resolved: resolveImport(importSpec)
42
+ });
43
+
44
+ if (process.env.JUX_VERBOSE) {
45
+ console.log(` [Line ${i + 1}] Found @import: ${importSpec}`);
46
+ }
47
+ }
48
+ }
49
+
50
+ return imports;
51
+ }
52
+
53
+ /**
54
+ * Resolve import specification to URL/path
55
+ */
56
+ export function resolveImport(importSpec) {
57
+ // Remove quotes if present
58
+ const cleaned = importSpec.replace(/^['"]|['"]$/g, '');
59
+
60
+ // Direct URL (starts with http:// or https://)
61
+ if (cleaned.startsWith('http://') || cleaned.startsWith('https://')) {
62
+ return {
63
+ type: 'cdn',
64
+ url: cleaned,
65
+ source: 'direct'
66
+ };
67
+ }
68
+
69
+ // Local file (starts with ./ or ../ or /)
70
+ if (cleaned.startsWith('./') || cleaned.startsWith('../') || cleaned.startsWith('/')) {
71
+ return {
72
+ type: 'local',
73
+ path: cleaned,
74
+ source: 'file'
75
+ };
76
+ }
77
+
78
+ // Unknown/unsupported
79
+ return {
80
+ type: 'unknown',
81
+ name: cleaned,
82
+ error: `Import "${cleaned}" must be a URL (https://...) or relative path (./...)`
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Auto-detect component dependencies
88
+ */
89
+ function detectComponentDependencies(usedComponents) {
90
+ const componentDeps = {
91
+ 'chart': 'chart.js'
92
+ // Add more mappings as needed
93
+ };
94
+
95
+ const deps = new Set();
96
+
97
+ usedComponents.forEach(comp => {
98
+ if (componentDeps[comp]) {
99
+ deps.add(componentDeps[comp]);
100
+ }
101
+ });
102
+
103
+ return Array.from(deps).map(pkg => ({
104
+ auto: true,
105
+ resolved: resolveImport(pkg)
106
+ }));
107
+ }
108
+
109
+ /**
110
+ * Generate HTML script tags from resolved imports
111
+ */
112
+ export function generateImportTags(imports) {
113
+ const tags = [];
114
+ const seen = new Set();
115
+
116
+ for (const imp of imports) {
117
+ const resolved = imp.resolved;
118
+
119
+ if (resolved.type === 'unknown') {
120
+ tags.push(`<!-- ERROR: ${resolved.error} -->`);
121
+ continue;
122
+ }
123
+
124
+ const key = resolved.url || resolved.path;
125
+ if (seen.has(key)) continue;
126
+ seen.add(key);
127
+
128
+ if (resolved.type === 'cdn') {
129
+ tags.push(` <script src="${resolved.url}"></script>`);
130
+ } else if (resolved.type === 'local') {
131
+ tags.push(` <script type="module" src="${resolved.path}"></script>`);
132
+ }
133
+ }
134
+
135
+ return tags.join('\n');
136
+ }
137
+
138
+ /**
139
+ * Validate all imports are resolvable
140
+ */
141
+ export function validateImports(imports) {
142
+ const errors = [];
143
+
144
+ imports.forEach(imp => {
145
+ if (imp.resolved.type === 'unknown') {
146
+ errors.push({
147
+ line: imp.line,
148
+ message: imp.resolved.error,
149
+ raw: imp.raw
150
+ });
151
+ }
152
+ });
153
+
154
+ return errors;
155
+ }
@@ -0,0 +1,166 @@
1
+ import express from 'express';
2
+ import http from 'http';
3
+ import path from 'path';
4
+ import fs from 'fs';
5
+ import { fileURLToPath } from 'url';
6
+ import { startWatcher } from './watcher.js';
7
+ import { WebSocketServer } from 'ws';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+
12
+ /**
13
+ * Try to start a server on a port, with fallback to next port if busy
14
+ * Returns the actual port that was successfully allocated
15
+ */
16
+ async function tryPort(startPort, maxAttempts = 5, reservedPorts = []) {
17
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
18
+ const port = startPort + attempt;
19
+
20
+ // Skip if this port is already reserved
21
+ if (reservedPorts.includes(port)) {
22
+ continue;
23
+ }
24
+
25
+ try {
26
+ // Test if port is available
27
+ await new Promise((resolve, reject) => {
28
+ const testServer = http.createServer();
29
+ testServer.once('error', reject);
30
+ testServer.once('listening', () => {
31
+ testServer.close();
32
+ resolve(port);
33
+ });
34
+ testServer.listen(port);
35
+ });
36
+ return port;
37
+ } catch (err) {
38
+ if (err.code === 'EADDRINUSE') {
39
+ if (attempt < maxAttempts - 1) {
40
+ console.log(` Port ${port} in use, trying ${port + 1}...`);
41
+ }
42
+ continue;
43
+ }
44
+ throw err;
45
+ }
46
+ }
47
+ throw new Error(`Could not find available port after ${maxAttempts} attempts starting from ${startPort}`);
48
+ }
49
+
50
+ async function serve(httpPort = 3000, wsPort = 3001, distDir = './.jux-dist') {
51
+ const app = express();
52
+ const absoluteDistDir = path.resolve(distDir);
53
+ const projectRoot = path.resolve('.');
54
+
55
+ app.use(express.json());
56
+
57
+ if (!fs.existsSync(absoluteDistDir)) {
58
+ console.error(`❌ Error: ${path.basename(distDir)}/ directory not found at ${absoluteDistDir}`);
59
+ console.error(' Run: npx jux build\n');
60
+ process.exit(1);
61
+ }
62
+
63
+ // Strong cache prevention
64
+ app.use((req, res, next) => {
65
+ res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
66
+ res.setHeader('Pragma', 'no-cache');
67
+ res.setHeader('Expires', '0');
68
+ res.setHeader('ETag', 'W/"' + Date.now() + '"');
69
+ next();
70
+ });
71
+
72
+ // ✅ ADD: Explicit MIME type for JavaScript files
73
+ app.use((req, res, next) => {
74
+ if (req.path.endsWith('.js')) {
75
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
76
+ }
77
+ next();
78
+ });
79
+
80
+ // Serve static files
81
+ app.use(express.static(absoluteDistDir));
82
+
83
+ // ✅ FIX: Only apply SPA fallback to routes, not static files
84
+ app.use((req, res, next) => {
85
+ // Skip SPA fallback for file extensions (static assets)
86
+ if (/\.[a-zA-Z0-9]+$/.test(req.path)) {
87
+ return res.status(404).send('File not found');
88
+ }
89
+
90
+ // SPA fallback for routes only
91
+ if (req.accepts('html')) {
92
+ const indexPath = path.join(absoluteDistDir, 'index.html');
93
+ if (fs.existsSync(indexPath)) {
94
+ res.sendFile(indexPath);
95
+ } else {
96
+ res.status(404).send('index.html not found. Run `npx jux build` first.');
97
+ }
98
+ } else {
99
+ res.status(404).send('Not found');
100
+ }
101
+ });
102
+
103
+ // Find available ports sequentially to avoid collision
104
+ console.log('🔍 Finding available ports...');
105
+
106
+ // First, find HTTP port
107
+ const availableHttpPort = await tryPort(httpPort);
108
+
109
+ // Then find WS port, excluding the HTTP port we just allocated
110
+ const availableWsPort = await tryPort(wsPort, 5, [availableHttpPort]);
111
+
112
+ // Create HTTP server
113
+ const server = http.createServer(app);
114
+
115
+ // WebSocket server for hot reload
116
+ const wss = new WebSocketServer({ port: availableWsPort });
117
+ const clients = [];
118
+
119
+ wss.on('connection', (ws) => {
120
+ clients.push(ws);
121
+ console.log('🔌 WebSocket client connected');
122
+
123
+ ws.on('close', () => {
124
+ console.log('🔌 WebSocket client disconnected');
125
+ const index = clients.indexOf(ws);
126
+ if (index > -1) clients.splice(index, 1);
127
+ });
128
+
129
+ ws.on('error', (error) => {
130
+ console.error('WebSocket error:', error);
131
+ });
132
+ });
133
+
134
+ console.log(`🔌 WebSocket server running at ws://localhost:${availableWsPort}`);
135
+
136
+ // Start HTTP server
137
+ server.listen(availableHttpPort, () => {
138
+ console.log(`🚀 JUX dev server running at http://localhost:${availableHttpPort}`);
139
+ console.log(` Serving: ${absoluteDistDir}`);
140
+ console.log(` Press Ctrl+C to stop\n`);
141
+ });
142
+
143
+ // Start file watcher
144
+ const juxSource = path.join(projectRoot, 'jux');
145
+ if (fs.existsSync(juxSource)) {
146
+ console.log(`👀 Watching: ${juxSource}\n`);
147
+ startWatcher(juxSource, absoluteDistDir, clients);
148
+ }
149
+
150
+ // Graceful shutdown
151
+ const shutdown = async () => {
152
+ console.log('\n\n👋 Shutting down server...');
153
+ wss.close();
154
+ server.close();
155
+ process.exit(0);
156
+ };
157
+
158
+ process.on('SIGINT', shutdown);
159
+ process.on('SIGTERM', shutdown);
160
+
161
+ return { server, httpPort: availableHttpPort, wsPort: availableWsPort };
162
+ }
163
+
164
+ export async function start(httpPort = 3000, wsPort = 3001, distDir = './.jux-dist') {
165
+ return serve(httpPort, wsPort, distDir);
166
+ }
@@ -0,0 +1,46 @@
1
+ import esbuild from 'esbuild';
2
+
3
+ /**
4
+ * TypeScript Shim - Strips type annotations using esbuild
5
+ * This is rock-solid and handles ALL TypeScript syntax correctly
6
+ */
7
+
8
+ /**
9
+ * Strip TypeScript type annotations from code using esbuild
10
+ *
11
+ * @param {string} code - TypeScript source code
12
+ * @returns {string} - JavaScript code with types removed
13
+ */
14
+ export function stripTypes(code) {
15
+ try {
16
+ // ✅ Use esbuild to transform TypeScript → JavaScript
17
+ const result = esbuild.transformSync(code, {
18
+ loader: 'ts',
19
+ format: 'esm',
20
+ target: 'es2020'
21
+ });
22
+
23
+ return result.code;
24
+ } catch (err) {
25
+ console.error('❌ Failed to strip TypeScript:', err.message);
26
+ // Return original code if transformation fails
27
+ return code;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Check if a file is TypeScript based on extension
33
+ */
34
+ export function isTypeScript(filePath) {
35
+ return filePath.endsWith('.ts') || filePath.endsWith('.tsx');
36
+ }
37
+
38
+ /**
39
+ * Load and parse a file, automatically stripping types if it's TypeScript
40
+ */
41
+ export function loadAndStripTypes(filePath, fileContent) {
42
+ if (isTypeScript(filePath)) {
43
+ return stripTypes(fileContent);
44
+ }
45
+ return fileContent;
46
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * File validation utilities for Jux compiler
3
+ * Validates file types and content security
4
+ */
5
+ export class FileValidator {
6
+ constructor() {
7
+ this.cssExtensions = /\.(css|scss|sass|less)$/i;
8
+ this.jsExtensions = /\.(js|mjs|ts|tsx|jsx)$/i;
9
+ this.imageExtensions = /\.(png|jpg|jpeg|gif|svg|webp|ico|bmp)$/i;
10
+ }
11
+
12
+ /**
13
+ * Check if file is a CSS file
14
+ */
15
+ isCSSFile(filepath) {
16
+ return this.cssExtensions.test(filepath);
17
+ }
18
+
19
+ /**
20
+ * Check if file is a JavaScript file
21
+ */
22
+ isJavaScriptFile(filepath) {
23
+ return this.jsExtensions.test(filepath);
24
+ }
25
+
26
+ /**
27
+ * Check if file is an image file
28
+ */
29
+ isImageFile(filepath) {
30
+ return this.imageExtensions.test(filepath);
31
+ }
32
+
33
+ /**
34
+ * Validate CSS content for security issues
35
+ * Detects <script> tags that could be injected
36
+ */
37
+ validateStyleContent(content, source = 'unknown') {
38
+ if (/<script/i.test(content)) {
39
+ throw new Error(
40
+ `🚨 Security Error: <script> tag detected in ${source}\n` +
41
+ `CSS content must not contain script tags.`
42
+ );
43
+ }
44
+
45
+ if (/<\/script/i.test(content)) {
46
+ throw new Error(
47
+ `🚨 Security Error: </script> tag detected in ${source}\n` +
48
+ `CSS content must not contain script tags.`
49
+ );
50
+ }
51
+
52
+ return content;
53
+ }
54
+
55
+ /**
56
+ * Determine import type based on file extension
57
+ * Returns: 'css' | 'js' | 'image' | 'unknown'
58
+ */
59
+ validateImportPath(importPath) {
60
+ // Handle URLs
61
+ if (importPath.startsWith('http://') || importPath.startsWith('https://')) {
62
+ // Try to infer from URL
63
+ if (this.isCSSFile(importPath)) return { type: 'css', path: importPath };
64
+ if (this.isJavaScriptFile(importPath)) return { type: 'js', path: importPath };
65
+ if (this.isImageFile(importPath)) return { type: 'image', path: importPath };
66
+
67
+ // Default to unknown for CDN URLs without clear extensions
68
+ return { type: 'unknown', path: importPath };
69
+ }
70
+
71
+ // Local files
72
+ if (this.isCSSFile(importPath)) {
73
+ return { type: 'css', path: importPath };
74
+ }
75
+
76
+ if (this.isJavaScriptFile(importPath)) {
77
+ return { type: 'js', path: importPath };
78
+ }
79
+
80
+ if (this.isImageFile(importPath)) {
81
+ return { type: 'image', path: importPath };
82
+ }
83
+
84
+ return { type: 'unknown', path: importPath };
85
+ }
86
+
87
+ /**
88
+ * Validate array of imports and categorize them
89
+ * Returns categorized imports with warnings
90
+ */
91
+ categorizeImports(imports) {
92
+ const categorized = {
93
+ css: [],
94
+ js: [],
95
+ images: [],
96
+ unknown: []
97
+ };
98
+
99
+ const warnings = [];
100
+
101
+ for (const importPath of imports) {
102
+ const result = this.validateImportPath(importPath);
103
+
104
+ if (result.type === 'unknown') {
105
+ warnings.push(
106
+ `⚠️ Unknown import type: ${importPath}\n` +
107
+ ` Supported: .css/.scss/.sass, .js/.ts, .png/.jpg/.svg`
108
+ );
109
+ }
110
+
111
+ categorized[result.type === 'unknown' ? 'unknown' : result.type].push(result.path);
112
+ }
113
+
114
+ return { categorized, warnings };
115
+ }
116
+
117
+ /**
118
+ * Check if inline style content is empty or whitespace-only
119
+ */
120
+ isEmptyStyle(styleContent) {
121
+ return !styleContent || styleContent.trim().length === 0;
122
+ }
123
+ }