All files / lib compiler.js

78.62% Statements 228/290
73.68% Branches 14/19
84.61% Functions 11/13
78.62% Lines 228/290

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 2912x 2x 2x 2x 2x 2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 2x 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 2x 2x 2x 2x 2x 2x 1x             1x 2x 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 2x 2x 2x 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 18x 18x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x                         1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x                       1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 2x 2x 2x  
const fs = require('fs');
const path = require('path');
const StyleProcessor = require('./compiler/StyleProcessor');
const ComponentParser = require('./compiler/ComponentParser');
 
const AvenxCompilerErrors = {
    AVX_C01: 'Could not create dist directory at "{0}".',
    AVX_C02: '"src" directory not found at "{0}". Run "avenx init" to scaffold a project.'
};
 
function formatCompilerError(code, ...args) {
    let message = AvenxCompilerErrors[code] || 'An unknown compiler error occurred.';
    args.forEach((arg, idx) => {
        message = message.replace(`{${idx}}`, String(arg));
    });
    return `[${code}] ${message}`;
}
 
 
/**
 * AvenxCompiler is the main orchestrator for the Avenx-JS build process.
 * It coordinates the parsing of components, processing of styles, and the
 * final bundling of the application.
 */
class AvenxCompiler {
    /**
     * Creates an instance of AvenxCompiler and initializes its sub-processors.
     * Uses the current working directory as the project root.
     */
    constructor() {
        /** 
         * The root directory of the project.
         * @type {string} 
         */
        this.rootDir = process.cwd();
        /** 
         * The source directory (usually 'src').
         * @type {string} 
         */
        this.srcDir = path.join(this.rootDir, 'src');
        /** 
         * The distribution directory (usually 'dist').
         * @type {string} 
         */
        this.distDir = path.join(this.rootDir, 'dist');
        /** 
         * The directory containing core runtime files.
         * @type {string} 
         */
        this.coreDir = path.join(__dirname, 'core');
        
        /** 
         * @type {StyleProcessor} 
         */
        this.styleProcessor = new StyleProcessor();
        /** 
         * @type {ComponentParser} 
         */
        this.componentParser = new ComponentParser(this.styleProcessor);
        
        this.init();
    }
 
    /**
     * Initializes the compiler environment, ensuring required directories exist.
     * @private
     */
    init() {
        if (!fs.existsSync(this.distDir)) {
            try {
                fs.mkdirSync(this.distDir, { recursive: true });
            } catch (e) {
                console.error(`❌ ${formatCompilerError('AVX_C01', this.distDir)}`);
            }
        }
    }
 
    /**
     * Executes the full build process.
     * Includes resetting style processor, generating runtime, processing bridges, components, and main app.
     */
    build() {
        console.log("--- Avenx-JS Compiler ---");
        
        if (!fs.existsSync(this.srcDir)) {
            console.error(`❌ ${formatCompilerError('AVX_C02', this.srcDir)}`);
            return;
        }
 
        // Reset style processor to avoid accumulating styles across multiple builds (watch mode)
        this.styleProcessor.reset();
 
        let bundleJs = this.getRuntime();
        const bridgeData = this.processBridges();
        bundleJs += this.processGuards();
        bundleJs += this.processComponents();
        const pageData = this.processPages();
        bundleJs += pageData.pagesJs;
        bundleJs += this.processMain((bridgeData.registrations || '') + '\n' + (pageData.registrations || ''));
 
        fs.writeFileSync(path.join(this.distDir, 'bundle.js'), bundleJs);
        fs.writeFileSync(path.join(this.distDir, 'bundle.css'), this.styleProcessor.getGlobalStyles());
        
        console.log("-----------------------");
        console.log(`Build erfolgreich: dist/bundle.js & dist/bundle.css`);
    }
 
    /**
     * Reads the core runtime files and prepares them for the bundle.
     * Strips imports and exports for a single-file bundle.
     * @returns {string} The concatenated runtime source code.
     * @private
     */
    getRuntime() {
        const runtimeFiles = [
            'runtime/AvenxError.js',
            'security/evaluator.js',
            'security/escapeHtml.js',
            'reactive/proxyHandler.js',
            'reactive/createState.js',
            'reactive/createComputed.js',
            'renderer/renderTemplate.js',
            'renderer/domPatch.js',
            'renderer/listManager.js',
            'events/eventExecutor.js',
            'events/bindEvents.js',
            'runtime/lifecycle.js',
            'runtime/AvenxBridge.js',
            'runtime/AvenxComponent.js',
            'runtime/AvenxPage.js',
            'runtime/AvenxGuard.js',
            'runtime/AvenxRouter.js',
            'runtime/AvenxApp.js'
        ];
 
        return runtimeFiles
            .map(file => fs.readFileSync(path.join(this.coreDir, file), 'utf-8'))
            .map(source => source
                .replace(/^import\s+.*?;\s*$/gm, '')
                .replace(/export\s+/g, '')
            )
            .join("\n");
    }
 
