|
| 1 | +import { co2 } from "@tgwf/co2"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Calculates the carbon emissions for a web page based on the results from Google's PageSpeed Insights (Lighthouse). |
| 5 | + * |
| 6 | + * @param {Object} pageSpeedResults - The PageSpeed Insights (Lighthouse) result object. |
| 7 | + * @returns {Object} An object containing: |
| 8 | + * @property {number} emissionsOneByte - Estimated emissions CO2e (in grams) from the OneByte model. |
| 9 | + * @property {number} emissionsSWD - Estimated emissions CO2e (in grams) from the Sustainable Web Design model. |
| 10 | + * TODO: This function currently returns emissions for both the OneByte and SWD models. Not sure which one we ultimately want to use. |
| 11 | + */ |
| 12 | +export const calculateEmissionsFromPageSpeedResults = (pageSpeedResults) => { |
| 13 | + const totalByteWeight = pageSpeedResults.lighthouseResult.audits['total-byte-weight'].numericValue; |
| 14 | + // this appears to be the same number as totalByteWeight: |
| 15 | + // const totalByteWeightSummed = pageSpeedResults.lighthouseResult.audits['network-requests'].details.items.reduce((total, item) => total + item.transferSize, 0); |
| 16 | + |
| 17 | + // OneByte model |
| 18 | + // https://developers.thegreenwebfoundation.org/co2js/models/#using-the-onebyte-model |
| 19 | + const perByte = new co2({ model: "1byte" }); |
| 20 | + const emissionsOneByte = perByte.perByte(totalByteWeight); |
| 21 | + |
| 22 | + // Sustainable Web Design (SWD) model |
| 23 | + // https://developers.thegreenwebfoundation.org/co2js/models/#using-the-sustainable-web-design-model-default-v0110 |
| 24 | + const swd = new co2({ model: "swd" }); |
| 25 | + const emissionsSWD = swd.perVisit(totalByteWeight); |
| 26 | + |
| 27 | + return { emissionsOneByte, emissionsSWD }; |
| 28 | +} |
| 29 | + |
| 30 | +// TODO: The code below is for testing purposes only. |
| 31 | +// It should be removed once it's able to be integrated with https://sparkbox.atlassian.net/browse/BLDL-9 |
| 32 | +// tempdata.json should also be removed. |
| 33 | +(async () => { |
| 34 | + const pageSpeedResults = (await import("./tempdata.json", { with: { type: "json" } })).default; |
| 35 | + const results = calculateEmissionsFromPageSpeedResults(pageSpeedResults) |
| 36 | + console.log("Emissions Calculation Results:", results); |
| 37 | +})(); |
| 38 | + |
0 commit comments