Files
markitect-main/test_js_fixes.py
tegwick 76b5bb1106 fix: resolve JavaScript const redeclaration and MarkitectMain issues
**JavaScript Fixes:**
- Fixed const redeclaration error: removed duplicate MARKITECT_STRICT_MODE declaration from control-base.js
- Fixed MarkitectMain not available: updated plugin to load main-updated.js instead of main.js
- Added MARKITECT_STRICT_MODE declaration to main-updated.js for consistency
- Ensured only one main file is loaded to prevent conflicts

**Plugin Asset Updates:**
- Changed testdrive-jsui plugin asset list from main.js to main-updated.js
- Verified proper loading order and dependency resolution
- All JavaScript constants now declared exactly once

**Testing Infrastructure:**
- Comprehensive JavaScript fix verification test
- Browser-ready test file generation for manual verification
- Automated const declaration conflict detection
- Asset loading order validation

**Key Fixes:**
-  "Uncaught SyntaxError: redeclaration of const MARKITECT_STRICT_MODE" →  Resolved
-  "⚠️ MarkitectMain not available, edit functionality may be limited" →  Resolved
-  Multiple main.js files causing conflicts →  Single main-updated.js loaded

**Verification Results:**
```
 No const declaration conflicts
 MarkitectMain properly declared once
 Correct main-updated.js file loaded
 HTML references correct scripts
```

Browser console should now show:
- 🎯 "TestDrive JSUI loading complete, initializing..."
- 🚀 "Starting MarkitectMain initialization..."
-  No redeclaration errors

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-14 09:25:00 +01:00

140 lines
5.3 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Test JavaScript fixes for const redeclaration and MarkitectMain issues
"""
import sys
from pathlib import Path
import re
# Add current directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
def test_javascript_fixes():
"""Test that JavaScript const redeclaration and MarkitectMain issues are resolved."""
print("🔧 Testing JavaScript Fixes")
print("=" * 50)
try:
# Test 1: Check for const declarations in loaded files
print("1⃣ Checking for const declaration conflicts...")
from markitect.plugins import PluginManager, RenderingEngineManager
plugin_manager = PluginManager()
rendering_manager = RenderingEngineManager(plugin_manager)
engine = rendering_manager.get_engine('testdrive-jsui')
required_assets = engine.get_required_assets()
js_files = required_assets.get('js', [])
print(f" 📄 JavaScript files to be loaded: {len(js_files)}")
const_declarations = {}
for js_file in js_files:
file_path = Path('testdrive-jsui') / js_file
if file_path.exists():
content = file_path.read_text()
# Find const declarations (both all-caps and camelCase)
const_matches = re.findall(r'^const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=', content, re.MULTILINE)
if const_matches:
const_declarations[js_file] = const_matches
print(f" {js_file}: {', '.join(const_matches)}")
# Check for duplicates
all_consts = []
for file, consts in const_declarations.items():
all_consts.extend(consts)
duplicates = set([const for const in all_consts if all_consts.count(const) > 1])
if duplicates:
print(f" ❌ Found duplicate const declarations: {', '.join(duplicates)}")
return False
else:
print(f" ✅ No duplicate const declarations found")
# Test 2: Verify MarkitectMain is in the loaded files
print(f"\n2⃣ Checking MarkitectMain availability...")
markitect_main_files = [f for f, consts in const_declarations.items() if 'MarkitectMain' in consts]
if not markitect_main_files:
print(f" ❌ MarkitectMain not found in any loaded files")
return False
elif len(markitect_main_files) > 1:
print(f" ❌ MarkitectMain declared in multiple files: {', '.join(markitect_main_files)}")
return False
else:
print(f" ✅ MarkitectMain found in: {markitect_main_files[0]}")
# Test 3: Verify correct main file is loaded
print(f"\n3⃣ Checking correct main file is loaded...")
if 'static/js/main-updated.js' in js_files and 'static/js/main.js' not in js_files:
print(f" ✅ Correct main file loaded: main-updated.js")
elif 'static/js/main.js' in js_files:
print(f" ❌ Wrong main file loaded: main.js (should be main-updated.js)")
return False
else:
print(f" ⚠️ No main file found in asset list")
# Test 4: Generate and verify HTML output
print(f"\n4⃣ Testing HTML generation...")
from markitect.plugins import RenderingConfig
content = "# JavaScript Fix Test\n\nTesting resolved JavaScript issues."
output_dir = Path('/tmp/test_js_fixes_verification')
output_dir.mkdir(exist_ok=True)
config = RenderingConfig(
asset_base_url="_markitect",
development_mode=False,
output_directory=output_dir
)
# Deploy assets and render
rendering_manager.deploy_engine_assets('testdrive-jsui', config)
html_content = engine.render_document(content, 'edit', config)
# Check HTML script references
script_refs = re.findall(r'<script src="([^"]*)"', html_content)
main_scripts = [ref for ref in script_refs if 'main' in ref]
print(f" 📜 Script references found: {len(script_refs)}")
print(f" 🎯 Main script references: {main_scripts}")
if any('main-updated.js' in ref for ref in main_scripts):
print(f" ✅ Correct main script referenced in HTML")
else:
print(f" ❌ main-updated.js not found in HTML script references")
return False
if any('main.js' in ref and 'main-updated.js' not in ref for ref in main_scripts):
print(f" ❌ Incorrect main.js reference found in HTML")
return False
# Save test file
test_file = output_dir / 'js_fixes_test.html'
test_file.write_text(html_content)
print(f"\n🎉 JavaScript fixes verification completed successfully!")
print(f"\n📊 Summary:")
print(f" ✅ No const declaration conflicts")
print(f" ✅ MarkitectMain properly declared once")
print(f" ✅ Correct main-updated.js file loaded")
print(f" ✅ HTML references correct scripts")
print(f" 🌐 Test file: file://{test_file.absolute()}")
return True
except Exception as e:
print(f"❌ JavaScript fixes test failed: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
success = test_javascript_fixes()
sys.exit(0 if success else 1)