juxscript 1.0.132 → 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.
Files changed (133) hide show
  1. package/README.md +1 -32
  2. package/bin/cli.js +4 -2
  3. package/index.d.ts +200 -0
  4. package/index.js +96 -22
  5. package/juxconfig.example.js +58 -63
  6. package/lib/components/alert.ts +200 -0
  7. package/lib/components/app.ts +247 -0
  8. package/lib/components/badge.ts +101 -0
  9. package/lib/components/base/BaseComponent.ts +421 -0
  10. package/lib/components/base/FormInput.ts +227 -0
  11. package/lib/components/button.ts +178 -0
  12. package/lib/components/card.ts +173 -0
  13. package/lib/components/chart.ts +231 -0
  14. package/lib/components/checkbox.ts +242 -0
  15. package/lib/components/code.ts +123 -0
  16. package/lib/components/container.ts +140 -0
  17. package/lib/components/data.ts +135 -0
  18. package/lib/components/datepicker.ts +234 -0
  19. package/lib/components/dialog.ts +172 -0
  20. package/lib/components/divider.ts +100 -0
  21. package/lib/components/dropdown.ts +186 -0
  22. package/lib/components/element.ts +267 -0
  23. package/lib/components/fileupload.ts +309 -0
  24. package/lib/components/grid.ts +291 -0
  25. package/lib/components/guard.ts +92 -0
  26. package/lib/components/heading.ts +96 -0
  27. package/lib/components/helpers.ts +41 -0
  28. package/lib/components/hero.ts +224 -0
  29. package/lib/components/icon.ts +178 -0
  30. package/lib/components/icons.ts +464 -0
  31. package/lib/components/include.ts +410 -0
  32. package/lib/components/input.ts +457 -0
  33. package/lib/components/list.ts +419 -0
  34. package/lib/components/loading.ts +100 -0
  35. package/lib/components/menu.ts +275 -0
  36. package/lib/components/modal.ts +284 -0
  37. package/lib/components/nav.ts +257 -0
  38. package/lib/components/paragraph.ts +97 -0
  39. package/lib/components/progress.ts +159 -0
  40. package/lib/components/radio.ts +278 -0
  41. package/lib/components/req.ts +303 -0
  42. package/lib/components/script.ts +41 -0
  43. package/lib/components/select.ts +252 -0
  44. package/lib/components/sidebar.ts +275 -0
  45. package/lib/components/style.ts +41 -0
  46. package/lib/components/switch.ts +246 -0
  47. package/lib/components/table.ts +1249 -0
  48. package/lib/components/tabs.ts +250 -0
  49. package/lib/components/theme-toggle.ts +293 -0
  50. package/lib/components/tooltip.ts +144 -0
  51. package/lib/components/view.ts +190 -0
  52. package/lib/components/write.ts +272 -0
  53. package/lib/globals.d.ts +19 -5
  54. package/lib/layouts/default.css +260 -0
  55. package/lib/layouts/figma.css +334 -0
  56. package/lib/reactivity/state.ts +78 -0
  57. package/lib/utils/{fetch.js → fetch.ts} +206 -81
  58. package/machinery/ast.js +347 -0
  59. package/machinery/build.js +466 -0
  60. package/machinery/compiler3.js +6 -66
  61. package/machinery/config.js +6 -93
  62. package/machinery/doc-generator.js +136 -0
  63. package/machinery/imports.js +155 -0
  64. package/machinery/server.js +166 -0
  65. package/machinery/ts-shim.js +46 -0
  66. package/machinery/watcher.js +162 -50
  67. package/package.json +9 -30
  68. package/create/index.jux +0 -77
  69. package/create/layout.jux +0 -18
  70. package/create/style.css +0 -57
  71. package/create/themes/assets/jux.svg +0 -34
  72. package/create/themes/base.css +0 -197
  73. package/create/themes/base2.css +0 -54
  74. package/create/themes/layouts/base.jux +0 -16
  75. package/create/themes/layouts/base_marketing.jux +0 -0
  76. package/create/themes/layouts/base_saas.jux +0 -0
  77. package/lib/componentsv2/base/BaseEngine.d.ts +0 -112
  78. package/lib/componentsv2/base/BaseEngine.js +0 -279
  79. package/lib/componentsv2/base/BaseSkin.d.ts +0 -74
  80. package/lib/componentsv2/base/BaseSkin.js +0 -130
  81. package/lib/componentsv2/base/Neighborhood.d.ts +0 -22
  82. package/lib/componentsv2/base/Neighborhood.js +0 -56
  83. package/lib/componentsv2/base/OptionsContract.d.ts +0 -20
  84. package/lib/componentsv2/base/OptionsContract.js +0 -107
  85. package/lib/componentsv2/base/State.d.ts +0 -18
  86. package/lib/componentsv2/base/State.js +0 -68
  87. package/lib/componentsv2/element/Element.d.ts +0 -30
  88. package/lib/componentsv2/element/Element.js +0 -50
  89. package/lib/componentsv2/element/ElementEngine.d.ts +0 -59
  90. package/lib/componentsv2/element/ElementEngine.js +0 -118
  91. package/lib/componentsv2/element/ElementSkin.d.ts +0 -10
  92. package/lib/componentsv2/element/ElementSkin.js +0 -56
  93. package/lib/componentsv2/element/structure.css +0 -261
  94. package/lib/componentsv2/grid/Grid.d.ts +0 -13
  95. package/lib/componentsv2/grid/Grid.js +0 -27
  96. package/lib/componentsv2/grid/GridEngine.d.ts +0 -77
  97. package/lib/componentsv2/grid/GridEngine.js +0 -153
  98. package/lib/componentsv2/grid/GridSkin.d.ts +0 -11
  99. package/lib/componentsv2/grid/GridSkin.js +0 -84
  100. package/lib/componentsv2/grid/structure.css +0 -27
  101. package/lib/componentsv2/input/Input.d.ts +0 -6
  102. package/lib/componentsv2/input/Input.js +0 -21
  103. package/lib/componentsv2/input/InputEngine.d.ts +0 -70
  104. package/lib/componentsv2/input/InputEngine.js +0 -143
  105. package/lib/componentsv2/input/InputSkin.d.ts +0 -11
  106. package/lib/componentsv2/input/InputSkin.js +0 -89
  107. package/lib/componentsv2/input/structure.css +0 -47
  108. package/lib/componentsv2/list/List.d.ts +0 -49
  109. package/lib/componentsv2/list/List.js +0 -105
  110. package/lib/componentsv2/list/ListEngine.d.ts +0 -121
  111. package/lib/componentsv2/list/ListEngine.js +0 -322
  112. package/lib/componentsv2/list/ListSkin.d.ts +0 -20
  113. package/lib/componentsv2/list/ListSkin.js +0 -345
  114. package/lib/componentsv2/list/structure.css +0 -359
  115. package/lib/componentsv2/plugins/ClientSQLitePlugin.d.ts +0 -21
  116. package/lib/componentsv2/plugins/ClientSQLitePlugin.js +0 -130
  117. package/lib/componentsv2/plugins/IndexedDBPlugin.d.ts +0 -18
  118. package/lib/componentsv2/plugins/IndexedDBPlugin.js +0 -75
  119. package/lib/componentsv2/plugins/LocalStoragePlugin.d.ts +0 -20
  120. package/lib/componentsv2/plugins/LocalStoragePlugin.js +0 -65
  121. package/lib/componentsv2/plugins/ServerSQLitePlugin.d.ts +0 -25
  122. package/lib/componentsv2/plugins/ServerSQLitePlugin.js +0 -70
  123. package/lib/componentsv2/stubs/ComponentComposition.ts.stub +0 -32
  124. package/lib/componentsv2/stubs/ComponentEngine.ts.stub +0 -36
  125. package/lib/componentsv2/stubs/ComponentSkin.ts.stub +0 -35
  126. package/lib/componentsv2/stubs/ComponentStructure.css.d.ts.stub +0 -2
  127. package/lib/componentsv2/stubs/ComponentStructure.css.stub +0 -13
  128. package/lib/utils/fetch.d.ts +0 -176
  129. package/machinery/serve.js +0 -255
  130. package/types/css.d.ts +0 -10
  131. /package/{create/themes/layouts/base_blog.jux → machinery/bundleAssets.js} +0 -0
  132. /package/{create/themes/layouts/base_docs.jux → machinery/bundleJux.js} +0 -0
  133. /package/{create/themes/layouts/base_login.jux → machinery/bundleVendors.js} +0 -0
