@tgwf/co2 0.11.3 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.esbuild.esm.js +1 -1
  2. package/.esbuild.node.js +1 -1
  3. package/README.md +3 -3
  4. package/dist/cjs/1byte.js.map +2 -2
  5. package/dist/cjs/co2.js +67 -4
  6. package/dist/cjs/co2.js.map +2 -2
  7. package/dist/cjs/constants/index.js +23 -1
  8. package/dist/cjs/constants/index.js.map +2 -2
  9. package/dist/cjs/helpers/index.js +139 -1
  10. package/dist/cjs/helpers/index.js.map +2 -2
  11. package/dist/cjs/hosting-api.js +0 -4
  12. package/dist/cjs/hosting-api.js.map +2 -2
  13. package/dist/cjs/hosting-json.node.js +2 -1
  14. package/dist/cjs/hosting-json.node.js.map +2 -2
  15. package/dist/cjs/sustainable-web-design.js +67 -49
  16. package/dist/cjs/sustainable-web-design.js.map +2 -2
  17. package/dist/esm/co2.js +70 -4
  18. package/dist/esm/constants/index.js +23 -1
  19. package/dist/esm/helpers/index.js +144 -1
  20. package/dist/esm/hosting-api.js +0 -4
  21. package/dist/esm/sustainable-web-design.js +90 -41
  22. package/dist/iife/index.js +19 -3
  23. package/dist/iife/index.js.map +3 -3
  24. package/package.json +1 -1
  25. package/src/1byte.js +7 -0
  26. package/src/co2.js +157 -4
  27. package/src/constants/index.js +38 -1
  28. package/src/helpers/index.js +173 -1
  29. package/src/hosting-api.js +5 -4
  30. package/src/hosting-json.node.js +1 -0
  31. package/src/sustainable-web-design.js +113 -72
  32. package/dist/cjs/1byte.test.js +0 -27
  33. package/dist/cjs/1byte.test.js.map +0 -7
  34. package/dist/cjs/co2.test.js +0 -281
  35. package/dist/cjs/co2.test.js.map +0 -7
  36. package/dist/cjs/hosting-api.test.js +0 -47
  37. package/dist/cjs/hosting-api.test.js.map +0 -7
  38. package/dist/cjs/hosting-database.node.test.js +0 -36
  39. package/dist/cjs/hosting-database.node.test.js.map +0 -7
  40. package/dist/cjs/hosting-json.node.test.js +0 -43
  41. package/dist/cjs/hosting-json.node.test.js.map +0 -7
  42. package/dist/cjs/hosting.test.js +0 -74
  43. package/dist/cjs/hosting.test.js.map +0 -7
  44. package/dist/cjs/sustainable-web-design.test.js +0 -84
  45. package/dist/cjs/sustainable-web-design.test.js.map +0 -7
  46. package/dist/esm/1byte.test.js +0 -11
  47. package/dist/esm/co2.test.js +0 -265
  48. package/dist/esm/hosting-api.test.js +0 -31
  49. package/dist/esm/hosting-database.node.test.js +0 -20
  50. package/dist/esm/hosting-json.node.test.js +0 -27
  51. package/dist/esm/hosting.test.js +0 -58
  52. package/dist/esm/sustainable-web-design.test.js +0 -68
  53. package/src/readme.md +0 -66
package/.esbuild.esm.js CHANGED
@@ -6,7 +6,7 @@ const esbuild = require('esbuild')
6
6
  const glob = require('tiny-glob');
7
7
 
