juxscript 1.1.2 → 1.1.4

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.
Files changed (67) hide show
  1. package/machinery/build3.js +7 -91
  2. package/machinery/compiler3.js +3 -209
  3. package/machinery/config.js +93 -6
  4. package/machinery/serve.js +255 -0
  5. package/machinery/watcher.js +49 -161
  6. package/package.json +19 -5
  7. package/lib/components/alert.ts +0 -200
  8. package/lib/components/app.ts +0 -247
  9. package/lib/components/badge.ts +0 -101
  10. package/lib/components/base/BaseComponent.ts +0 -421
  11. package/lib/components/base/FormInput.ts +0 -227
  12. package/lib/components/button.ts +0 -178
  13. package/lib/components/card.ts +0 -173
  14. package/lib/components/chart.ts +0 -231
  15. package/lib/components/checkbox.ts +0 -242
  16. package/lib/components/code.ts +0 -123
  17. package/lib/components/container.ts +0 -140
  18. package/lib/components/data.ts +0 -135
  19. package/lib/components/datepicker.ts +0 -234
  20. package/lib/components/dialog.ts +0 -172
  21. package/lib/components/divider.ts +0 -100
  22. package/lib/components/dropdown.ts +0 -186
  23. package/lib/components/element.ts +0 -267
  24. package/lib/components/fileupload.ts +0 -309
  25. package/lib/components/grid.ts +0 -291
  26. package/lib/components/guard.ts +0 -92
  27. package/lib/components/heading.ts +0 -96
  28. package/lib/components/helpers.ts +0 -41
  29. package/lib/components/hero.ts +0 -224
  30. package/lib/components/icon.ts +0 -178
  31. package/lib/components/icons.ts +0 -464
  32. package/lib/components/include.ts +0 -410
  33. package/lib/components/input.ts +0 -457
  34. package/lib/components/list.ts +0 -419
  35. package/lib/components/loading.ts +0 -100
  36. package/lib/components/menu.ts +0 -275
  37. package/lib/components/modal.ts +0 -284
  38. package/lib/components/nav.ts +0 -257
  39. package/lib/components/paragraph.ts +0 -97
  40. package/lib/components/progress.ts +0 -159
  41. package/lib/components/radio.ts +0 -278
  42. package/lib/components/req.ts +0 -303
  43. package/lib/components/script.ts +0 -41
  44. package/lib/components/select.ts +0 -252
  45. package/lib/components/sidebar.ts +0 -275
  46. package/lib/components/style.ts +0 -41
  47. package/lib/components/switch.ts +0 -246
  48. package/lib/components/table.ts +0 -1249
  49. package/lib/components/tabs.ts +0 -250
  50. package/lib/components/theme-toggle.ts +0 -293
  51. package/lib/components/tooltip.ts +0 -144
  52. package/lib/components/view.ts +0 -190
  53. package/lib/components/write.ts +0 -272
  54. package/lib/layouts/default.css +0 -260
  55. package/lib/layouts/figma.css +0 -334
  56. package/lib/reactivity/state.ts +0 -78
  57. package/lib/utils/fetch.ts +0 -553
  58. package/machinery/ast.js +0 -347
  59. package/machinery/build.js +0 -466
  60. package/machinery/bundleAssets.js +0 -0
  61. package/machinery/bundleJux.js +0 -0
  62. package/machinery/bundleVendors.js +0 -0
  63. package/machinery/doc-generator.js +0 -136
  64. package/machinery/imports.js +0 -155
  65. package/machinery/server.js +0 -166
  66. package/machinery/ts-shim.js +0 -46
  67. package/machinery/validators/file-validator.js +0 -123
