All files / src/rendering html-renderer.js

68.14% Statements 246/361
47.05% Branches 16/34
40% Functions 6/15
68.14% Lines 246/361

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 4231x 1x 1x 1x                                   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x   9x 9x 9x       9x 9x 9x   9x 9x 9x 9x 9x   9x   9x       9x   1x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x   30x 2x 30x 2x 2x 30x   30x 26x 26x 26x 26x 30x     30x 30x   1x 1x 1x 1x 26x   26x 26x       26x 26x 21x 21x 21x       21x   26x 26x                   26x 26x         26x 26x 26x 26x     26x                       26x   1x 1x 1x 1x                   1x 1x 1x 1x 26x   26x 26x 26x 26x 26x 26x       26x 26x   26x 26x   26x 26x 26x 26x 26x   26x 26x 26x 18x 18x 18x 18x 18x                 18x 18x 18x 18x   26x 26x 26x 8x 8x 8x 8x 8x   26x 26x   26x 26x 20x 20x 20x 20x 20x   26x 26x 26x 1x   1x   1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   1x   1x   1x 1x 1x 1x                               1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x         1x 1x 1x 1x       1x 1x 1x 1x           1x 1x 1x 1x             1x 1x 1x 1x                           1x 1x 1x 1x                          
/**
 * High-performance HTML renderer with caching, monitoring, and streaming support
 * Converts object-based components to HTML strings with advanced optimizations
 */
 
import { BaseRenderer, RendererUtils } from './base-renderer.js';
import {
    hasChildren,
    normalizeChildren,
} from '../core/object-utils.js';
 
import {
    escapeHtml,
    isVoidElement,
    formatAttributes,
    minifyHtml
} from '../core/html-utils.js';
 
import { performanceMonitor } from '../performance/monitor.js';
import { createCacheManager } from '../performance/cache-manager.js';
 
// Create a global cache instance for the renderer
const rendererCache = createCacheManager({
    maxSize: 1000,
    ttlMs: 300000 // 5 minutes
});
 
/**
 * HTML Renderer Class extending BaseRenderer
 * 
 * @class HTMLRenderer
 * @extends BaseRenderer
 * @description High-performance HTML renderer with caching, monitoring, and streaming support.
 * Converts object-based components to HTML strings with advanced optimizations.
 * 
 * @param {Object} [options={}] - Renderer configuration options
 * @param {boolean} [options.enableCache=true] - Enable component caching
 * @param {boolean} [options.enableMonitoring=true] - Enable performance monitoring
 * @param {boolean} [options.minify=false] - Enable HTML minification
 * @param {boolean} [options.streaming=false] - Enable streaming mode
 * @param {number} [options.maxDepth=100] - Maximum rendering depth
 * @param {number} [options.cacheSize=1000] - Cache size limit
 * @param {number} [options.cacheTTL=300000] - Cache TTL in milliseconds
 * 
 * @example
 * const renderer = new HTMLRenderer({
 *   enableCache: true,
 *   enableMonitoring: true,
 *   minify: true
 * });
 * 
 * const html = renderer.render({ div: { text: 'Hello World' } });
 */
class HTMLRenderer extends BaseRenderer {
    constructor(options = {}) {
        super({
            enableCache: options.enableCache !== false,
            enableMonitoring: options.enableMonitoring !== false,
            minify: options.minify || false,
            streaming: options.streaming || false,
            maxDepth: options.maxDepth || 100,
            ...options
        });
        
        // Initialize cache if enabled
        if (this.config.enableCache && !this.cache) {
            this.cache = rendererCache;
        }
    }
 
    /**
     * Main render method - converts components to HTML string
     * 
     * @param {Object|Array|string|Function} component - Component to render
     * @param {Object} [options={}] - Rendering options
     * @param {Object} [options.context] - Rendering context
     * @param {boolean} [options.enableCache] - Override cache setting
     * @param {number} [options.depth=0] - Current rendering depth
     * @returns {string} Rendered HTML string
     * 
     * @example
     * const html = renderer.render({
     *   div: {
     *     className: 'container',
     *     children: [
     *       { h1: { text: 'Title' } },
     *       { p: { text: 'Content' } }
     *     ]
     *   }
     * });
     */
    render(component, options = {}) {
        const config = { ...this.config, ...options };
        this.startTiming();
 
        try {
            // Input validation
            if (config.validateInput && !this.isValidComponent(component)) {
                throw new Error('Invalid component structure');
            }
 
            // Main rendering logic
            const html = this.renderComponent(component, config, 0);
            const finalHtml = config.minify ? minifyHtml(html, config) : html;
 
            // Performance monitoring
            this.endTiming();
            this.recordPerformance('renderToString', this.metrics.startTime, false, { 
                cacheEnabled: config.enableCache 
            });
 
            return finalHtml;
 
        } catch (error) {
            this.recordError('renderToString', error);
            throw error;
        }
    }
 