8
8
  async function main() {
9
- const results = await glob('src/**/**.js')
9
+ const results = await glob('src/**/!(*.test.js|test-constants.js|!(*.js))')
10
10
  // we remove node specific files here, with the assumption that
11
11
  // the common use case is bundling into browser based web apps
12
12
  const justBrowserCompatibleFiles = results.filter(filepath => !filepath.endsWith('node.js'))
package/.esbuild.node.js CHANGED
@@ -2,7 +2,7 @@ const { globPlugin } = require('esbuild-plugin-glob');
2
2
 
3
3
  function main() {
4
4
  require('esbuild').build({
5
- entryPoints: ['src/**/**.js',],
5
+ entryPoints: ['src/**/!(*.test.js|test-constants.js|!(*.js))'],
6
6
  bundle: false,
7
7
  minify: false,
8
8
  sourcemap: true,
package/README.md CHANGED
@@ -100,10 +100,10 @@ We use [`np`](https://www.npmjs.com/package/np) to publish new versions of this
100
100
 
101
101
  ## Licenses
102
102
 
103
- The code for CO2.js is licensed Apache 2.0.
103
+ The code for CO2.js is licensed Apache 2.0. ([What does this mean?](https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)))
104
104
 
105
- The average carbon intensity data from Ember is published under the Creative Commons ShareAlike Attribution Licence ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/))
105
+ The average carbon intensity data from Ember is published under the Creative Commons ShareAlike Attribution Licence ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)). ([What does this mean?](https://tldrlegal.com/license/creative-commons-attribution-sharealike-4.0-international-(cc-by-sa-4.0)))
106
106
 
107
- The marginal intensity data is published by the Green Web Foundation, under the Creative Commons ShareAlike Attribution Licence ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)).
107
+ The marginal intensity data is published by the Green Web Foundation, under the Creative Commons ShareAlike Attribution Licence ([CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)). ([What does this mean?](https://tldrlegal.com/license/creative-commons-attribution-sharealike-4.0-international-(cc-by-sa-4.0)))
108
108
 
109
109
  See LICENCE for more.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/1byte.js"],
4
- "sourcesContent": ["// Use the 1byte model for now from the Shift Project, and assume a US grid mix figure they use of around 519 g co2 for the time being. It's lower for Europe, and in particular, France, but for v1, we don't include this\nconst CO2_PER_KWH_IN_DC_GREY = 519;\n\n// this figure is from the IEA's 2018 report for a global average:\nconst CO2_PER_KWH_NETWORK_GREY = 475;\n\n// TODO - these figures need to be updated, as the figures for green\n// shouldn't really be zero now we know that carbon intensity figures\n// for renewables still usually include the life cycle emissions\nconst CO2_PER_KWH_IN_DC_GREEN = 0;\n\n// the 1 byte model gives figures for energy usage for:\n\n// datacentres\n// networks\n// the device used to access a site/app\n\n// The device usage figure combines figures for:\n// 1. the usage for devices (which is small proportion of the energy use)\n// 2. the *making* the device, which is comparatively high.\n\nconst KWH_PER_BYTE_IN_DC = 7.2e-11;\n\n// this is probably best left as something users can define, or\n// a weighted average based on total usage.\n// Using a simple mean for now, as while web traffic to end users might trend\n// towards wifi and mobile,\n// Web traffic between servers is likely wired networks\n\nconst FIXED_NETWORK_WIRED = 4.29e-10;\nconst FIXED_NETWORK_WIFI = 1.52e-10;\nconst FOUR_G_MOBILE = 8.84e-10;\n\n// Pull requests gratefully accepted\nconst KWH_PER_BYTE_FOR_NETWORK =\n (FIXED_NETWORK_WIRED + FIXED_NETWORK_WIFI + FOUR_G_MOBILE) / 3;\n\nconst KWH_PER_BYTE_FOR_DEVICES = 1.3e-10;\n\nclass OneByte {\n constructor(options) {\n this.options = options;\n\n this.KWH_PER_BYTE_FOR_NETWORK = KWH_PER_BYTE_FOR_NETWORK;\n }\n\n perByte(bytes, green) {\n if (bytes < 1) {\n return 0;\n }\n\n if (green) {\n // if we have a green datacentre, use the lower figure for renewable energy\n const Co2ForDC = bytes * KWH_PER_BYTE_IN_DC * CO2_PER_KWH_IN_DC_GREEN;\n\n // but for the worest of the internet, we can't easily check, so assume\n // grey for now\n const Co2forNetwork =\n bytes * KWH_PER_BYTE_FOR_NETWORK * CO2_PER_KWH_NETWORK_GREY;\n\n return Co2ForDC + Co2forNetwork;\n }\n\n const KwHPerByte = KWH_PER_BYTE_IN_DC + KWH_PER_BYTE_FOR_NETWORK;\n return bytes * KwHPerByte * CO2_PER_KWH_IN_DC_GREY;\n }\n}\n\nexport { OneByte };\nexport default OneByte;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,MAAM,yBAAyB;AAG/B,MAAM,2BAA2B;AAKjC,MAAM,0BAA0B;AAYhC,MAAM,qBAAqB;AAQ3B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AAGtB,MAAM,2BACH,uBAAsB,qBAAqB,iBAAiB;AAE/D,MAAM,2BAA2B;AAEjC,MAAM,QAAQ;AAAA,EACZ,YAAY,SAAS;AACnB,SAAK,UAAU;AAEf,SAAK,2BAA2B;AAAA,EAClC;AAAA,EAEA,QAAQ,OAAO,OAAO;AACpB,QAAI,QAAQ,GAAG;AACb,aAAO;AAAA,IACT;AAEA,QAAI,OAAO;AAET,YAAM,WAAW,QAAQ,qBAAqB;AAI9C,YAAM,gBACJ,QAAQ,2BAA2B;AAErC,aAAO,WAAW;AAAA,IACpB;AAEA,UAAM,aAAa,qBAAqB;AACxC,WAAO,QAAQ,aAAa;AAAA,EAC9B;AACF;AAGA,IAAO,eAAQ;",
4
+ "sourcesContent": ["// Use the 1byte model for now from the Shift Project, and assume a US grid mix figure they use of around 519 g co2 for the time being. It's lower for Europe, and in particular, France, but for v1, we don't include this\nconst CO2_PER_KWH_IN_DC_GREY = 519;\n\n// this figure is from the IEA's 2018 report for a global average:\nconst CO2_PER_KWH_NETWORK_GREY = 475;\n\n// TODO - these figures need to be updated, as the figures for green\n// shouldn't really be zero now we know that carbon intensity figures\n// for renewables still usually include the life cycle emissions\nconst CO2_PER_KWH_IN_DC_GREEN = 0;\n\n// the 1 byte model gives figures for energy usage for:\n\n// datacentres\n// networks\n// the device used to access a site/app\n\n// The device usage figure combines figures for:\n// 1. the usage for devices (which is small proportion of the energy use)\n// 2. the *making* the device, which is comparatively high.\n\nconst KWH_PER_BYTE_IN_DC = 7.2e-11;\n\n// this is probably best left as something users can define, or\n// a weighted average based on total usage.\n// Using a simple mean for now, as while web traffic to end users might trend\n// towards wifi and mobile,\n// Web traffic between servers is likely wired networks\n\nconst FIXED_NETWORK_WIRED = 4.29e-10;\nconst FIXED_NETWORK_WIFI = 1.52e-10;\nconst FOUR_G_MOBILE = 8.84e-10;\n\n// Pull requests gratefully accepted\nconst KWH_PER_BYTE_FOR_NETWORK =\n (FIXED_NETWORK_WIRED + FIXED_NETWORK_WIFI + FOUR_G_MOBILE) / 3;\n\nconst KWH_PER_BYTE_FOR_DEVICES = 1.3e-10;\n\nclass OneByte {\n constructor(options) {\n this.options = options;\n\n this.KWH_PER_BYTE_FOR_NETWORK = KWH_PER_BYTE_FOR_NETWORK;\n }\n\n /**\n * Calculates the carbon footprint of a website using the OneByte model\n * @param {number} bytes - The number of bytes to calculate the carbon footprint for\n * @param {boolean} green - Whether the energy is green or not\n * @returns {number} The carbon footprint in grams of CO2\n */\n\n perByte(bytes, green) {\n if (bytes < 1) {\n return 0;\n }\n\n if (green) {\n // if we have a green datacentre, use the lower figure for renewable energy\n const Co2ForDC = bytes * KWH_PER_BYTE_IN_DC * CO2_PER_KWH_IN_DC_GREEN;\n\n // but for the worest of the internet, we can't easily check, so assume\n // grey for now\n const Co2forNetwork =\n bytes * KWH_PER_BYTE_FOR_NETWORK * CO2_PER_KWH_NETWORK_GREY;\n\n return Co2ForDC + Co2forNetwork;\n }\n\n const KwHPerByte = KWH_PER_BYTE_IN_DC + KWH_PER_BYTE_FOR_NETWORK;\n return bytes * KwHPerByte * CO2_PER_KWH_IN_DC_GREY;\n }\n}\n\nexport { OneByte };\nexport default OneByte;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,MAAM,yBAAyB;AAG/B,MAAM,2BAA2B;AAKjC,MAAM,0BAA0B;AAYhC,MAAM,qBAAqB;AAQ3B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;AAGtB,MAAM,2BACH,uBAAsB,qBAAqB,iBAAiB;AAE/D,MAAM,2BAA2B;AAEjC,MAAM,QAAQ;AAAA,EACZ,YAAY,SAAS;AACnB,SAAK,UAAU;AAEf,SAAK,2BAA2B;AAAA,EAClC;AAAA,EASA,QAAQ,OAAO,OAAO;AACpB,QAAI,QAAQ,GAAG;AACb,aAAO;AAAA,IACT;AAEA,QAAI,OAAO;AAET,YAAM,WAAW,QAAQ,qBAAqB;AAI9C,YAAM,gBACJ,QAAQ,2BAA2B;AAErC,aAAO,WAAW;AAAA,IACpB;AAEA,UAAM,aAAa,qBAAqB;AACxC,WAAO,QAAQ,aAAa;AAAA,EAC9B;AACF;AAGA,IAAO,eAAQ;",
6
6
  "names": []
7
7
  }
package/dist/cjs/co2.js CHANGED
@@ -27,6 +27,8 @@ __export(co2_exports, {
27
27
  module.exports = __toCommonJS(co2_exports);
28
28
  var import_byte = __toESM(require("./1byte.js"));
29
29
  var import_sustainable_web_design = __toESM(require("./sustainable-web-design.js"));
30
+ var import_constants = require("./constants/index.js");
31
+ var import_helpers = require("./helpers/index.js");
30
32
  class CO2 {
31
33
  constructor(options) {
32
34
  this.model = new import_sustainable_web_design.default();
@@ -38,16 +40,77 @@ class CO2 {
38
40
  throw new Error(`"${options.model}" is not a valid model. Please use "1byte" for the OneByte model, and "swd" for the Sustainable Web Design model.
39
41
  See https://developers.thegreenwebfoundation.org/co2js/models/ to learn more about the models available in CO2.js.`);
40
42
  }
43
+ if ((options == null ? void 0 : options.results) === "segment") {
44
+ this.model.results = {
45
+ segment: true
46
+ };
47
+ } else {
48
+ this.model.results = {
49
+ segment: false
50
+ };
51
+ }
41
52
  }
42
- perByte(bytes, green) {
43
- return this.model.perByte(bytes, green);
53
+ perByte(bytes, green = false) {
54
+ return this.model.perByte(bytes, green, this.model.results.segment);
44
55
  }
45
- perVisit(bytes, green) {
56
+ perVisit(bytes, green = false) {
46
57
  var _a;
47
58
  if ((_a = this.model) == null ? void 0 : _a.perVisit) {
48
- return this.model.perVisit(bytes, green);
59
+ return this.model.perVisit(bytes, green, this.model.results.segment);
49
60
  } else {
50
61
  throw new Error(`The perVisit() method is not supported in the model you are using. Try using perByte() instead.
62
+ See https://developers.thegreenwebfoundation.org/co2js/methods/ to learn more about the methods available in CO2.js.`);
63
+ }
64
+ }
65
+ perByteTrace(bytes, green = false, options = {}) {
66
+ var _a, _b, _c, _d, _e, _f;
67
+ let adjustments = {};
68
+ if (options) {
69
+ adjustments = (0, import_helpers.parseOptions)(options);
70
+ }
71
+ return {
72
+ co2: this.model.perByte(bytes, green, this.model.results.segment, adjustments),
73
+ green,
74
+ variables: {
75
+ description: "Below are the variables used to calculate this CO2 estimate.",
76
+ bytes,
77
+ gridIntensity: {
78
+ description: "The grid intensity (grams per kilowatt-hour) used to calculate this CO2 estimate.",
79
+ network: ((_b = (_a = adjustments == null ? void 0 : adjustments.gridIntensity) == null ? void 0 : _a.network) == null ? void 0 : _b.value) || import_constants.GLOBAL_GRID_INTENSITY,
80
+ dataCenter: green ? import_constants.RENEWABLES_GRID_INTENSITY : ((_d = (_c = adjustments == null ? void 0 : adjustments.gridIntensity) == null ? void 0 : _c.dataCenter) == null ? void 0 : _d.value) || import_constants.GLOBAL_GRID_INTENSITY,
81
+ production: import_constants.GLOBAL_GRID_INTENSITY,
82
+ device: ((_f = (_e = adjustments == null ? void 0 : adjustments.gridIntensity) == null ? void 0 : _e.device) == null ? void 0 : _f.value) || import_constants.GLOBAL_GRID_INTENSITY
83
+ }
84
+ }
85
+ };
86
+ }
87
+ perVisitTrace(bytes, green = false, options = {}) {
88
+ var _a, _b, _c, _d, _e, _f, _g;
89
+ if ((_a = this.model) == null ? void 0 : _a.perVisit) {
90
+ let adjustments = {};
91
+ if (options) {
92
+ adjustments = (0, import_helpers.parseOptions)(options);
93
+ }
94
+ return {
95
+ co2: this.model.perVisit(bytes, green, this.model.results.segment, adjustments),
96
+ green,
97
+ variables: {
98
+ description: "Below are the variables used to calculate this CO2 estimate.",
99
+ bytes,
100
+ gridIntensity: {
101
+ description: "The grid intensity (grams per kilowatt-hour) used to calculate this CO2 estimate.",
102
+ network: ((_c = (_b = adjustments == null ? void 0 : adjustments.gridIntensity) == null ? void 0 : _b.network) == null ? void 0 : _c.value) || import_constants.GLOBAL_GRID_INTENSITY,
103
+ dataCenter: green ? import_constants.RENEWABLES_GRID_INTENSITY : ((_e = (_d = adjustments == null ? void 0 : adjustments.gridIntensity) == null ? void 0 : _d.dataCenter) == null ? void 0 : _e.value) || import_constants.GLOBAL_GRID_INTENSITY,
104
+ production: import_constants.GLOBAL_GRID_INTENSITY,
105
+ device: ((_g = (_f = adjustments == null ? void 0 : adjustments.gridIntensity) == null ? void 0 : _f.device) == null ? void 0 : _g.value) || import_constants.GLOBAL_GRID_INTENSITY
106
+ },
107
+ dataReloadRatio: (adjustments == null ? void 0 : adjustments.dataReloadRatio) || 0.02,
108
+ firstVisitPercentage: (adjustments == null ? void 0 : adjustments.firstVisitPercentage) || 0.75,
109
+ returnVisitPercentage: (adjustments == null ? void 0 : adjustments.returnVisitPercentage) || 0.25
110
+ }
111
+ };
112
+ } else {
113
+ throw new Error(`The perVisitDetailed() method is not supported in the model you are using. Try using perByte() instead.
51
114
  See https://developers.thegreenwebfoundation.org/co2js/methods/ to learn more about the methods available in CO2.js.`);
52
115
  }
53
116
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/co2.js"],
4
- "sourcesContent": ["\"use strict\";\n\nimport OneByte from \"./1byte.js\";\nimport SustainableWebDesign from \"./sustainable-web-design.js\";\n\nclass CO2 {\n constructor(options) {\n this.model = new SustainableWebDesign();\n // Using optional chaining allows an empty object to be passed\n // in without breaking the code.\n if (options?.model === \"1byte\") {\n this.model = new OneByte();\n } else if (options?.model === \"swd\") {\n this.model = new SustainableWebDesign();\n } else if (options?.model) {\n throw new Error(\n `\"${options.model}\" is not a valid model. Please use \"1byte\" for the OneByte model, and \"swd\" for the Sustainable Web Design model.\\nSee https://developers.thegreenwebfoundation.org/co2js/models/ to learn more about the models available in CO2.js.`\n );\n }\n }\n\n /**\n * Accept a figure in bytes for data transfer, and a boolean for whether\n * the domain shows as 'green', and return a CO2 figure for energy used to shift the corresponding\n * the data transfer.\n *\n * @param {number} bytes\n * @param {boolean} green\n * @return {number} the amount of CO2 in grammes\n */\n perByte(bytes, green) {\n return this.model.perByte(bytes, green);\n }\n\n /**\n * Accept a figure in bytes for data transfer, and a boolean for whether\n * the domain shows as 'green', and return a CO2 figure for energy used to shift the corresponding\n * the data transfer.\n *\n * @param {number} bytes\n * @param {boolean} green\n * @return {number} the amount of CO2 in grammes\n */\n perVisit(bytes, green) {\n if (this.model?.perVisit) {\n return this.model.perVisit(bytes, green);\n } else {\n throw new Error(\n `The perVisit() method is not supported in the model you are using. Try using perByte() instead.\\nSee https://developers.thegreenwebfoundation.org/co2js/methods/ to learn more about the methods available in CO2.js.`\n );\n }\n }\n\n perDomain(pageXray, greenDomains) {\n const co2PerDomain = [];\n for (let domain of Object.keys(pageXray.domains)) {\n let co2;\n if (greenDomains && greenDomains.indexOf(domain) > -1) {\n co2 = this.perByte(pageXray.domains[domain].transferSize, true);\n } else {\n co2 = this.perByte(pageXray.domains[domain].transferSize);\n }\n co2PerDomain.push({\n domain,\n co2,\n transferSize: pageXray.domains[domain].transferSize,\n });\n }\n co2PerDomain.sort((a, b) => b.co2 - a.co2);\n\n return co2PerDomain;\n }\n\n perPage(pageXray, green) {\n // Accept an xray object, and if we receive a boolean as the second\n // argument, we assume every request we make is sent to a server\n // running on renwewable power.\n\n // if we receive an array of domains, return a number accounting the\n // reduced CO2 from green hosted domains\n\n const domainCO2 = this.perDomain(pageXray, green);\n let totalCO2 = 0;\n for (let domain of domainCO2) {\n totalCO2 += domain.co2;\n }\n return totalCO2;\n }\n\n perContentType(pageXray, greenDomains) {\n const co2PerContentType = {};\n for (let asset of pageXray.assets) {\n const domain = new URL(asset.url).domain;\n const transferSize = asset.transferSize;\n const co2ForTransfer = this.perByte(\n transferSize,\n greenDomains && greenDomains.indexOf(domain) > -1\n );\n const contentType = asset.type;\n if (!co2PerContentType[contentType]) {\n co2PerContentType[contentType] = { co2: 0, transferSize: 0 };\n }\n co2PerContentType[contentType].co2 += co2ForTransfer;\n co2PerContentType[contentType].transferSize += transferSize;\n }\n // restructure and sort\n const all = [];\n for (let type of Object.keys(co2PerContentType)) {\n all.push({\n type,\n co2: co2PerContentType[type].co2,\n transferSize: co2PerContentType[type].transferSize,\n });\n }\n all.sort((a, b) => b.co2 - a.co2);\n return all;\n }\n\n dirtiestResources(pageXray, greenDomains) {\n const allAssets = [];\n for (let asset of pageXray.assets) {\n const domain = new URL(asset.url).domain;\n const transferSize = asset.transferSize;\n const co2ForTransfer = this.perByte(\n transferSize,\n greenDomains && greenDomains.indexOf(domain) > -1\n );\n allAssets.push({ url: asset.url, co2: co2ForTransfer, transferSize });\n }\n allAssets.sort((a, b) => b.co2 - a.co2);\n\n return allAssets.slice(0, allAssets.length > 10 ? 10 : allAssets.length);\n }\n\n perParty(pageXray, greenDomains) {\n let firstParty = 0;\n let thirdParty = 0;\n // calculate co2 per first/third party\n const firstPartyRegEx = pageXray.firstPartyRegEx;\n for (let d of Object.keys(pageXray.domains)) {\n if (!d.match(firstPartyRegEx)) {\n thirdParty += this.perByte(\n pageXray.domains[d].transferSize,\n greenDomains && greenDomains.indexOf(d) > -1\n );\n } else {\n firstParty += this.perByte(\n pageXray.domains[d].transferSize,\n greenDomains && greenDomains.indexOf(d) > -1\n );\n }\n }\n return { firstParty, thirdParty };\n }\n}\n\nexport { CO2 };\nexport default CO2;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,kBAAoB;AACpB,oCAAiC;AAEjC,MAAM,IAAI;AAAA,EACR,YAAY,SAAS;AACnB,SAAK,QAAQ,IAAI,sCAAqB;AAGtC,QAAI,oCAAS,WAAU,SAAS;AAC9B,WAAK,QAAQ,IAAI,oBAAQ;AAAA,IAC3B,WAAW,oCAAS,WAAU,OAAO;AACnC,WAAK,QAAQ,IAAI,sCAAqB;AAAA,IACxC,WAAW,mCAAS,OAAO;AACzB,YAAM,IAAI,MACR,IAAI,QAAQ;AAAA,mHACd;AAAA,IACF;AAAA,EACF;AAAA,EAWA,QAAQ,OAAO,OAAO;AACpB,WAAO,KAAK,MAAM,QAAQ,OAAO,KAAK;AAAA,EACxC;AAAA,EAWA,SAAS,OAAO,OAAO;AA3CzB;AA4CI,QAAI,WAAK,UAAL,mBAAY,UAAU;AACxB,aAAO,KAAK,MAAM,SAAS,OAAO,KAAK;AAAA,IACzC,OAAO;AACL,YAAM,IAAI,MACR;AAAA,qHACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,UAAU,UAAU,cAAc;AAChC,UAAM,eAAe,CAAC;AACtB,aAAS,UAAU,OAAO,KAAK,SAAS,OAAO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MAAM,EAAE,GAAG;AAChC,WAAO;AAAA,EACT;AAAA,EAEA,kBAAkB,UAAU,cAAc;AACxC,UAAM,YAAY,CAAC;AACnB,aAAS,SAAS,SAAS,QAAQ;AACjC,YAAM,SAAS,IAAI,IAAI,MAAM,GAAG,EAAE;AAClC,YAAM,eAAe,MAAM;AAC3B,YAAM,iBAAiB,KAAK,QAC1B,cACA,gBAAgB,aAAa,QAAQ,MAAM,IAAI,EACjD;AACA,gBAAU,KAAK,EAAE,KAAK,MAAM,KAAK,KAAK,gBAAgB,aAAa,CAAC;AAAA,IACtE;AACA,cAAU,KAAK,CAAC,GAAG,MAAM,EAAE,MAAM,EAAE,GAAG;AAEtC,WAAO,UAAU,MAAM,GAAG,UAAU,SAAS,KAAK,KAAK,UAAU,MAAM;AAAA,EACzE;AAAA,EAEA,SAAS,UAAU,cAAc;AAC/B,QAAI,aAAa;AACjB,QAAI,aAAa;AAEjB,UAAM,kBAAkB,SAAS;AACjC,aAAS,KAAK,OAAO,KAAK,SAAS,OAAO,GAAG;AAC3C,UAAI,CAAC,EAAE,MAAM,eAAe,GAAG;AAC7B,sBAAc,KAAK,QACjB,SAAS,QAAQ,GAAG,cACpB,gBAAgB,aAAa,QAAQ,CAAC,IAAI,EAC5C;AAAA,MACF,OAAO;AACL,sBAAc,KAAK,QACjB,SAAS,QAAQ,GAAG,cACpB,gBAAgB,aAAa,QAAQ,CAAC,IAAI,EAC5C;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,YAAY,WAAW;AAAA,EAClC;AACF;AAGA,IAAO,cAAQ;",
4
+ "sourcesContent": ["\"use strict\";\n\n/**\n * @typedef {Object} CO2EstimateTraceResultPerByte\n * @property {number} co2 - The CO2 estimate in grams/kilowatt-hour\n * @property {boolean} green - Whether the domain is green or not\n * @property {TraceResultVariables} variables - The variables used to calculate the CO2 estimate\n */\n\n/**\n * @typedef {Object} CO2EstimateTraceResultPerVisit\n * @property {number} co2 - The CO2 estimate in grams/kilowatt-hour\n * @property {boolean} green - Whether the domain is green or not\n * @property {TraceResultVariables} variables - The variables used to calculate the CO2 estimate\n */\n\n/**\n * @typedef {Object} TraceResultVariablesPerByte\n * @property {GridIntensityVariables} gridIntensity - The grid intensity related variables\n */\n/**\n * @typedef {Object} TraceResultVariablesPerVisit\n * @property {GridIntensityVariables} gridIntensity - The grid intensity related variables\n * @property {number} dataReloadRatio - What percentage of a page is reloaded on each subsequent page view\n * @property {number} firstVisitPercentage - What percentage of visits are loading this page for subsequent times\n * @property {number} returnVisitPercentage - What percentage of visits are loading this page for the second or more time\n */\n\n/**\n * @typedef {Object} GridIntensityVariables\n * @property {string} description - The description of the variables\n * @property {number} network - The network grid intensity set by the user or the default\n * @property {number} dataCenter - The data center grid intensity set by the user or the default\n * @property {number} device - The device grid intensity set by the user or the default\n * @property {number} production - The production grid intensity set by the user or the default\n */\n\nimport OneByte from \"./1byte.js\";\nimport SustainableWebDesign from \"./sustainable-web-design.js\";\n\nimport {\n GLOBAL_GRID_INTENSITY,\n RENEWABLES_GRID_INTENSITY,\n} from \"./constants/index.js\";\nimport { parseOptions } from \"./helpers/index.js\";\n\nclass CO2 {\n constructor(options) {\n this.model = new SustainableWebDesign();\n // Using optional chaining allows an empty object to be passed\n // in without breaking the code.\n if (options?.model === \"1byte\") {\n this.model = new OneByte();\n } else if (options?.model === \"swd\") {\n this.model = new SustainableWebDesign();\n } else if (options?.model) {\n throw new Error(\n `\"${options.model}\" is not a valid model. Please use \"1byte\" for the OneByte model, and \"swd\" for the Sustainable Web Design model.\\nSee https://developers.thegreenwebfoundation.org/co2js/models/ to learn more about the models available in CO2.js.`\n );\n }\n\n if (options?.results === \"segment\") {\n this.model.results = {\n segment: true,\n };\n } else {\n this.model.results = {\n segment: false,\n };\n }\n }\n\n /**\n * Accept a figure in bytes for data transfer, and a boolean for whether\n * the domain shows as 'green', and return a CO2 figure for energy used to shift the corresponding\n * the data transfer.\n *\n * @param {number} bytes\n * @param {boolean} green\n * @return {number} the amount of CO2 in grammes\n */\n perByte(bytes, green = false) {\n return this.model.perByte(bytes, green, this.model.results.segment);\n }\n\n /**\n * Accept a figure in bytes for data transfer, and a boolean for whether\n * the domain shows as 'green', and return a CO2 figure for energy used to shift the corresponding\n * the data transfer.\n *\n * @param {number} bytes\n * @param {boolean} green\n * @return {number} the amount of CO2 in grammes\n */\n perVisit(bytes, green = false) {\n if (this.model?.perVisit) {\n return this.model.perVisit(bytes, green, this.model.results.segment);\n } else {\n throw new Error(\n `The perVisit() method is not supported in the model you are using. Try using perByte() instead.\\nSee https://developers.thegreenwebfoundation.org/co2js/methods/ to learn more about the methods available in CO2.js.`\n );\n }\n }\n\n /**\n * Accept a figure in bytes for data transfer, a boolean for whether\n * the domain shows as 'green', and an options object.\n * Returns an object containing CO2 figure, green boolean, and object of the variables used in calculating the CO2 figure.\n *\n * @param {number} bytes\n * @param {boolean} green\n * @param {Object} options\n * @return {CO2EstimateTraceResultPerByte} the amount of CO2 in grammes\n */\n perByteTrace(bytes, green = false, options = {}) {\n let adjustments = {};\n if (options) {\n // If there are options, parse them and add them to the model.\n adjustments = parseOptions(options);\n }\n return {\n co2: this.model.perByte(\n bytes,\n green,\n this.model.results.segment,\n adjustments\n ),\n green,\n variables: {\n description:\n \"Below are the variables used to calculate this CO2 estimate.\",\n bytes,\n gridIntensity: {\n description:\n \"The grid intensity (grams per kilowatt-hour) used to calculate this CO2 estimate.\",\n network:\n adjustments?.gridIntensity?.network?.value || GLOBAL_GRID_INTENSITY,\n dataCenter: green\n ? RENEWABLES_GRID_INTENSITY\n : adjustments?.gridIntensity?.dataCenter?.value ||\n GLOBAL_GRID_INTENSITY,\n production: GLOBAL_GRID_INTENSITY,\n device:\n adjustments?.gridIntensity?.device?.value || GLOBAL_GRID_INTENSITY,\n },\n },\n };\n }\n\n /**\n * Accept a figure in bytes for data transfer, a boolean for whether\n * the domain shows as 'green', and an options object.\n * Returns an object containing CO2 figure, green boolean, and object of the variables used in calculating the CO2 figure.\n *\n * @param {number} bytes\n * @param {boolean} green\n * @param {Object} options\n * @return {CO2EstimateTraceResultPerVisit} the amount of CO2 in grammes\n */\n perVisitTrace(bytes, green = false, options = {}) {\n if (this.model?.perVisit) {\n let adjustments = {};\n if (options) {\n // If there are options, parse them and add them to the model.\n adjustments = parseOptions(options);\n }\n\n return {\n co2: this.model.perVisit(\n bytes,\n green,\n this.model.results.segment,\n adjustments\n ),\n green,\n variables: {\n description:\n \"Below are the variables used to calculate this CO2 estimate.\",\n bytes,\n gridIntensity: {\n description:\n \"The grid intensity (grams per kilowatt-hour) used to calculate this CO2 estimate.\",\n network:\n adjustments?.gridIntensity?.network?.value ||\n GLOBAL_GRID_INTENSITY,\n dataCenter: green\n ? RENEWABLES_GRID_INTENSITY\n : adjustments?.gridIntensity?.dataCenter?.value ||\n GLOBAL_GRID_INTENSITY,\n production: GLOBAL_GRID_INTENSITY,\n device:\n adjustments?.gridIntensity?.device?.value ||\n GLOBAL_GRID_INTENSITY,\n },\n dataReloadRatio: adjustments?.dataReloadRatio || 0.02,\n firstVisitPercentage: adjustments?.firstVisitPercentage || 0.75,\n returnVisitPercentage: adjustments?.returnVisitPercentage || 0.25,\n },\n };\n } else {\n throw new Error(\n `The perVisitDetailed() method is not supported in the model you are using. Try using perByte() instead.\\nSee https://developers.thegreenwebfoundation.org/co2js/methods/ to learn more about the methods available in CO2.js.`\n );\n }\n }\n\n perDomain(pageXray, greenDomains) {\n const co2PerDomain = [];\n for (let domain of Object.keys(pageXray.domains)) {\n let co2;\n if (greenDomains && greenDomains.indexOf(domain) > -1) {\n co2 = this.perByte(pageXray.domains[domain].transferSize, true);\n } else {\n co2 = this.perByte(pageXray.domains[domain].transferSize);\n }\n co2PerDomain.push({\n domain,\n co2,\n transferSize: pageXray.domains[domain].transferSize,\n });\n }\n co2PerDomain.sort((a, b) => b.co2 - a.co2);\n\n return co2PerDomain;\n }\n\n perPage(pageXray, green) {\n // Accept an xray object, and if we receive a boolean as the second\n // argument, we assume every request we make is sent to a server\n // running on renwewable power.\n\n // if we receive an array of domains, return a number accounting the\n // reduced CO2 from green hosted domains\n\n const domainCO2 = this.perDomain(pageXray, green);\n let totalCO2 = 0;\n for (let domain of domainCO2) {\n totalCO2 += domain.co2;\n }\n return totalCO2;\n }\n\n perContentType(pageXray, greenDomains) {\n const co2PerContentType = {};\n for (let asset of pageXray.assets) {\n const domain = new URL(asset.url).domain;\n const transferSize = asset.transferSize;\n const co2ForTransfer = this.perByte(\n transferSize,\n greenDomains && greenDomains.indexOf(domain) > -1\n );\n const contentType = asset.type;\n if (!co2PerContentType[contentType]) {\n co2PerContentType[contentType] = { co2: 0, transferSize: 0 };\n }\n co2PerContentType[contentType].co2 += co2ForTransfer;\n co2PerContentType[contentType].transferSize += transferSize;\n }\n // restructure and sort\n const all = [];\n for (let type of Object.keys(co2PerContentType)) {\n all.push({\n type,\n co2: co2PerContentType[type].co2,\n transferSize: co2PerContentType[type].transferSize,\n });\n }\n all.sort((a, b) => b.co2 - a.co2);\n return all;\n }\n\n dirtiestResources(pageXray, greenDomains) {\n const allAssets = [];\n for (let asset of pageXray.assets) {\n const domain = new URL(asset.url).domain;\n const transferSize = asset.transferSize;\n const co2ForTransfer = this.perByte(\n transferSize,\n greenDomains && greenDomains.indexOf(domain) > -1\n );\n allAssets.push({ url: asset.url, co2: co2ForTransfer, transferSize });\n }\n allAssets.sort((a, b) => b.co2 - a.co2);\n\n return allAssets.slice(0, allAssets.length > 10 ? 10 : allAssets.length);\n }\n\n perParty(pageXray, greenDomains) {\n let firstParty = 0;\n let thirdParty = 0;\n // calculate co2 per first/third party\n const firstPartyRegEx = pageXray.firstPartyRegEx;\n for (let d of Object.keys(pageXray.domains)) {\n if (!d.match(firstPartyRegEx)) {\n thirdParty += this.perByte(\n pageXray.domains[d].transferSize,\n greenDomains && greenDomains.indexOf(d) > -1\n );\n } else {\n firstParty += this.perByte(\n pageXray.domains[d].transferSize,\n greenDomains && greenDomains.indexOf(d) > -1\n );\n }\n }\n return { firstParty, thirdParty };\n }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ChC,WAAO;AAAA,EACT;AAAA,EAEA,kBAAkB,UAAU,cAAc;AACxC,UAAM,YAAY,CAAC;AACnB,aAAS,SAAS,SAAS,QAAQ;AACjC,YAAM,SAAS,IAAI,IAAI,MAAM,GAAG,EAAE;AAClC,YAAM,eAAe,MAAM;AAC3B,YAAM,iBAAiB,KAAK,QAC1B,cACA,gBAAgB,aAAa,QAAQ,MAAM,IAAI,EACjD;AACA,gBAAU,KAAK,EAAE,KAAK,MAAM,KAAK,KAAK,gBAAgB,aAAa,CAAC;AAAA,IACtE;AACA,cAAU,KAAK,CAAC,GAAG,MAAM,EAAE,MAAM,EAAE,GAAG;AAEtC,WAAO,UAAU,MAAM,GAAG,UAAU,SAAS,KAAK,KAAK,UAAU,MAAM;AAAA,EACzE;AAAA,EAEA,SAAS,UAAU,cAAc;AAC/B,QAAI,aAAa;AACjB,QAAI,aAAa;AAEjB,UAAM,kBAAkB,SAAS;AACjC,aAAS,KAAK,OAAO,KAAK,SAAS,OAAO,GAAG;AAC3C,UAAI,CAAC,EAAE,MAAM,eAAe,GAAG;AAC7B,sBAAc,KAAK,QACjB,SAAS,QAAQ,GAAG,cACpB,gBAAgB,aAAa,QAAQ,CAAC,IAAI,EAC5C;AAAA,MACF,OAAO;AACL,sBAAc,KAAK,QACjB,SAAS,QAAQ,GAAG,cACpB,gBAAgB,aAAa,QAAQ,CAAC,IAAI,EAC5C;AAAA,MACF;AAAA,IACF;AACA,WAAO,EAAE,YAAY,WAAW;AAAA,EAClC;AACF;AAGA,IAAO,cAAQ;",
6
6
  "names": []
7
7
  }
@@ -20,8 +20,30 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
21
  var constants_exports = {};
22
22
  __export(constants_exports, {
23
- fileSize: () => import_file_size.default
23
+ DATACENTER_ENERGY: () => DATACENTER_ENERGY,
24
+ END_USER_DEVICE_ENERGY: () => END_USER_DEVICE_ENERGY,
25
+ FIRST_TIME_VIEWING_PERCENTAGE: () => FIRST_TIME_VIEWING_PERCENTAGE,
26
+ GLOBAL_GRID_INTENSITY: () => GLOBAL_GRID_INTENSITY,
27
+ KWH_PER_GB: () => KWH_PER_GB,
28
+ NETWORK_ENERGY: () => NETWORK_ENERGY,
29
+ PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD: () => PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD,
30
+ PRODUCTION_ENERGY: () => PRODUCTION_ENERGY,
31
+ RENEWABLES_GRID_INTENSITY: () => RENEWABLES_GRID_INTENSITY,
32
+ RETURNING_VISITOR_PERCENTAGE: () => RETURNING_VISITOR_PERCENTAGE,
33
+ fileSize: () => import_file_size.default,
34
+ testConstants: () => import_test_constants.default
24
35
  });
25
36
  module.exports = __toCommonJS(constants_exports);
26
37
  var import_file_size = __toESM(require("./file-size.js"));
38
+ var import_test_constants = __toESM(require("./test-constants.js"));
39
+ const KWH_PER_GB = 0.81;
40
+ const END_USER_DEVICE_ENERGY = 0.52;
41
+ const NETWORK_ENERGY = 0.14;
42
+ const DATACENTER_ENERGY = 0.15;
43
+ const PRODUCTION_ENERGY = 0.19;
44
+ const GLOBAL_GRID_INTENSITY = 442;
45
+ const RENEWABLES_GRID_INTENSITY = 50;
46
+ const FIRST_TIME_VIEWING_PERCENTAGE = 0.75;
47
+ const RETURNING_VISITOR_PERCENTAGE = 0.25;
48
+ const PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD = 0.02;
27
49
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/constants/index.js"],
4
- "sourcesContent": ["import fileSize from \"./file-size.js\";\n\nexport { fileSize };\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;",
4
+ "sourcesContent": ["import fileSize from \"./file-size.js\";\nimport testConstants from \"./test-constants.js\";\n\n// SUSTAINABLE WEB DESIGN CONSTANTS\n// this refers to the estimated total energy use for the internet around 2000 TWh,\n// divided by the total transfer it enables around 2500 exabytes\nconst KWH_PER_GB = 0.81;\n\n// these constants outline how the energy is attributed to\n// different parts of the system in the SWD model\nconst END_USER_DEVICE_ENERGY = 0.52;\nconst NETWORK_ENERGY = 0.14;\nconst DATACENTER_ENERGY = 0.15;\nconst PRODUCTION_ENERGY = 0.19;\n\n// These carbon intensity figures https://ember-climate.org/data/data-explorer\n// - Global carbon intensity for 2021\nconst GLOBAL_GRID_INTENSITY = 442;\nconst RENEWABLES_GRID_INTENSITY = 50;\n\n// Taken from: https://gitlab.com/wholegrain/carbon-api-2-0/-/blob/master/includes/carbonapi.php\n\nconst FIRST_TIME_VIEWING_PERCENTAGE = 0.75;\nconst RETURNING_VISITOR_PERCENTAGE = 0.25;\nconst PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD = 0.02;\n\nexport {\n fileSize,\n testConstants,\n KWH_PER_GB,\n END_USER_DEVICE_ENERGY,\n NETWORK_ENERGY,\n DATACENTER_ENERGY,\n PRODUCTION_ENERGY,\n GLOBAL_GRID_INTENSITY,\n RENEWABLES_GRID_INTENSITY,\n FIRST_TIME_VIEWING_PERCENTAGE,\n RETURNING_VISITOR_PERCENTAGE,\n PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD,\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;AACrB,4BAA0B;AAK1B,MAAM,aAAa;AAInB,MAAM,yBAAyB;AAC/B,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAI1B,MAAM,wBAAwB;AAC9B,MAAM,4BAA4B;AAIlC,MAAM,gCAAgC;AACtC,MAAM,+BAA+B;AACrC,MAAM,+CAA+C;",
6
6
  "names": []
7
7
  }
@@ -17,8 +17,146 @@ var __copyProps = (to, from, except, desc) => {
17
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
18
  var helpers_exports = {};
19
19
  __export(helpers_exports, {
20
- formatNumber: () => formatNumber
20
+ formatNumber: () => formatNumber,
21
+ parseOptions: () => parseOptions
21
22
  });
22
23
  module.exports = __toCommonJS(helpers_exports);
24
+ var import__ = require("../index.js");
25
+ var import_constants = require("../constants/index.js");
23
26
  const formatNumber = (num) => parseFloat(num.toFixed(2));
27
+ function parseOptions(options) {
28
+ var _a, _b, _c, _d, _e, _f;
29
+ if (typeof options !== "object") {
30
+ throw new Error("Options must be an object");
31
+ }
32
+ const adjustments = {};
33
+ if (options == null ? void 0 : options.gridIntensity) {
34
+ adjustments.gridIntensity = {};
35
+ const { device, dataCenter, network } = options.gridIntensity;
36
+ if (device) {
37
+ if (typeof device === "object") {
38
+ if (!import__.averageIntensity.data[(_a = device.country) == null ? void 0 : _a.toUpperCase()]) {
39
+ console.warn(`"${device.country}" is not a valid country. Please use a valid 3 digit ISO 3166 country code.
40
+ See https://developers.thegreenwebfoundation.org/co2js/data/ for more information.
41
+ Falling back to global average grid intensity.`);
42
+ adjustments.gridIntensity["device"] = {
43
+ value: import_constants.GLOBAL_GRID_INTENSITY
44
+ };
45
+ }
46
+ adjustments.gridIntensity["device"] = {
47
+ country: device.country,
48
+ value: parseFloat(import__.averageIntensity.data[(_b = device.country) == null ? void 0 : _b.toUpperCase()])
49
+ };
50
+ } else if (typeof device === "number") {
51
+ adjustments.gridIntensity["device"] = {
52
+ value: device
53
+ };
54
+ } else {
55
+ adjustments.gridIntensity["device"] = {
56
+ value: import_constants.GLOBAL_GRID_INTENSITY
57
+ };
58
+ console.warn(`The device grid intensity must be a number or an object. You passed in a ${typeof device}.
59
+ Falling back to global average grid intensity.`);
60
+ }
61
+ }
62
+ if (dataCenter) {
63
+ if (typeof dataCenter === "object") {
64
+ if (!import__.averageIntensity.data[(_c = dataCenter.country) == null ? void 0 : _c.toUpperCase()]) {
65
+ console.warn(`"${dataCenter.country}" is not a valid country. Please use a valid 3 digit ISO 3166 country code.
66
+ See https://developers.thegreenwebfoundation.org/co2js/data/ for more information.
67
+ Falling back to global average grid intensity.`);
68
+ adjustments.gridIntensity["dataCenter"] = {
69
+ value: import_constants.GLOBAL_GRID_INTENSITY
70
+ };
71
+ }
72
+ adjustments.gridIntensity["dataCenter"] = {
73
+ country: dataCenter.country,
74
+ value: parseFloat(import__.averageIntensity.data[(_d = dataCenter.country) == null ? void 0 : _d.toUpperCase()])
75
+ };
76
+ } else if (typeof dataCenter === "number") {
77
+ adjustments.gridIntensity["dataCenter"] = {
78
+ value: dataCenter
79
+ };
80
+ } else {
81
+ adjustments.gridIntensity["dataCenter"] = {
82
+ value: import_constants.GLOBAL_GRID_INTENSITY
83
+ };
84
+ console.warn(`The data center grid intensity must be a number or an object. You passed in a ${typeof dataCenter}.
85
+ Falling back to global average grid intensity.`);
86
+ }
87
+ }
88
+ if (network) {
89
+ if (typeof network === "object") {
90
+ if (!import__.averageIntensity.data[(_e = network.country) == null ? void 0 : _e.toUpperCase()]) {
91
+ console.warn(`"${network.country}" is not a valid country. Please use a valid 3 digit ISO 3166 country code.
92
+ See https://developers.thegreenwebfoundation.org/co2js/data/ for more information. Falling back to global average grid intensity.
93
+ Falling back to global average grid intensity.`);
94
+ adjustments.gridIntensity["network"] = {
95
+ value: import_constants.GLOBAL_GRID_INTENSITY
96
+ };
97
+ }
98
+ adjustments.gridIntensity["network"] = {
99
+ country: network.country,
100
+ value: parseFloat(import__.averageIntensity.data[(_f = network.country) == null ? void 0 : _f.toUpperCase()])
101
+ };
102
+ } else if (typeof network === "number") {
103
+ adjustments.gridIntensity["network"] = {
104
+ value: network
105
+ };
106
+ } else {
107
+ adjustments.gridIntensity["network"] = {
108
+ value: import_constants.GLOBAL_GRID_INTENSITY
109
+ };
110
+ console.warn(`The network grid intensity must be a number or an object. You passed in a ${typeof network}.
111
+ Falling back to global average grid intensity.`);
112
+ }
113
+ }
114
+ }
115
+ if (options == null ? void 0 : options.dataReloadRatio) {
116
+ if (typeof options.dataReloadRatio === "number") {
117
+ if (options.dataReloadRatio >= 0 && options.dataReloadRatio <= 1) {
118
+ adjustments.dataReloadRatio = options.dataReloadRatio;
119
+ } else {
120
+ adjustments.dataReloadRatio = import_constants.PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD;
121
+ console.warn(`The dataReloadRatio option must be a number between 0 and 1. You passed in ${options.dataReloadRatio}.
122
+ Falling back to default value.`);
123
+ }
124
+ } else {
125
+ adjustments.dataReloadRatio = import_constants.PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD;
126
+ console.warn(`The dataReloadRatio option must be a number. You passed in a ${typeof options.dataReloadRatio}.
127
+ Falling back to default value.`);
128
+ }
129
+ }
130
+ if (options == null ? void 0 : options.firstVisitPercentage) {
131
+ if (typeof options.firstVisitPercentage === "number") {
132
+ if (options.firstVisitPercentage >= 0 && options.firstVisitPercentage <= 1) {
133
+ adjustments.firstVisitPercentage = options.firstVisitPercentage;
134
+ } else {
135
+ adjustments.firstVisitPercentage = import_constants.FIRST_TIME_VIEWING_PERCENTAGE;
136
+ console.warn(`The firstVisitPercentage option must be a number between 0 and 1. You passed in ${options.firstVisitPercentage}.
137
+ Falling back to default value.`);
138
+ }
139
+ } else {
140
+ adjustments.firstVisitPercentage = import_constants.FIRST_TIME_VIEWING_PERCENTAGE;
141
+ console.warn(`The firstVisitPercentage option must be a number. You passed in a ${typeof options.firstVisitPercentage}.
142
+ Falling back to default value.`);
143
+ }
144
+ }
145
+ if (options == null ? void 0 : options.returnVisitPercentage) {
146
+ if (typeof options.returnVisitPercentage === "number") {
147
+ if (options.returnVisitPercentage >= 0 && options.returnVisitPercentage <= 1) {
148
+ adjustments.returnVisitPercentage = options.returnVisitPercentage;
149
+ } else {
150
+ adjustments.returnVisitPercentage = import_constants.RETURNING_VISITOR_PERCENTAGE;
151
+ console.warn(`The returnVisitPercentage option must be a number between 0 and 1. You passed in ${options.returnVisitPercentage}.
152
+ Falling back to default value.`);
153
+ }
154
+ } else {
155
+ adjustments.returnVisitPercentage = import_constants.RETURNING_VISITOR_PERCENTAGE;
156
+ console.warn(`The returnVisitPercentage option must be a number. You passed in a ${typeof options.returnVisitPercentage}.
157
+ Falling back to default value.`);
158
+ }
159
+ }
160
+ return adjustments;
161
+ }
24
162
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/helpers/index.js"],
4
- "sourcesContent": ["const formatNumber = (num) => parseFloat(num.toFixed(2));\n\nexport { formatNumber };\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAAM,eAAe,CAAC,QAAQ,WAAW,IAAI,QAAQ,CAAC,CAAC;",
4
+ "sourcesContent": ["import { averageIntensity } from \"../index.js\";\nimport {\n GLOBAL_GRID_INTENSITY,\n PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD,\n FIRST_TIME_VIEWING_PERCENTAGE,\n RETURNING_VISITOR_PERCENTAGE,\n} from \"../constants/index.js\";\nconst formatNumber = (num) => parseFloat(num.toFixed(2));\n\nfunction parseOptions(options) {\n // CHeck that it is an object\n if (typeof options !== \"object\") {\n throw new Error(\"Options must be an object\");\n }\n\n const adjustments = {};\n\n if (options?.gridIntensity) {\n adjustments.gridIntensity = {};\n const { device, dataCenter, network } = options.gridIntensity;\n if (device) {\n if (typeof device === \"object\") {\n if (!averageIntensity.data[device.country?.toUpperCase()]) {\n console.warn(\n `\"${device.country}\" is not a valid country. Please use a valid 3 digit ISO 3166 country code. \\nSee https://developers.thegreenwebfoundation.org/co2js/data/ for more information. \\nFalling back to global average grid intensity.`\n );\n adjustments.gridIntensity[\"device\"] = {\n value: GLOBAL_GRID_INTENSITY,\n };\n }\n adjustments.gridIntensity[\"device\"] = {\n country: device.country,\n value: parseFloat(\n averageIntensity.data[device.country?.toUpperCase()]\n ),\n };\n } else if (typeof device === \"number\") {\n adjustments.gridIntensity[\"device\"] = {\n value: device,\n };\n } else {\n adjustments.gridIntensity[\"device\"] = {\n value: GLOBAL_GRID_INTENSITY,\n };\n console.warn(\n `The device grid intensity must be a number or an object. You passed in a ${typeof device}. \\nFalling back to global average grid intensity.`\n );\n }\n }\n if (dataCenter) {\n if (typeof dataCenter === \"object\") {\n if (!averageIntensity.data[dataCenter.country?.toUpperCase()]) {\n console.warn(\n `\"${dataCenter.country}\" is not a valid country. Please use a valid 3 digit ISO 3166 country code. \\nSee https://developers.thegreenwebfoundation.org/co2js/data/ for more information. \\nFalling back to global average grid intensity.`\n );\n adjustments.gridIntensity[\"dataCenter\"] = {\n value: GLOBAL_GRID_INTENSITY,\n };\n }\n adjustments.gridIntensity[\"dataCenter\"] = {\n country: dataCenter.country,\n value: parseFloat(\n averageIntensity.data[dataCenter.country?.toUpperCase()]\n ),\n };\n } else if (typeof dataCenter === \"number\") {\n adjustments.gridIntensity[\"dataCenter\"] = {\n value: dataCenter,\n };\n } else {\n adjustments.gridIntensity[\"dataCenter\"] = {\n value: GLOBAL_GRID_INTENSITY,\n };\n console.warn(\n `The data center grid intensity must be a number or an object. You passed in a ${typeof dataCenter}. \\nFalling back to global average grid intensity.`\n );\n }\n }\n if (network) {\n if (typeof network === \"object\") {\n if (!averageIntensity.data[network.country?.toUpperCase()]) {\n console.warn(\n `\"${network.country}\" is not a valid country. Please use a valid 3 digit ISO 3166 country code. \\nSee https://developers.thegreenwebfoundation.org/co2js/data/ for more information. Falling back to global average grid intensity. \\nFalling back to global average grid intensity.`\n );\n adjustments.gridIntensity[\"network\"] = {\n value: GLOBAL_GRID_INTENSITY,\n };\n }\n adjustments.gridIntensity[\"network\"] = {\n country: network.country,\n value: parseFloat(\n averageIntensity.data[network.country?.toUpperCase()]\n ),\n };\n } else if (typeof network === \"number\") {\n adjustments.gridIntensity[\"network\"] = {\n value: network,\n };\n } else {\n adjustments.gridIntensity[\"network\"] = {\n value: GLOBAL_GRID_INTENSITY,\n };\n console.warn(\n `The network grid intensity must be a number or an object. You passed in a ${typeof network}. \\nFalling back to global average grid intensity.`\n );\n }\n }\n }\n\n if (options?.dataReloadRatio) {\n if (typeof options.dataReloadRatio === \"number\") {\n if (options.dataReloadRatio >= 0 && options.dataReloadRatio <= 1) {\n adjustments.dataReloadRatio = options.dataReloadRatio;\n } else {\n adjustments.dataReloadRatio =\n PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD;\n console.warn(\n `The dataReloadRatio option must be a number between 0 and 1. You passed in ${options.dataReloadRatio}. \\nFalling back to default value.`\n );\n }\n } else {\n adjustments.dataReloadRatio =\n PERCENTAGE_OF_DATA_LOADED_ON_SUBSEQUENT_LOAD;\n console.warn(\n `The dataReloadRatio option must be a number. You passed in a ${typeof options.dataReloadRatio}. \\nFalling back to default value.`\n );\n }\n }\n\n if (options?.firstVisitPercentage) {\n if (typeof options.firstVisitPercentage === \"number\") {\n if (\n options.firstVisitPercentage >= 0 &&\n options.firstVisitPercentage <= 1\n ) {\n adjustments.firstVisitPercentage = options.firstVisitPercentage;\n } else {\n adjustments.firstVisitPercentage = FIRST_TIME_VIEWING_PERCENTAGE;\n console.warn(\n `The firstVisitPercentage option must be a number between 0 and 1. You passed in ${options.firstVisitPercentage}. \\nFalling back to default value.`\n );\n }\n } else {\n adjustments.firstVisitPercentage = FIRST_TIME_VIEWING_PERCENTAGE;\n console.warn(\n `The firstVisitPercentage option must be a number. You passed in a ${typeof options.firstVisitPercentage}. \\nFalling back to default value.`\n );\n }\n }\n\n if (options?.returnVisitPercentage) {\n if (typeof options.returnVisitPercentage === \"number\") {\n if (\n options.returnVisitPercentage >= 0 &&\n options.returnVisitPercentage <= 1\n ) {\n adjustments.returnVisitPercentage = options.returnVisitPercentage;\n } else {\n adjustments.returnVisitPercentage = RETURNING_VISITOR_PERCENTAGE;\n console.warn(\n `The returnVisitPercentage option must be a number between 0 and 1. You passed in ${options.returnVisitPercentage}. \\nFalling back to default value.`\n );\n }\n } else {\n adjustments.returnVisitPercentage = RETURNING_VISITOR_PERCENTAGE;\n console.warn(\n `The returnVisitPercentage option must be a number. You passed in a ${typeof options.returnVisitPercentage}. \\nFalling back to default value.`\n );\n }\n }\n\n return adjustments;\n}\n\nexport { formatNumber, parseOptions };\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAiC;AACjC,uBAKO;AACP,MAAM,eAAe,CAAC,QAAQ,WAAW,IAAI,QAAQ,CAAC,CAAC;AAEvD,sBAAsB,SAAS;AAT/B;AAWE,MAAI,OAAO,YAAY,UAAU;AAC/B,UAAM,IAAI,MAAM,2BAA2B;AAAA,EAC7C;AAEA,QAAM,cAAc,CAAC;AAErB,MAAI,mCAAS,eAAe;AAC1B,gBAAY,gBAAgB,CAAC;AAC7B,UAAM,EAAE,QAAQ,YAAY,YAAY,QAAQ;AAChD,QAAI,QAAQ;AACV,UAAI,OAAO,WAAW,UAAU;AAC9B,YAAI,CAAC,0BAAiB,KAAK,aAAO,YAAP,mBAAgB,gBAAgB;AACzD,kBAAQ,KACN,IAAI,OAAO;AAAA;AAAA,+CACb;AACA,sBAAY,cAAc,YAAY;AAAA,YACpC,OAAO;AAAA,UACT;AAAA,QACF;AACA,oBAAY,cAAc,YAAY;AAAA,UACpC,SAAS,OAAO;AAAA,UAChB,OAAO,WACL,0BAAiB,KAAK,aAAO,YAAP,mBAAgB,cACxC;AAAA,QACF;AAAA,MACF,WAAW,OAAO,WAAW,UAAU;AACrC,oBAAY,cAAc,YAAY;AAAA,UACpC,OAAO;AAAA,QACT;AAAA,MACF,OAAO;AACL,oBAAY,cAAc,YAAY;AAAA,UACpC,OAAO;AAAA,QACT;AACA,gBAAQ,KACN,4EAA4E,OAAO;AAAA,+CACrF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AAI,OAAO,QAAQ,oBAAoB,UAAU;AAC/C,UAAI,QAAQ,mBAAmB,KAAK,QAAQ,mBAAmB,GAAG;AAChE,oBAAY,kBAAkB,QAAQ;AAAA,MACxC,OAAO;AACL,oBAAY,kBACV;AACF,gBAAQ,KACN,8EAA8E,QAAQ;AAAA,+BACxF;AAAA,MACF;AAAA,IACF,OAAO;AACL,kBAAY,kBACV;AACF,cAAQ,KACN,gEAAgE,OAAO,QAAQ;AAAA,+BACjF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,mCAAS,sBAAsB;AACjC,QAAI,OAAO,QAAQ,yBAAyB,UAAU;AACpD,UACE,QAAQ,wBAAwB,KAChC,QAAQ,wBAAwB,GAChC;AACA,oBAAY,uBAAuB,QAAQ;AAAA,MAC7C,OAAO;AACL,oBAAY,uBAAuB;AACnC,gBAAQ,KACN,mFAAmF,QAAQ;AAAA,+BAC7F;AAAA,MACF;AAAA,IACF,OAAO;AACL,kBAAY,uBAAuB;AACnC,cAAQ,KACN,qEAAqE,OAAO,QAAQ;AAAA,+BACtF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,mCAAS,uBAAuB;AAClC,QAAI,OAAO,QAAQ,0BAA0B,UAAU;AACrD,UACE,QAAQ,yBAAyB,KACjC,QAAQ,yBAAyB,GACjC;AACA,oBAAY,wBAAwB,QAAQ;AAAA,MAC9C,OAAO;AACL,oBAAY,wBAAwB;AACpC,gBAAQ,KACN,oFAAoF,QAAQ;AAAA,+BAC9F;AAAA,MACF;AAAA,IACF,OAAO;AACL,kBAAY,wBAAwB;AACpC,cAAQ,KACN,sEAAsE,OAAO,QAAQ;AAAA,+BACvF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -43,10 +43,6 @@ async function checkDomainsAgainstAPI(domains) {
43
43
  const apiPath = "https://api.thegreenwebfoundation.org/v2/greencheckmulti";
44
44
  const domainsString = JSON.stringify(domains);
45
45
  const req = await fetch(`${apiPath}/${domainsString}`);
46
- log(`${apiPath}/${domainsString}`);
47
- log({ req });
48
- const textResult = await req.text();
49
- log({ textResult });
50
46
  const allGreenCheckResults = await req.json();
51
47
  return greenDomainsFromResults(allGreenCheckResults);
52
48
  } catch (e) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hosting-api.js"],
4
- "sourcesContent": ["\"use strict\";\n\nimport debugFactory from \"debug\";\nconst log = debugFactory(\"tgwf:hostingAPI\");\n\nfunction check(domain) {\n // is it a single domain or an array of them?\n if (typeof domain === \"string\") {\n return checkAgainstAPI(domain);\n } else {\n return checkDomainsAgainstAPI(domain);\n }\n}\n\nasync function checkAgainstAPI(domain) {\n const req = await fetch(\n `https://api.thegreenwebfoundation.org/greencheck/${domain}`\n );\n const res = await req.json();\n return res.green;\n}\n\nasync function checkDomainsAgainstAPI(domains) {\n try {\n const apiPath = \"https://api.thegreenwebfoundation.org/v2/greencheckmulti\";\n const domainsString = JSON.stringify(domains);\n\n const req = await fetch(`${apiPath}/${domainsString}`);\n\n // sanity check API result. Is this the library or\n // the actual API request that's the problem?\n // Is nock mocking node-native fetch API calls properly?\n log(`${apiPath}/${domainsString}`);\n log({ req });\n const textResult = await req.text();\n log({ textResult });\n\n const allGreenCheckResults = await req.json();\n\n return greenDomainsFromResults(allGreenCheckResults);\n } catch (e) {\n return [];\n }\n}\n\nfunction greenDomainsFromResults(greenResults) {\n const entries = Object.entries(greenResults);\n const greenEntries = entries.filter(([key, val]) => val.green);\n return greenEntries.map(([key, val]) => val.url);\n}\n\nexport default {\n check,\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAyB;AACzB,MAAM,MAAM,0BAAa,iBAAiB;AAE1C,eAAe,QAAQ;AAErB,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,gBAAgB,MAAM;AAAA,EAC/B,OAAO;AACL,WAAO,uBAAuB,MAAM;AAAA,EACtC;AACF;AAEA,+BAA+B,QAAQ;AACrC,QAAM,MAAM,MAAM,MAChB,oDAAoD,QACtD;AACA,QAAM,MAAM,MAAM,IAAI,KAAK;AAC3B,SAAO,IAAI;AACb;AAEA,sCAAsC,SAAS;AAC7C,MAAI;AACF,UAAM,UAAU;AAChB,UAAM,gBAAgB,KAAK,UAAU,OAAO;AAE5C,UAAM,MAAM,MAAM,MAAM,GAAG,WAAW,eAAe;AAKrD,QAAI,GAAG,WAAW,eAAe;AACjC,QAAI,EAAE,IAAI,CAAC;AACX,UAAM,aAAa,MAAM,IAAI,KAAK;AAClC,QAAI,EAAE,WAAW,CAAC;AAElB,UAAM,uBAAuB,MAAM,IAAI,KAAK;AAE5C,WAAO,wBAAwB,oBAAoB;AAAA,EACrD,SAAS,GAAP;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,iCAAiC,cAAc;AAC7C,QAAM,UAAU,OAAO,QAAQ,YAAY;AAC3C,QAAM,eAAe,QAAQ,OAAO,CAAC,CAAC,KAAK,SAAS,IAAI,KAAK;AAC7D,SAAO,aAAa,IAAI,CAAC,CAAC,KAAK,SAAS,IAAI,GAAG;AACjD;AAEA,IAAO,sBAAQ;AAAA,EACb;AACF;",
4
+ "sourcesContent": ["\"use strict\";\n\nimport debugFactory from \"debug\";\nconst log = debugFactory(\"tgwf:hostingAPI\");\n\nfunction check(domain) {\n // is it a single domain or an array of them?\n if (typeof domain === \"string\") {\n return checkAgainstAPI(domain);\n } else {\n return checkDomainsAgainstAPI(domain);\n }\n}\n\nasync function checkAgainstAPI(domain) {\n const req = await fetch(\n `https://api.thegreenwebfoundation.org/greencheck/${domain}`\n );\n const res = await req.json();\n return res.green;\n}\n\nasync function checkDomainsAgainstAPI(domains) {\n try {\n const apiPath = \"https://api.thegreenwebfoundation.org/v2/greencheckmulti\";\n const domainsString = JSON.stringify(domains);\n\n const req = await fetch(`${apiPath}/${domainsString}`);\n\n // sanity check API result. Is this the library or\n // the actual API request that's the problem?\n // Is nock mocking node-native fetch API calls properly?\n // Commented out the logs for now, as they cause an error to be thrown when using the library.\n // log(`${apiPath}/${domainsString}`);\n // log({ req });\n // const textResult = await req.text();\n // log({ textResult });\n\n const allGreenCheckResults = await req.json();\n\n return greenDomainsFromResults(allGreenCheckResults);\n } catch (e) {\n return [];\n }\n}\n\nfunction greenDomainsFromResults(greenResults) {\n const entries = Object.entries(greenResults);\n const greenEntries = entries.filter(([key, val]) => val.green);\n return greenEntries.map(([key, val]) => val.url);\n}\n\nexport default {\n check,\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAyB;AACzB,MAAM,MAAM,0BAAa,iBAAiB;AAE1C,eAAe,QAAQ;AAErB,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,gBAAgB,MAAM;AAAA,EAC/B,OAAO;AACL,WAAO,uBAAuB,MAAM;AAAA,EACtC;AACF;AAEA,+BAA+B,QAAQ;AACrC,QAAM,MAAM,MAAM,MAChB,oDAAoD,QACtD;AACA,QAAM,MAAM,MAAM,IAAI,KAAK;AAC3B,SAAO,IAAI;AACb;AAEA,sCAAsC,SAAS;AAC7C,MAAI;AACF,UAAM,UAAU;AAChB,UAAM,gBAAgB,KAAK,UAAU,OAAO;AAE5C,UAAM,MAAM,MAAM,MAAM,GAAG,WAAW,eAAe;AAWrD,UAAM,uBAAuB,MAAM,IAAI,KAAK;AAE5C,WAAO,wBAAwB,oBAAoB;AAAA,EACrD,SAAS,GAAP;AACA,WAAO,CAAC;AAAA,EACV;AACF;AAEA,iCAAiC,cAAc;AAC7C,QAAM,UAAU,OAAO,QAAQ,YAAY;AAC3C,QAAM,eAAe,QAAQ,OAAO,CAAC,CAAC,KAAK,SAAS,IAAI,KAAK;AAC7D,SAAO,aAAa,IAAI,CAAC,CAAC,KAAK,SAAS,IAAI,GAAG;AACjD;AAEA,IAAO,sBAAQ;AAAA,EACb;AACF;",
6
6
  "names": []
7
7
  }
@@ -68,6 +68,7 @@ function checkDomainsInJSON(domains, db) {
68
68
  }
69
69
  module.exports = {
70
70
  check,
71
- loadJSON
71
+ loadJSON,
72
+ greenDomainsFromResults
72
73
  };
73
74
  //# sourceMappingURL=hosting-json.node.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/hosting-json.node.js"],
4
- "sourcesContent": ["\"use strict\";\n\nimport fs from \"fs\";\nimport zlib from \"zlib\";\nimport { promisify } from \"util\";\n\nconst readFile = promisify(fs.readFile);\nconst gunzip = promisify(zlib.gunzip);\n\nimport debugFactory from \"debug\";\nconst log = debugFactory(\"tgwf:hostingCache\");\n\nasync function streamToString(stream) {\n return new Promise((resolve, reject) => {\n const chunks = [];\n stream.on(\"error\", reject);\n stream.on(\"data\", (chunk) => chunks.push(chunk));\n stream.on(\"end\", () => resolve(Buffer.concat(chunks)));\n });\n}\n\nasync function getGzippedFileAsJson(jsonPath) {\n const readStream = fs.createReadStream(jsonPath);\n const text = await streamToString(readStream);\n const unzipped = await gunzip(text);\n return unzipped.toString();\n}\n\nasync function loadJSON(jsonPath) {\n const jsonBuffer = jsonPath.endsWith(\".gz\")\n ? await getGzippedFileAsJson(jsonPath)\n : await readFile(jsonPath);\n return JSON.parse(jsonBuffer);\n}\n\nasync function check(domain, db) {\n // is it a single domain or an array of them?\n if (typeof domain === \"string\") {\n return checkInJSON(domain, db);\n } else {\n return checkDomainsInJSON(domain, db);\n }\n}\n\nfunction checkInJSON(domain, db) {\n if (db.indexOf(domain) > -1) {\n return true;\n }\n return false;\n}\n\nfunction greenDomainsFromResults(greenResults) {\n const entries = Object.entries(greenResults);\n const greenEntries = entries.filter(([key, val]) => val.green);\n\n return greenEntries.map(([key, val]) => val.url);\n}\n\nfunction checkDomainsInJSON(domains, db) {\n let greenDomains = [];\n\n for (let domain of domains) {\n if (db.indexOf(domain) > -1) {\n greenDomains.push(domain);\n }\n }\n return greenDomains;\n}\n\nmodule.exports = {\n check,\n loadJ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C,CAAC,KAAK,SAAS,IAAI,GAAG;AACjD;AAEA,4BAA4B,SAAS,IAAI;AACvC,MAAI,eAAe,CAAC;AAEpB,WAAS,UAAU,SAAS;AAC1B,QAAI,GAAG,QAAQ,MAAM,IAAI,IAAI;AAC3B,mBAAa,KAAK,MAAM;AAAA,IAC1B;AAAA,EACF;AACA,SAAO;AACT;AAEA,OAAO,UAAU;AAAA,EACf;AAAA,EACA;AACF;",
4
+ "sourcesContent": ["\"use strict\";\n\nimport fs from \"fs\";\nimport zlib from \"zlib\";\nimport { promisify } from \"util\";\n\nconst readFile = promisify(fs.readFile);\nconst gunzip = promisify(zlib.gunzip);\n\nimport debugFactory from \"debug\";\nconst log = debugFactory(\"tgwf:hostingCache\");\n\nasync function streamToString(stream) {\n return new Promise((resolve, reject) => {\n const chunks = [];\n stream.on(\"error\", reject);\n stream.on(\"data\", (chunk) => chunks.push(chunk));\n stream.on(\"end\", () => resolve(Buffer.concat(chunks)));\n });\n}\n\nasync function getGzippedFileAsJson(jsonPath) {\n const readStream = fs.createReadStream(jsonPath);\n const text = await streamToString(readStream);\n const unzipped = await gunzip(text);\n return unzipped.toString();\n}\n\nasync function loadJSON(jsonPath) {\n const jsonBuffer = jsonPath.endsWith(\".gz\")\n ? await getGzippedFileAsJson(jsonPath)\n : await readFile(jsonPath);\n return JSON.parse(jsonBuffer);\n}\n\nasync function check(domain, db) {\n // is it a single domain or an array of them?\n if (typeof domain === \"string\") {\n return checkInJSON(domain, db);\n } else {\n return checkDomainsInJSON(domain, db);\n }\n}\n\nfunction checkInJSON(domain, db) {\n if (db.indexOf(domain) > -1) {\n return true;\n }\n return false;\n}\n\nfunction greenDomainsFromResults(greenResults) {\n const entries = Object.entries(greenResults);\n const greenEntries = entries.filter(([key, val]) => val.green);\n\n return greenEntries.map(([key, val]) => val.url);\n}\n\nfunction checkDomainsInJSON(domains, db) {\n let greenDomains = [];\n\n for (let domain of domains) {\n if (db.indexOf(domain) > -1) {\n greenDomains.push(domain);\n }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