UNPKG

@pierrad/web-carbon-analyzer

Version:

A tool to measure the carbon footprint of websites using CO2.js

161 lines 7.46 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CarbonFootprintAnalyzer = void 0; /** * Carbon Footprint Analyzer * Main class for analyzing the carbon footprint of websites */ const browser_controller_1 = __importDefault(require("./modules/browser-controller")); const network_interceptor_1 = __importDefault(require("./modules/network-interceptor")); const co2_calculator_1 = __importDefault(require("./modules/co2-calculator")); const output_formatter_1 = __importDefault(require("./modules/output-formatter")); const lighthouse_controller_1 = __importDefault(require("./modules/lighthouse-controller")); const default_1 = __importDefault(require("./config/default")); const logger_1 = __importDefault(require("./utils/logger")); class CarbonFootprintAnalyzer { /** * Create a new CarbonFootprintAnalyzer instance * @param customConfig Optional configuration overrides */ constructor(customConfig = {}) { this.lighthouseController = null; // Merge default config with custom config this.config = { browser: { ...default_1.default.browser, ...(customConfig.browser || {}) }, userBehavior: { ...default_1.default.userBehavior, ...(customConfig.userBehavior || {}) }, co2: { ...default_1.default.co2, ...(customConfig.co2 || {}) }, output: { ...default_1.default.output, ...(customConfig.output || {}) }, logging: { ...default_1.default.logging, ...(customConfig.logging || {}) }, lighthouse: { ...default_1.default.lighthouse, ...(customConfig.lighthouse || {}) } }; // Initialize modules // If lighthouse is enabled, configure the browser with a remote debugging port if (this.config.lighthouse?.enabled && this.config.browser.type === 'chromium') { this.config.browser.remoteDebuggingPort = this.config.lighthouse.port || 9222; } this.browserController = new browser_controller_1.default(this.config.browser); this.networkInterceptor = new network_interceptor_1.default(); this.co2Calculator = new co2_calculator_1.default(this.config.co2); this.outputFormatter = new output_formatter_1.default(this.config.output); // Initialize lighthouse controller if enabled if (this.config.lighthouse && this.config.lighthouse.enabled) { this.lighthouseController = new lighthouse_controller_1.default(this.config.lighthouse); } // Configure logging if (customConfig.logging?.level) { logger_1.default.level = customConfig.logging.level; } } /** * Analyze a URL and calculate its carbon footprint * @param url The URL to analyze * @returns Formatted analysis results */ async analyze(url) { logger_1.default.info(`Starting analysis of ${url}`); // Launch browser with Lighthouse port if needed const page = await this.browserController.launch(); try { // Setup network interception await this.networkInterceptor.setupInterception(page); // Navigate to URL await this.browserController.navigateTo(url); // Simulate user behavior await this.browserController.simulateUserBehavior(this.config.userBehavior); // Process resources data const resourcesData = this.networkInterceptor.processResourcesData(); logger_1.default.info(`Processed ${resourcesData.totalResources} resources, ${resourcesData.totalSize} bytes total`); // Calculate emissions const emissionsData = await this.co2Calculator.calculateEmissions(resourcesData); // Run lighthouse audit if enabled let lighthouseResults = null; if (this.lighthouseController) { logger_1.default.info('Running Lighthouse audit'); lighthouseResults = await this.lighthouseController.runAudit(page, url); } // Format results const metadata = { configuration: { browser: this.config.browser, userBehavior: this.config.userBehavior, co2: this.config.co2, lighthouse: this.config.lighthouse } }; const results = this.outputFormatter.formatResults(url, resourcesData, emissionsData, metadata); // Add lighthouse results if available if (lighthouseResults) { results.lighthouse = lighthouseResults; } logger_1.default.info('Analysis completed successfully'); return results; } catch (error) { logger_1.default.error(`Analysis failed: ${error.message}`); throw error; } finally { // Ensure browser is closed await this.browserController.close(); } } /** * Load cookies for authentication or session persistence * @param cookiesPath Path to a JSON file containing cookies */ async loadCookies(cookiesPath) { logger_1.default.info(`Loading cookies from ${cookiesPath}`); // Check if browser is initialized if (!this.browserController) { throw new Error('Browser controller not initialized'); } // Launch browser if not already launched const page = await this.browserController.launch(); try { // Read cookies file const fs = require('fs'); const cookiesJson = fs.readFileSync(cookiesPath, 'utf8'); const cookies = JSON.parse(cookiesJson); // Add cookies to browser context await page.context().addCookies(cookies); logger_1.default.info(`Loaded cookies from ${cookiesPath}`); } catch (error) { logger_1.default.error(`Failed to load cookies: ${error.message}`); throw error; } } /** * Get the current configuration * @returns The current configuration object */ getConfig() { return this.config; } /** * Update the current configuration * @param newConfig Partial configuration to update */ updateConfig(newConfig) { this.config = { browser: { ...this.config.browser, ...(newConfig.browser || {}) }, userBehavior: { ...this.config.userBehavior, ...(newConfig.userBehavior || {}) }, co2: { ...this.config.co2, ...(newConfig.co2 || {}) }, output: { ...this.config.output, ...(newConfig.output || {}) }, logging: { ...this.config.logging, ...(newConfig.logging || {}) } }; // Update module configurations this.browserController = new browser_controller_1.default(this.config.browser); this.co2Calculator = new co2_calculator_1.default(this.config.co2); this.outputFormatter = new output_formatter_1.default(this.config.output); // Update logging configuration if (newConfig.logging?.level) { logger_1.default.level = newConfig.logging.level; } } } exports.CarbonFootprintAnalyzer = CarbonFootprintAnalyzer; //# sourceMappingURL=analyzer.js.map