All files / src/performance bundle-optimizer.js

59.57% Statements 112/188
61.11% Branches 11/18
81.81% Functions 9/11
59.57% Lines 112/188

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 2211x 1x 1x   1x 1x 2x 2x 2x 2x 2x   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   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 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  
/**
 * Bundle size optimization through tree-shaking and code analysis
 */
 
export class BundleOptimizer {
    constructor() {
        this.usedComponents = new Set();
        this.usedUtilities = new Set();
        this.componentDependencies = new Map();
        this.unusedCode = new Set();
    }
 
    // Analyze component tree to identify what's actually used
    analyzeUsage(rootComponent, props = {}) {
        const analysisContext = {
            componentStack: [],
            propsFlow: new Map(),
            conditionalBranches: new Set()
        };
 
        this.traverseComponent(rootComponent, props, analysisContext);
        return this.generateOptimizationReport();
    }
 
    traverseComponent(component, props, context) {
        const componentName = this.getComponentName(component);
 
        // Track component usage
        this.usedComponents.add(componentName);
        context.componentStack.push(componentName);
 
        // Track props flow for optimization
        context.propsFlow.set(componentName, Object.keys(props));
 
        // Analyze component implementation
        if (typeof component === 'function') {
            this.analyzeFunctionComponent(component, props, context);
        } else if (typeof component === 'object') {
            this.analyzeObjectComponent(component, context);
        }
 
        context.componentStack.pop();
    }
 
    analyzeFunctionComponent(component, props, context) {
        const componentStr = component.toString();
 
        // Detect conditional rendering patterns
        const conditionalPatterns = [
            /\?\s*\{/g,  // Conditional objects
            /&&\s*\{/g,  // Logical AND rendering
            /if\s*\(/g   // If statements
        ];
 
        for (const pattern of conditionalPatterns) {
            const matches = componentStr.match(pattern);
            if (matches) {
                context.conditionalBranches.add(`${this.getComponentName(component)}_conditional`);
            }
        }
 
        // Try to execute with sample props to discover runtime paths
        try {
            const result = component(props);
            if (result) {
                this.traverseComponent(result, {}, context);
            }
        } catch {
            // Component might need specific props, skip runtime analysis
        }
    }
 
    analyzeObjectComponent(obj, context) {
        if (Array.isArray(obj)) {
            obj.forEach(item => {
                if (item && typeof item === 'object') {
                    this.traverseComponent(item, {}, context);
                }
            });
            return;
        }
 
        const keys = Object.keys(obj);
        if (keys.length === 1) {
            const tagName = keys[0];
            const props = obj[tagName];
 
            // Track HTML tag usage
            this.usedComponents.add(`html_${tagName}`);
 
            // Traverse children
            if (props && typeof props === 'object') {
                if (props.children) {
                    if (Array.isArray(props.children)) {
                        props.children.forEach(child => {
                            this.traverseComponent(child, {}, context);
                        });
                    } else {
                        this.traverseComponent(props.children, {}, context);
                    }
                }
            }
        }
    }
 
    getComponentName(component) {
        if (typeof component === 'function') {
            return component.name || 'AnonymousFunction';
        }
        if (typeof component === 'object' && component) {
            const keys = Object.keys(component);
            return keys.length > 0 ? `Object_${keys[0]}` : 'EmptyObject';
        }
        return 'Unknown';
    }
 
    // Generate optimization recommendations
    generateOptimizationReport() {
        return {
            usedComponents: Array.from(this.usedComponents),
            componentDependencies: Object.fromEntries(this.componentDependencies),
            optimizationOpportunities: this.findOptimizationOpportunities(),
            bundleEstimate: this.estimateBundleSize(),
            recommendations: this.generateRecommendations()
        };
    }
 
    findOptimizationOpportunities() {
        const opportunities = [];
 
        // Check for unused utilities
        const coreUtilities = ['validateCoherentObject', 'mergeProps', 'cloneCoherentObject'];
        const unusedUtilities = coreUtilities.filter(util => !this.usedUtilities.has(util));
 
        if (unusedUtilities.length > 0) {
            opportunities.push({
                type: 'unused_utilities',
                impact: 'medium',
                description: `Remove unused utilities: ${unusedUtilities.join(', ')}`,
                estimatedSavings: unusedUtilities.length * 2 // KB estimate
            });
        }
 
        // Check for component consolidation opportunities
        const htmlComponents = Array.from(this.usedComponents)
            .filter(name => name.startsWith('html_'));
 
        if (htmlComponents.length < 10) {
            opportunities.push({
                type: 'minimal_html_tags',
                impact: 'high',
                description: 'Create minimal HTML tag bundle for smaller apps',
                estimatedSavings: 15 // KB estimate
            });
        }
 
        return opportunities;
    }
 
    estimateBundleSize() {
        const baseFrameworkSize = 25; // KB
        const componentOverhead = this.usedComponents.size * 0.5; // KB per component
        const utilitySize = this.usedUtilities.size * 2; // KB per utility
 
        return {
            estimated: baseFrameworkSize + componentOverhead + utilitySize,
            breakdown: {
                framework: baseFrameworkSize,
                components: componentOverhead,
                utilities: utilitySize
            }
        };
    }
 
    generateRecommendations() {
        const recommendations = [];
 
        if (this.usedComponents.size < 5) {
            recommendations.push({
                priority: 'high',
                action: 'Consider creating a minimal bundle with only required components',
                impact: 'Reduce bundle size by 40-60%'
            });
        }
 
        if (this.usedComponents.size > 50) {
            recommendations.push({
                priority: 'medium',
                action: 'Implement code-splitting to load components on demand',
                impact: 'Improve initial load time by 30-50%'
            });
        }
 
        return recommendations;
    }
 
    // Generate optimized bundle configuration
    generateOptimizedConfig() {
        return {
            entryPoints: {
                core: ['./src/coherent.js'],
                components: Array.from(this.usedComponents)
                    .filter(name => !name.startsWith('html_'))
                    .map(name => `./src/components/${name}.js`),
                utilities: Array.from(this.usedUtilities)
                    .map(name => `./src/core/${name}.js`)
            },
            treeShaking: {
                unusedExports: Array.from(this.unusedCode),
                sideEffects: false
            },
            optimization: {
                minify: true,
                splitChunks: this.usedComponents.size > 20
            }
        };
    }
}
 
export const bundleOptimizer = new BundleOptimizer();