    /**
     * Processes bridge registrations from the global directory.
     * @returns {{registrations: string}} The registration code for bridges.
     * @private
     */
    processBridges() {
        const globalDir = path.join(this.srcDir, 'global');
        let registrations = "";
        if (fs.existsSync(globalDir)) {
            fs.readdirSync(globalDir).forEach(file => {
                if (file.endsWith('.bridge.js')) {
                    const name = path.basename(file, '.bridge.js');
                    const capitalizedName = name.split(/[-_]/).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join("") + "Bridge";
                    
                    console.log(`[Bridge] ${capitalizedName}`);
                    const content = fs.readFileSync(path.join(globalDir, file), 'utf-8');
                    const match = content.match(/export\s+default\s+([\s\S]*)/);
                    if (match) {
                        const objStr = match[1].trim().replace(/;$/, '');
                        registrations += `app.registerBridge('${capitalizedName}', ${objStr});\n`;
                    }
                }
            });
        }
        return { registrations };
    }
 
    /**
     * Processes guard classes from the global and guards directories.
     * @returns {string} The concatenated guard source code.
     * @private
     */
    processGuards() {
        const globalDir = path.join(this.srcDir, 'global');
        const guardsDir = path.join(this.srcDir, 'guards');
        let guardsJs = "";
 
        const processFile = (dir, file) => {
            const name = path.basename(file, '.guard.js');
            const capitalizedName = name.split(/[-_]/).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join("") + "Guard";
            
            console.log(`[Guard] ${capitalizedName}`);
            const content = fs.readFileSync(path.join(dir, file), 'utf-8');
            const cleaned = content
                .replace(/^import\s+.*?;\s*$/gm, '')
                .replace(/import\s+.*?\s+from\s+['"].*?['"];?/gm, '')
                .replace(/export\s+default\s+/g, '')
                .replace(/export\s+/g, '');
            guardsJs += `\n${cleaned}\n`;
        };
 
        if (fs.existsSync(globalDir)) {
            fs.readdirSync(globalDir).forEach(file => {
                if (file.endsWith('.guard.js')) {
                    processFile(globalDir, file);
                }
            });
        }
        if (fs.existsSync(guardsDir)) {
            fs.readdirSync(guardsDir).forEach(file => {
                if (file.endsWith('.guard.js')) {
                    processFile(guardsDir, file);
                }
            });
        }
        return guardsJs;
    }
 
    /**
     * Processes all components in the src/components folder recursively.
     * @returns {string} The concatenated source code of all compiled components.
     * @private
     */
    processComponents() {
        let componentsJs = "";
        const compDir = path.join(this.srcDir, 'components');
        
        const scan = (dir) => {
            if (!fs.existsSync(dir)) return;
            fs.readdirSync(dir).forEach(file => {
                const fullPath = path.join(dir, file);
                if (fs.statSync(fullPath).isDirectory()) {
                    scan(fullPath);
                } else if (file.endsWith('.component.js')) {
                    console.log(`[Compiling] ${file}`);
                    componentsJs += this.componentParser.parse(fullPath);
                }
            });
        };
 
        scan(compDir);
        return componentsJs;
    }
 
    /**
     * Processes all pages in the src/pages folder recursively.
     * @returns {{pagesJs: string, registrations: string}} The compiled pages code and their registrations.
     * @private
     */
    processPages() {
        let pagesJs = "";
        let registrations = "";
        const pageDir = path.join(this.srcDir, 'pages');
        
        const scan = (dir) => {
            if (!fs.existsSync(dir)) return;
            fs.readdirSync(dir).forEach(file => {
                const fullPath = path.join(dir, file);
                if (fs.statSync(fullPath).isDirectory()) {
                    scan(fullPath);
                } else if (file.endsWith('.page.js')) {
                    console.log(`[Compiling Page] ${file}`);
                    const name = path.basename(file, '.page.js').split(/[-_]/).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join("");
                    pagesJs += this.componentParser.parse(fullPath, 'page');
                    registrations += `app.registerPage('${name}', ${name});\n`;
                }
            });
        };
 
        scan(pageDir);
        return { pagesJs, registrations };
    }
 
    /**
     * Processes the main application entry point.
     * @param {string} registrations - The bridge and page registration code to inject.
     * @returns {string} The wrapped main application code.
     * @private
     */
    processMain(registrations) {
        const mainFile = path.join(this.srcDir, 'main.app.js');
        if (fs.existsSync(mainFile)) {
            let main = fs.readFileSync(mainFile, 'utf-8')
                .replace(/import\s*{\s*AvenxApp\s*}\s*from\s*['"].*?['"];?/g, '') 
                .replace(/import\s+.*?\s+from\s+['"].*?['"];?/gm, ''); 
            
            if (registrations) {
                main = main.replace(/(const\s+app\s+=\s+new\s+AvenxApp\([\s\S]*?\);)/, `$1\n${registrations}`);
            }
            return `\n(function(){\n${main}\n})();`;
        }
        return "";
    }
}
 
module.exports = AvenxCompiler;