Skip to content

Commit 40be103

Browse files
authored
Merge pull request #50 from liamgold/feature/bundle-co2-library
Bundle @tgwf/co2 library locally to remove Skypack CDN dependency
2 parents 3c082cb + 4e114e0 commit 40be103

File tree

7 files changed

+134
-76
lines changed

7 files changed

+134
-76
lines changed

examples/DancingGoat/packages.lock.json

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,14 +1062,14 @@
10621062
"dependencies": {
10631063
"Kentico.Xperience.admin": "[30.4.2, )",
10641064
"Kentico.Xperience.webapp": "[30.4.2, )",
1065-
"Microsoft.Playwright": "[1.52.0, )"
1065+
"Microsoft.Playwright": "[1.55.0, )"
10661066
}
10671067
},
10681068
"Microsoft.Playwright": {
10691069
"type": "CentralTransitive",
1070-
"requested": "[1.52.0, )",
1071-
"resolved": "1.52.0",
1072-
"contentHash": "zH8a7OiXtq8BC6i0yYHAG/DSN8J8/bVyQYVESK7mK1ZJF19eY1ca51BAQpQxzF+Qm/A20x6Rsl8cT+QYXSfxbw==",
1070+
"requested": "[1.55.0, )",
1071+
"resolved": "1.55.0",
1072+
"contentHash": "iPVHeRI5EZB1gK43MC/qnINvGUV3pYh/PJn5wNmeaiZ4ARlFAfK3azf46c7/kx/lmVaknZ5rSNT1F8SZgSaWSQ==",
10731073
"dependencies": {
10741074
"Microsoft.Bcl.AsyncInterfaces": "6.0.0",
10751075
"System.ComponentModel.Annotations": "5.0.0",

src/Client/package-lock.json

Lines changed: 10 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Client/package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
"scripts": {
77
"start": "webpack serve --mode development",
88
"dev:buildlike": "webpack serve --mode development --env buildlike=true",
9-
"build": "webpack --mode=production"
9+
"build": "npm run build:admin && npm run build:resource-checker",
10+
"build:admin": "webpack --mode=production",
11+
"build:resource-checker": "webpack --config webpack.resource-checker.config.js"
1012
},
1113
"dependencies": {
1214
"@kentico/xperience-admin-base": "30.4.2",
1315
"@kentico/xperience-admin-components": "30.4.2",
16+
"@tgwf/co2": "^0.15.0",
1417
"css-loader": "^7.1.2",
1518
"postcss-loader": "^8.2.0",
1619
"react": "^18.3.1",

src/Client/src/resource-checker.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { co2, hosting } from '@tgwf/co2';
2+
3+
export async function reportEmissions() {
4+
console.log("reportEmissions called");
5+
6+
await scrollPage();
7+
await delay(2000); // give lazy-loaded resources time to load
8+
9+
console.log("getting emissions data");
10+
const emissionsData = await getEmissionsData();
11+
console.log("received emissions data");
12+
13+
const emissionsDiv = document.createElement("div");
14+
emissionsDiv.setAttribute("data-testid", "sustainabilityData");
15+
emissionsDiv.textContent = JSON.stringify(emissionsData);
16+
17+
document.body.appendChild(emissionsDiv);
18+
}
19+
20+
async function scrollPage() {
21+
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
22+
return delay(2000);
23+
}
24+
25+
function delay(ms) {
26+
return new Promise(resolve => setTimeout(resolve, ms));
27+
}
28+
29+
async function getEmissionsData() {
30+
console.log("calculating...");
31+
const resources = getResources();
32+
const bytesSent = getTransferSize(resources);
33+
const hostCheck = await hosting.check(window.location.hostname);
34+
35+
const co2Emission = new co2({ model: "swd" });
36+
const emissions = co2Emission.perVisitTrace(bytesSent, hostCheck);
37+
38+
return {
39+
pageWeight: bytesSent,
40+
carbonRating: calculateGrade(emissions.co2),
41+
emissions: emissions,
42+
resources: resources
43+
};
44+
}
45+
46+
function getResources() {
47+
const allResources = window.performance.getEntriesByType("resource");
48+
// Filter out the resource-checker.js script itself to avoid artificially inflating page weight calculations
49+
return allResources.filter(resource => {
50+
const url = resource.name || '';
51+
return !url.includes('resource-checker.js');
52+
});
53+
}
54+
55+
function getTransferSize(resources) {
56+
return resources.reduce((total, entry) => total + entry.transferSize, 0);
57+
}
58+
59+
// grade using swd digital carbon ratings
60+
// https://sustainablewebdesign.org/digital-carbon-ratings/
61+
function calculateGrade(score) {
62+
if (score < 0.095) return 'A+';
63+
if (score < 0.186) return 'A';
64+
if (score < 0.341) return 'B';
65+
if (score < 0.493) return 'C';
66+
if (score < 0.656) return 'D';
67+
if (score < 0.846) return 'E';
68+
return 'F';
69+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const path = require("path");
2+
3+
module.exports = {
4+
mode: "production",
5+
entry: path.resolve(__dirname, "src/resource-checker.js"),
6+
output: {
7+
path: path.resolve(__dirname, "../wwwroot/scripts"),
8+
filename: "resource-checker.js",
9+
library: {
10+
type: "module",
11+
},
12+
},
13+
experiments: {
14+
outputModule: true,
15+
},
16+
module: {
17+
rules: [
18+
{
19+
test: /\.js$/,
20+
exclude: /node_modules/,
21+
use: {
22+
loader: "babel-loader",
23+
options: {
24+
presets: [
25+
["@babel/preset-env", {
26+
targets: "> .2% and last 3 versions, not op_mini all, not IE 11",
27+
modules: false,
28+
}]
29+
],
30+
},
31+
},
32+
},
33+
],
34+
},
35+
resolve: {
36+
extensions: [".js"],
37+
},
38+
};

src/Services/SustainabilityService.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using Microsoft.Extensions.Logging;
55
using Microsoft.Extensions.Options;
66
using Microsoft.Playwright;
7+
using System.Reflection;
78
using System.Text.Json;
89
using XperienceCommunity.Sustainability.Models;
910

@@ -23,9 +24,15 @@ public class SustainabilityService : ISustainabilityService
2324
private readonly IInfoProvider<SustainabilityPageDataInfo> _sustainabilityPageDataInfoProvider;
2425
private readonly SustainabilityOptions _options;
2526

26-
private const string ScriptPath = "/_content/XperienceCommunity.Sustainability/scripts/resource-checker.js";
27+
private static readonly string ScriptPath = GetScriptPath();
2728
private const string SustainabilityDataTestId = "sustainabilityData";
2829

30+
private static string GetScriptPath()
31+
{
32+
var version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "1.0.0";
33+
return $"/_content/XperienceCommunity.Sustainability/scripts/resource-checker.js?v={version}";
34+
}
35+
2936
public SustainabilityService(
3037
IWebHostEnvironment env,
3138
IEventLogService eventLogService,

src/wwwroot/scripts/resource-checker.js

Lines changed: 1 addition & 70 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)