@@ -0,0 +1,255 @@
1
+ import express from 'express';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+ import http from 'http';
5
+ import { fileURLToPath } from 'url';
6
+ import { WebSocketServer } from 'ws';
7
+ import { createWatcher } from './watcher.js';
8
+ import { JuxCompiler } from './compiler3.js';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = path.dirname(__filename);
12
+
13
+ // ═══════════════════════════════════════════════════════════════
14
+ // CONFIGURATION
15
+ // ═══════════════════════════════════════════════════════════════
16
+ const args = process.argv.slice(2);
17
+ const HOT_RELOAD = args.includes('--hot') || args.includes('-h') || args.includes('--watch');
18
+
19
+ // Extract port from args (e.g., --port=3000 or -p 3000)
20
+ function getArgValue(flag, shortFlag, defaultValue) {
21
+ for (let i = 0; i < args.length; i++) {
22
+ if (args[i].startsWith(`${flag}=`)) return args[i].split('=')[1];
23
+ if (args[i].startsWith(`${shortFlag}=`)) return args[i].split('=')[1];
24
+ if ((args[i] === flag || args[i] === shortFlag) && args[i + 1]) return args[i + 1];
25
+ }
26
+ return defaultValue;
27
+ }
28
+
29
+ const PORT = parseInt(getArgValue('--port', '-p', process.env.PORT || '3000'));
30
+ const WS_PORT = parseInt(getArgValue('--ws-port', '-w', process.env.WS_PORT || String(PORT + 1)));
31
+
32
+ // Resolve paths relative to CWD (user's project)
33
+ const PROJECT_ROOT = process.cwd();
34
+ const DIST_DIR = path.resolve(PROJECT_ROOT, '.jux-dist');
35
+ const SRC_DIR = path.resolve(PROJECT_ROOT, 'jux');
36
+
37
+ const app = express();
38
+ let lastBuildResult = { success: true, errors: [] };
39
+
40
+ // Check if dist directory exists - if not, try to build first
41
+ if (!fs.existsSync(DIST_DIR) || !fs.existsSync(path.join(DIST_DIR, 'index.html'))) {
42
+ console.log('⚠️ Dist directory not found. Running initial build...');
43
+
44
+ const compiler = new JuxCompiler({
45
+ srcDir: SRC_DIR,
46
+ distDir: DIST_DIR
47
+ });
48
+
49
+ try {
50
+ const result = await compiler.build();
51
+ lastBuildResult = result;
52
+
53
+ if (!result.success) {
54
+ console.log('\n❌ Initial build failed. Starting server to show error overlay.\n');
55
+ }
56
+ } catch (err) {
57
+ console.error('❌ Initial build failed:', err.message);
58
+ lastBuildResult = { success: false, errors: [{ message: err.message }] };
59
+ }
60
+ }
61
+
62
+ if (!fs.existsSync(DIST_DIR)) {
63
+ fs.mkdirSync(DIST_DIR, { recursive: true });
64
+ }
65
+
66
+ app.use((req, res, next) => {
67
+ res.setHeader('Cache-Control', 'no-store');
68
+ next();
69
+ });
70
+
71
+ app.use((req, res, next) => {
72
+ if (req.path.endsWith('.js')) {
73
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
74
+ }
75
+ next();
76
+ });
77
+
78
+ app.get('/favicon.ico', (req, res) => res.status(204).end());
79
+ app.get('/favicon.png', (req, res) => res.status(204).end());
80
+
81
+ app.get('/__jux_sources.json', (req, res) => {
82
+ const snapshotPath = path.join(DIST_DIR, '__jux_sources.json');
83
+ if (fs.existsSync(snapshotPath)) {
84
+ res.setHeader('Content-Type', 'application/json');
85
+ res.sendFile(snapshotPath);
86
+ } else {
87
+ res.json({});
88
+ }
89
+ });
90
+
91
+ const hotReloadScript = `
92
+ <script>
93
+ (function() {
94
+ var ws = new WebSocket('ws://localhost:${WS_PORT}');
95
+ ws.onopen = function() { console.log('🔥 Hot reload connected'); };
96
+ ws.onmessage = function(e) {
97
+ var data = JSON.parse(e.data);
98
+ if (data.type === 'reload') location.reload();
99
+ else if (data.type === 'build-error') console.error('❌ Build error:', data.errors);
100
+ };
101
+ ws.onclose = function() { setTimeout(function() { location.reload(); }, 2000); };
102
+ })();
103
+ </script>
104
+ `;
105
+
106
+ function getErrorPageHtml(errors) {
107
+ return `<!DOCTYPE html>
108
+ <html lang="en">
109
+ <head>
110
+ <meta charset="UTF-8">
111
+ <title>JUX Build Error</title>
112
+ <style>
113
+ * { margin: 0; padding: 0; box-sizing: border-box; }
114
+ body { font-family: monospace; background: #1a1a2e; color: #eee; min-height: 100vh; padding: 40px; }
115
+ .container { max-width: 800px; margin: 0 auto; }
116
+ h1 { color: #ff6b6b; margin-bottom: 8px; }
117
+ .subtitle { color: #888; margin-bottom: 30px; }
118
+ .error-card { background: #16213e; padding: 16px 20px; border-radius: 8px; margin-bottom: 12px; border-left: 4px solid #ff6b6b; }
119
+ .error-header { color: #ff6b6b; font-weight: bold; margin-bottom: 8px; }
120
+ .error-code { background: #0f0f23; padding: 12px; border-radius: 4px; font-size: 13px; color: #888; }
121
+ </style>
122
+ </head>
123
+ <body>
124
+ <div class="container">
125
+ <h1>🛑 Build Failed</h1>
126
+ <p class="subtitle">Fix the errors below and save to rebuild.</p>
127
+ ${errors.map(err => `
128
+ <div class="error-card">
129
+ <div class="error-header">${err.view ? `[${err.view}] ` : ''}${err.message}</div>
130
+ ${err.code ? `<pre class="error-code">${err.code}</pre>` : ''}
131
+ </div>
132
+ `).join('')}
133
+ </div>
134
+ ${HOT_RELOAD ? `<script>
135
+ var ws = new WebSocket('ws://localhost:${WS_PORT}');
136
+ ws.onmessage = function(e) { if (JSON.parse(e.data).type === 'reload') location.reload(); };
137
+ </script>` : ''}
138
+ </body>
139
+ </html>`;
140
+ }
141
+
142
+ if (HOT_RELOAD) {
143
+ app.get(['/', '/index.html'], (req, res) => {
144
+ const indexPath = path.join(DIST_DIR, 'index.html');
145
+
146
+ if (!fs.existsSync(indexPath) || !lastBuildResult.success) {
147
+ return res.send(getErrorPageHtml(lastBuildResult.errors));
148
+ }
149
+
150
+ let html = fs.readFileSync(indexPath, 'utf8');
151
+ html = html.replace('</body>', hotReloadScript + '</body>');
152
+ res.setHeader('Content-Type', 'text/html');
153
+ res.send(html);
154
+ });
155
+ }
156
+
157
+ app.use(express.static(DIST_DIR));
158
+
159
+ app.get('*', (req, res) => {
160
+ if (path.extname(req.path) && req.path !== '/') {
161
+ return res.status(404).send('Not found');
162
+ }
163
+
164
+ const indexPath = path.join(DIST_DIR, 'index.html');
165
+
166
+ if (!fs.existsSync(indexPath) || !lastBuildResult.success) {
167
+ return res.send(getErrorPageHtml(lastBuildResult.errors));
168
+ }
169
+
170
+ if (HOT_RELOAD) {
171
+ let html = fs.readFileSync(indexPath, 'utf8');
172
+ html = html.replace('</body>', hotReloadScript + '</body>');
173
+ res.setHeader('Content-Type', 'text/html');
174
+ res.send(html);
175
+ } else {
176
+ res.sendFile(indexPath);
177
+ }
178
+ });
179
+
180
+ const server = http.createServer(app);
181
+ let wss = null;
182
+ let watcher = null;
183
+
184
+ if (HOT_RELOAD) {
185
+ wss = new WebSocketServer({ port: WS_PORT });
186
+ const clients = new Set();
187
+
188
+ wss.on('connection', (ws) => {
189
+ clients.add(ws);
190
+ ws.on('close', () => clients.delete(ws));
191
+ });
192
+
193
+ const broadcast = (message) => {
194
+ const data = JSON.stringify(message);
195
+ clients.forEach(client => {
196
+ if (client.readyState === 1) client.send(data);
197
+ });
198
+ };
199
+
200
+ const compiler = new JuxCompiler({
201
+ srcDir: SRC_DIR,
202
+ distDir: DIST_DIR
203
+ });
204
+
205
+ watcher = createWatcher(SRC_DIR, {
206
+ onChange: async (changedFiles) => {
207
+ console.log('🔄 Rebuilding...');
208
+
209
+ try {
210
+ const result = await compiler.build();
211
+ lastBuildResult = result;
212
+
213
+ if (!result.success) {
214
+ console.error('❌ Rebuild failed');
215
+ broadcast({ type: 'build-error', errors: result.errors });
216
+ return;
217
+ }
218
+
219
+ console.log('✅ Rebuild complete');
220
+ broadcast({ type: 'reload', files: changedFiles });
221
+ } catch (err) {
222
+ console.error('❌ Rebuild failed:', err.message);
223
+ lastBuildResult = { success: false, errors: [{ message: err.message }] };
224
+ broadcast({ type: 'build-error', errors: [{ message: err.message }] });
225
+ }
226
+ },
227
+ onReady: () => {
228
+ console.log(`👀 Watching: ${SRC_DIR}`);
229
+ }
230
+ });
231
+ }
232
+
233
+ server.listen(PORT, () => {
234
+ console.log(`\n🚀 JUX Server running at http://localhost:${PORT}`);
235
+ if (HOT_RELOAD) {
236
+ console.log(`🔥 Hot reload: ws://localhost:${WS_PORT}`);
237
+ }
238
+ if (!lastBuildResult.success) {
239
+ console.log(`⚠️ Build has errors - fix them and save\n`);
240
+ }
241
+ });
242
+
243
+ const shutdown = () => {
244
+ console.log('\n👋 Shutting down...');
245
+ if (watcher) watcher.close();
246
+ if (wss) {
247
+ wss.clients.forEach(client => client.terminate());
248
+ wss.close();
249
+ }
250
+ server.close(() => process.exit(0));
251
+ setTimeout(() => process.exit(0), 2000);
252
+ };
253
+
254
+ process.on('SIGINT', shutdown);
255
+ process.on('SIGTERM', shutdown);
@@ -1,171 +1,59 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- import {
4
- copyLibToOutput,
5
- bundleJuxFilesToRouter,
6
- generateIndexHtml
7
- } from './compiler.js';
8
-
9
- let isRebuilding = false;
10
- let rebuildQueued = false;
11
3
 