@@ -23,12 +23,12 @@ export const defaultConfig = {
23
23
  // Load user configuration
24
24
  export async function loadConfig(projectRoot) {
25
25
  const configPath = path.join(projectRoot, 'juxconfig.js');
26
-
26
+
27
27
  if (fs.existsSync(configPath)) {
28
28
  try {
29
29
  const configModule = await import(`file://${configPath}`);
30
30
  const userConfig = configModule.default || configModule;
31
-
31
+
32
32
  return {
33
33
  ...defaultConfig,
34
34
  ...userConfig,
@@ -41,7 +41,7 @@ export async function loadConfig(projectRoot) {
41
41
  return defaultConfig;
42
42
  }
43
43
  }
44
-
44
+
45
45
  console.log('ℹ️ No juxconfig.js found, using defaults');
46
46
  return defaultConfig;
47
47
  }
@@ -51,9 +51,9 @@ export async function runBootstrap(bootstrapFunctions = []) {
51
51
  if (!Array.isArray(bootstrapFunctions) || bootstrapFunctions.length === 0) {
52
52
  return;
53
53
  }
54
-
54
+
55
55
  console.log('🚀 Running bootstrap functions...\n');
56
-
56
+
57
57
  for (const fn of bootstrapFunctions) {
58
58
  if (typeof fn === 'function') {
59
59
  try {
@@ -63,93 +63,6 @@ export async function runBootstrap(bootstrapFunctions = []) {
63
63
  }
64
64
  }
65
65
  }
66
-
66
+
67
67
  console.log('✅ Bootstrap complete\n');
68
- }
69
-
70
- /**
71
- * Type helper for JUX Configuration (Identity function for Autocomplete)
72
- * Used in juxconfig.js to provide Intellisense.
73
- * @param {Object} config
74
- * @returns {Object}
75
- */
76
- export function defineConfig(config) {
77
- return config;
78
- }
79
-
80
- /**
81
- * Normalizes user configuration into the strict format used by the compiler/server.
82
- * Handles "DX Sugar" like:
83
- * - Inferring file extensions (.jux, .css)
84
- * - Mapping 'dist' -> 'distribution'
85
- * - Resolving shortcuts (e.g. layouts)
86
- * - Defaulting ports
87
- */
88
- export function resolveConfig(userConfig, projectRoot = process.cwd()) {
89
- const root = userConfig.root || projectRoot;
90
-
91
- // 1. Directories (Map 'dist' alias to 'distribution')
92
- const dirs = userConfig.directories || {};
93
- const directories = {
94
- source: dirs.source || 'jux',
95
- distribution: dirs.dist || dirs.distribution || '.jux-dist',
96
- themes: dirs.themes || 'themes',
97
- layouts: dirs.layouts || 'themes/layouts',
98
- assets: dirs.assets || 'themes/assets'
99
- };
100
-
101
- // 2. Defaults (Infer extensions)
102
- const defs = userConfig.defaults || {};
103
- const httpPort = defs.port || defs.httpPort || 3000;
104
-
105
- const defaults = {
106
- httpPort,
107
- wsPort: defs.wsPort || (httpPort + 1),
108
- autoRoute: defs.autoRoute !== false, // default true
109
- layout: ensureExt(defs.layout, '.jux') || 'base.jux',
110
- theme: ensureExt(defs.theme, '.css') || 'base.css'
111
- };
112
-
113
- // 3. Pages Normalization (Recursively fix route paths)
114
- const pages = normalizePages(userConfig.pages || {});
115
-
116
- // 4. Return Normalized Config
117
- return {
118
- root,
119
- directories,
120
- defaults,
121
- pages,
122
- hooks: userConfig.hooks || {}
123
- };
124
- }
125
-
126
- /**
127
- * Helper: Appends extension if missing
128
- */
129
- function ensureExt(file, ext) {
130
- if (!file) return file;
131
- return file.endsWith(ext) ? file : `${file}${ext}`;
132
- }
133
-
134
- /**
135
- * Helper: Recursively normalizes page routes
136
- */
137
- function normalizePages(pages) {
138
- const normalized = {};
139
- for (const [key, value] of Object.entries(pages)) {
140
- if (typeof value === 'string') {
141
- // Direct route: '/' -> 'experiments/index'
142
- // Becomes: '/' -> 'experiments/index.jux'
143
- normalized[key] = ensureExt(value, '.jux');
144
- } else if (typeof value === 'object') {
145
- // Route Group
146
- normalized[key] = {
147
- ...value,
148
- layout: value.layout ? ensureExt(value.layout, '.jux') : undefined,
149
- theme: value.theme ? ensureExt(value.theme, '.css') : undefined,
150
- routes: normalizePages(value.routes || {})
151
- };
152
- }
153
- }
154
- return normalized;
155
68
  }
@@ -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
+ }