    /**
     * Render a single component with full optimization pipeline
     */
    renderComponent(component, options, depth = 0) {
        // Use base class depth validation
        this.validateDepth(depth);
        
        // Use base class component type processing
        const { type, value } = this.processComponentType(component);
        
        switch (type) {
            case 'empty':
                return '';
            case 'text':
                return escapeHtml(value);
            case 'function':
                const result = this.executeFunctionComponent(value, depth);
                return this.renderComponent(result, options, depth + 1);
            case 'array':
                return value.map(child => this.renderComponent(child, options, depth + 1)).join('');
            case 'element':
                // Process object-based component
                const tagName = Object.keys(value)[0];
                const elementContent = value[tagName];
                return this.renderElement(tagName, elementContent, options, depth);
            default:
                this.recordError('renderComponent', new Error(`Unknown component type: ${type}`));
                return '';
        }
    }
 
    /**
     * Render an HTML element with advanced caching and optimization
     */
    renderElement(tagName, element, options, depth = 0) {
        const startTime = performance.now();
 
        // Track element usage for performance analysis (via stats in the new cache manager)
        if (options.enableMonitoring && this.cache) {
            // The new cache manager tracks usage automatically via get/set operations
        }
 
        // Check cache first for static elements
        if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
            const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
            const cached = this.cache.get('static', cacheKey);
            if (cached) {
                this.recordPerformance(tagName, startTime, true);
                return cached.value; // Return the cached HTML
            }
        }
 
        // Handle text-only elements including booleans
        if (typeof element === 'string' || typeof element === 'number' || typeof element === 'boolean') {
            const html = isVoidElement(tagName)
                ? `<${tagName}>`
                : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
 
            this.cacheIfStatic(tagName, element, html, options);
            this.recordPerformance(tagName, startTime, false);
            return html;
        }
 
        // Handle function elements
        if (typeof element === 'function') {
            const result = this.executeFunctionComponent(element, depth);
            return this.renderElement(tagName, result, options, depth);
        }
 
        // Handle object elements (complex elements with props and children)
        if (element && typeof element === 'object') {
            return this.renderObjectElement(tagName, element, options, depth);
        }
 
        // Handle null and undefined by returning empty tags
        if (element === null || element === undefined) {
            const html = isVoidElement(tagName)
                ? `<${tagName}>`
                : `<${tagName}></${tagName}>`;
            this.recordPerformance(tagName, startTime, false);
            return html;
        }
 
        // Fallback for any other types
        const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
        this.recordPerformance(tagName, startTime, false);
        return html;
    }
 
    /**
     * Cache element if it's static
     */
    cacheIfStatic(tagName, element, html) {
        if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
            const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
            this.cache.set('static', cacheKey, html, {
                ttlMs: this.config.cacheTTL || 5 * 60 * 1000, // 5 minutes default
                size: html.length // Approximate size
            });
        }
    }
 
    /**
     * Render complex object elements with attributes and children
     */
    renderObjectElement(tagName, element, options, depth = 0) {
        const startTime = performance.now();
 
        // Check component-level cache
        if (options.enableCache && this.cache) {
            const cacheKey = RendererUtils.generateCacheKey(tagName, element);
            if (cacheKey) {
                const cached = this.cache.get(cacheKey);
                if (cached) {
                    this.recordPerformance(tagName, startTime, true);
                    return cached;
                }
            }
        }
 
        // Extract props and children directly from element content
        const { children, text, ...attributes } = element || {};
 
        // Build opening tag with attributes
        const attributeString = formatAttributes(attributes);
        const openingTag = attributeString
            ? `<${tagName} ${attributeString}>`
            : `<${tagName}>`;
 
        // Handle text content
        let textContent = '';
        if (text !== undefined) {
            const isScript = tagName === 'script';
            const isStyle = tagName === 'style';
            const isRawTag = isScript || isStyle;
            const raw = typeof text === 'function' ? String(text()) : String(text);
            if (isRawTag) {
                // Prevent </script> or </style> early-terminating the tag
                const safe = raw
                  .replace(/<\/(script)/gi, '<\\/$1')
                  .replace(/<\/(style)/gi, '<\\/$1')
                  // Escape problematic Unicode line separators in JS
                  .replace(/\u2028/g, '\\u2028')
                  .replace(/\u2029/g, '\\u2029');
                textContent = safe;
            } else {
                textContent = escapeHtml(raw);
            }
        }
 
        // Handle children
        let childrenHtml = '';
        if (hasChildren(element)) {
            const normalizedChildren = normalizeChildren(children);
            childrenHtml = normalizedChildren
                .map(child => this.renderComponent(child, options, depth + 1))
                .join('');
        }
 
        // Build complete HTML
        const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;
 
        // Cache the result if appropriate
        if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {
            const cacheKey = RendererUtils.generateCacheKey(tagName, element);
            if (cacheKey) {
                this.cache.set(cacheKey, html);
            }
        }
 
        this.recordPerformance(tagName, startTime, false);
        return html;
    }
}
 