12
4
  /**
13
- * Find all .jux files in a directory
5
+ * Watch a directory for changes and trigger callbacks
14
6
  */
15
- function findJuxFiles(dir, fileList = []) {
16
- if (!fs.existsSync(dir)) return fileList;
17
-
18
- const files = fs.readdirSync(dir);
19
-
20
- files.forEach(file => {
21
- const filePath = path.join(dir, file);
22
- const stat = fs.statSync(filePath);
23
-
24
- if (stat.isDirectory()) {
25
- if (file !== 'node_modules' && file !== 'jux-dist' && file !== '.git' && file !== 'server') {
26
- findJuxFiles(filePath, fileList);
27
- }
28
- } else if (file.endsWith('.jux')) {
29
- fileList.push(filePath);
30
- }
7
+ export function createWatcher(srcDir, options = {}) {
8
+ const {
9
+ onChange = () => { },
10
+ onReady = () => { },
11
+ debounceMs = 100,
12
+ extensions = ['.jux', '.js', '.css']
13
+ } = options;
14
+
15
+ const absoluteSrcDir = path.resolve(srcDir);
16
+ let debounceTimer = null;
17
+ let pendingChanges = new Set();
18
+
19
+ console.log(`👀 Watching: ${absoluteSrcDir}`);
20
+
21
+ // Debounced change handler
22
+ const handleChange = (eventType, filename) => {
23
+ if (!filename) return;
24
+
25
+ // Filter by extension
26
+ const ext = path.extname(filename);
27
+ if (!extensions.includes(ext)) return;
28
+
29
+ pendingChanges.add(filename);
30
+
31
+ // Debounce rapid changes
32
+ if (debounceTimer) clearTimeout(debounceTimer);
33
+ debounceTimer = setTimeout(() => {
34
+ const changes = [...pendingChanges];
35
+ pendingChanges.clear();
36
+
37
+ console.log(`📝 Changed: ${changes.join(', ')}`);
38
+ onChange(changes);
39
+ }, debounceMs);
40
+ };
41
+
42
+ // Start watching
43
+ const watcher = fs.watch(absoluteSrcDir, { recursive: true }, handleChange);
44
+
45
+ watcher.on('error', (err) => {
46
+ console.error('❌ Watcher error:', err);
31
47
  });
32
48
 
33
- return fileList;
34
- }
35
-
36
- /**
37
- * Full rebuild of the entire bundle
38
- */
39
- async function fullRebuild(juxSource, distDir) {
40
- const startTime = performance.now(); // ✅ Start timing
41
- console.log('\n🔄 Rebuilding bundle...');
42
-
43
- try {
44
- // Find all .jux files
45
- const projectJuxFiles = findJuxFiles(juxSource);
46
- console.log(` Found ${projectJuxFiles.length} .jux file(s)`);
47
-
48
- // ✅ Time the bundling step
49
- const bundleStartTime = performance.now();
50
-
51
- // Bundle all files
52
- const mainJsFilename = await bundleJuxFilesToRouter(juxSource, distDir, {
53
- routePrefix: ''
54
- });
55
-
56
- const bundleTime = performance.now() - bundleStartTime;
57
-
58
- // ✅ Time the route generation step
59
- const routeStartTime = performance.now();
60
-
61
- // Generate routes for index.html
62
- const routes = projectJuxFiles.map(juxFile => {
63
- const relativePath = path.relative(juxSource, juxFile);
64
- const parsedPath = path.parse(relativePath);
65
-
66
- const rawFunctionName = parsedPath.dir
67
- ? `${parsedPath.dir.replace(/\//g, '_')}_${parsedPath.name}`
68
- : parsedPath.name;
69
-
70
- const functionName = rawFunctionName
71
- .replace(/[-_]/g, ' ')
72
- .split(' ')
73
- .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
74
- .join('');
75
-
76
- const routePath = '/' + (parsedPath.dir ? `${parsedPath.dir}/` : '') + parsedPath.name;
77
-
78
- return {
79
- path: routePath.replace(/\/+/g, '/'),
80
- functionName
81
- };
82
- });
83
-
84
- // Generate index.html
85
- generateIndexHtml(distDir, routes, mainJsFilename);
86
-
87
- const routeTime = performance.now() - routeStartTime;
88
- const totalTime = performance.now() - startTime;
49
+ onReady();
89
50
 
90
- // Pretty-print timing breakdown
91
- console.log(`\n⏱️ Rebuild Performance:`);
92
- console.log(` Bundle generation: ${bundleTime.toFixed(0)}ms`);
93
- console.log(` Route/index.html: ${routeTime.toFixed(0)}ms`);
94
- console.log(` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
95
- console.log(` Total rebuild: ${totalTime.toFixed(0)}ms`);
96
-
97
- // ✅ Color-coded performance indicator
98
- if (totalTime < 100) {
99
- console.log(` ✅ Lightning fast! ⚡`);
100
- } else if (totalTime < 500) {
101
- console.log(` ✅ Fast rebuild`);
102
- } else if (totalTime < 1000) {
103
- console.log(` ⚠️ Moderate speed`);
104
- } else {
105
- console.log(` 🐌 Slow rebuild (consider optimizing)`);
106
- }
107
-
108
- console.log(`✅ Bundle rebuilt: ${mainJsFilename}\n`);
109
- return true;
110
-
111
- } catch (err) {
112
- const failTime = performance.now() - startTime;
113
- console.error(`❌ Rebuild failed after ${failTime.toFixed(0)}ms:`, err.message);
114
- return false;
115
- }
116
- }
117
-
118
- /**
119
- * Start watching for file changes and rebuild on change
120
- */
121
- export function startWatcher(juxSource, distDir, wsClients) {
122
- console.log(`👀 Watching: ${juxSource}`);
123
-
124
- const watcher = fs.watch(juxSource, { recursive: true }, async (eventType, filename) => {
125
- // Ignore non-.jux files and certain patterns
126
- if (!filename ||
127
- !filename.endsWith('.jux') ||
128
- filename.includes('node_modules') ||
129
- filename.includes('jux-dist') ||
130
- filename.startsWith('.')) {
131
- return;
132
- }
133
-
134
- // Debounce: If already rebuilding, queue another rebuild
135
- if (isRebuilding) {
136
- rebuildQueued = true;
137
- return;
51
+ // Return control object
52
+ return {
53
+ close: () => {
54
+ if (debounceTimer) clearTimeout(debounceTimer);
55
+ watcher.close();
56
+ console.log('👋 Watcher closed');
138
57
  }
139
-
140
- isRebuilding = true;
141
- console.log(`\n📝 File changed: ${filename}`);
142
-
143
- // Rebuild the entire bundle
144
- const success = await fullRebuild(juxSource, distDir);
145
-
146
- isRebuilding = false;
147
-
148
- // Notify all WebSocket clients to reload
149
- if (success && wsClients && wsClients.length > 0) {
150
- console.log(`🔌 Notifying ${wsClients.length} client(s) to reload`);
151
-
152
- // ✅ Add small delay to ensure file is fully written
153
- setTimeout(() => {
154
- wsClients.forEach(client => {
155
- if (client.readyState === 1) { // OPEN
156
- client.send(JSON.stringify({ type: 'reload' }));
157
- }
158
- });
159
- }, 100);
160
- }
161
-
162
- // Process queued rebuild if needed
163
- if (rebuildQueued) {
164
- rebuildQueued = false;
165
- console.log('🔄 Processing queued rebuild...');
166
- setTimeout(() => watcher.emit('change', 'change', filename), 500);
167
- }
168
- });
169
-
170
- return watcher;
58
+ };
171
59
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "juxscript",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "type": "module",
5
5
  "description": "A JavaScript UX authorship platform",
6
6
  "main": "index.js",
@@ -19,14 +19,25 @@
19
19
  "./package.json": "./package.json"
20
20
  },
21
21
  "files": [
22
- "bin",
23
- "lib",
24
- "machinery",
25
22
  "index.js",
26
23
  "index.d.ts",
24
+ "bin",
25
+ "create/*.jux",
26
+ "lib/**/*.js",
27
+ "lib/**/*.d.ts",
28
+ "machinery/build3.js",
29
+ "machinery/compiler3.js",
30
+ "machinery/config.js",
31
+ "machinery/serve.js",
32
+ "machinery/watcher.js",
33
+ "types",
27
34
  "juxconfig.example.js",
28
35
  "README.md",
29
- "LICENSE"
36
+ "LICENSE",
37
+ "!lib/**/*.test.js",
38
+ "!lib/**/*.spec.js",
39
+ "!lib/previews/**",
40
+ "!**/*.map"
30
41
  ],
31
42
  "bin": {
32
43
  "jux": "./bin/cli.js"
@@ -46,6 +57,7 @@
46
57
  },
47
58
  "dependencies": {
48
59
  "acorn": "^8.15.0",
60
+ "astray": "^1.1.1",
49
61
  "axios": "^1.6.0",
50
62
  "chart.js": "^4.5.1",
51
63
  "esbuild": "^0.19.0",
@@ -54,10 +66,12 @@
54
66
  },
55
67
  "devDependencies": {
56
68
  "@types/express": "^4.17.17",
69
+ "@types/jsdom": "^27.0.0",
57
70
  "@types/node": "^20.0.0",
58
71
  "@types/ws": "^8.5.5",
59
72
  "acorn-walk": "^8.3.4",
60
73
  "jsdom": "^27.4.0",
74
+ "ts-node": "^10.9.2",
61
75
  "typescript": "^5.0.0"
62
76
  }
63
77
  }