// Note: globalCache is now imported from cache-manager.js
 
/**
 * Main render function - converts object components to HTML
 */
export function renderToString(component, options = {}) {
    // Merge default options with provided options
    const mergedOptions = {
        enableCache: true,
        enableMonitoring: false,
        ...options
    };
    
    const renderer = new HTMLRenderer(mergedOptions);
    return renderer.render(component, mergedOptions);
}
 
// Old functions removed - now part of HTMLRenderer class
 
// Old helper functions removed - now available in RendererUtils from BaseRenderer
 
/**
 * Batch rendering for multiple components
 */
export function renderBatch(components, options = {}) {
    if (!Array.isArray(components)) {
        throw new Error('renderBatch expects an array of components');
    }
 
    // Merge default options with provided options
    const mergedOptions = {
        enableCache: true,
        enableMonitoring: false,
        ...options
    };
 
    const renderer = new HTMLRenderer(mergedOptions);
    return components.map(component => renderer.render(component, mergedOptions));
}
 
/**
 * Render to chunks for large output (fake streaming - renders full HTML then chunks it)
 * For true progressive streaming, use the streaming-renderer.js renderToStream function
 */
export function* renderToChunks(component, options = {}) {
    // Merge default options with provided options
    const mergedOptions = {
        enableCache: true,
        enableMonitoring: false,
        ...options,
        chunkSize: options.chunkSize || 1024 // Default 1KB chunks
    };
    
    const html = renderToString(component, mergedOptions);
    
    for (let i = 0; i < html.length; i += mergedOptions.chunkSize) {
        yield html.slice(i, i + mergedOptions.chunkSize);
    }
}
 
/**
 * @deprecated Use renderToChunks instead. This function will be removed in a future version.
 * For true progressive streaming, use the streaming-renderer.js renderToStream function.
 */
export async function* renderToStream(component, options = {}) {
    console.warn('renderToStream from html-renderer is deprecated. Use renderToChunks for chunking or streaming-renderer.js renderToStream for true streaming.');
    return yield* renderToChunks(component, options);
}
 
/**
 * Get global cache instance for external access
 */
export function getCache() {
    return rendererCache;
}
 
/**
 * Reset cache (useful for testing)
 */
export function resetCache() {
    if (rendererCache) {
        rendererCache.clear();
    }
}
 
/**
 * Get rendering statistics
 */
export function getRenderingStats() {
    return {
        cache: rendererCache ? rendererCache.getStats() : null,
        performance: performanceMonitor.getStats()
    };
}
 
/**
 * Precompile static components for maximum performance
 */
export function precompileComponent(component, options = {}) {
    if (!isStaticElement(component)) {
        throw new Error('Can only precompile static components');
    }
 
    const html = renderToString(component, { ...options, enableCache: false });
 
    return {
        html,
        isPrecompiled: true,
        render: () => html
    };
}
 
/**
 * Development helper - render with detailed timing
 */
export function renderWithTiming(component, options = {}) {
    const start = performance.now();
    const html = renderToString(component, { ...options, enableMonitoring: true });
    const end = performance.now();
 
    return {
        html,
        timing: {
            total: end - start,
            breakdown: performanceMonitor.getStats()
        }
    };
}