@hestia-earth/api 0.25.45 → 0.25.47

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.
@@ -1,124 +1,88 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __rest = (this && this.__rest) || function (s, e) {
14
- var t = {};
15
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
- t[p] = s[p];
17
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
- t[p[i]] = s[p[i]];
21
- }
22
- return t;
23
- };
24
- var _a;
25
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
3
  exports.setPrivate = exports.formatForUpload = exports.parseLogMissingLookups = exports.paramToNodeType = exports.nodeTypeToParam = exports.pathWithState = exports.allowedDataStates = exports.dataStatesTypeMapping = exports.DataState = exports.blankNodeTypes = void 0;
27
- var schema_1 = require("@hestia-earth/schema");
28
- var utils_1 = require("@hestia-earth/utils");
29
- var model_1 = require("../../files/model/model");
30
- exports.blankNodeTypes = Object.values(schema_1.SchemaType).filter(function (t) { return !(0, schema_1.isTypeNode)(t); });
4
+ const schema_1 = require("@hestia-earth/schema");
5
+ const utils_1 = require("@hestia-earth/utils");
6
+ const model_1 = require("../../files/model/model");
7
+ exports.blankNodeTypes = Object.values(schema_1.SchemaType).filter(t => !(0, schema_1.isTypeNode)(t));
31
8
  var DataState;
32
9
  (function (DataState) {
33
10
  DataState["original"] = "original";
34
11
  DataState["recalculated"] = "recalculated";
35
- })(DataState = exports.DataState || (exports.DataState = {}));
36
- exports.dataStatesTypeMapping = (_a = {},
37
- _a[DataState.original] = Object.values(schema_1.NodeType),
38
- _a[DataState.recalculated] = [schema_1.NodeType.Cycle, schema_1.NodeType.ImpactAssessment, schema_1.NodeType.Site],
39
- _a);
40
- var allowedDataStates = function (type) {
41
- return Object.values(DataState).filter(function (dataState) { return exports.dataStatesTypeMapping[dataState].includes(type); });
12
+ })(DataState || (exports.DataState = DataState = {}));
13
+ exports.dataStatesTypeMapping = {
14
+ [DataState.original]: Object.values(schema_1.NodeType),
15
+ [DataState.recalculated]: [schema_1.NodeType.Cycle, schema_1.NodeType.ImpactAssessment, schema_1.NodeType.Site]
42
16
  };
17
+ const allowedDataStates = (type) => Object.values(DataState).filter(dataState => exports.dataStatesTypeMapping[dataState].includes(type));
43
18
  exports.allowedDataStates = allowedDataStates;
44
- var pathWithState = function (type, id, dataState, strictDataState) {
45
- if (dataState === void 0) { dataState = DataState.original; }
46
- if (strictDataState === void 0) { strictDataState = false; }
47
- var state = exports.dataStatesTypeMapping[dataState].includes(type) ? dataState : null;
19
+ const pathWithState = (type, id, dataState = DataState.original, strictDataState = false) => {
20
+ const state = exports.dataStatesTypeMapping[dataState].includes(type) ? dataState : null;
48
21
  return state !== null || !strictDataState
49
22
  ? [state === DataState.original ? null : state, (0, schema_1.jsonldPath)(type, id)].filter(Boolean).join('/')
50
23
  : null;
51
24
  };
52
25
  exports.pathWithState = pathWithState;
53
- var nodeTypeToParam = function (type) { return "".concat((type || '').toLowerCase(), "s"); };
26
+ const nodeTypeToParam = (type) => `${(type || '').toLowerCase()}s`;
54
27
  exports.nodeTypeToParam = nodeTypeToParam;
55
- var paramToNodeType = function (type) { return Object.values(schema_1.NodeType).find(function (v) { return (0, exports.nodeTypeToParam)(v) === type; }); };
28
+ const paramToNodeType = (type) => Object.values(schema_1.NodeType).find(v => (0, exports.nodeTypeToParam)(v) === type);
56
29
  exports.paramToNodeType = paramToNodeType;
57
- var csvValue = function (value) { return (value || '').replace('[', '').replace(']', ''); };
58
- var parseMessage = function (message) {
30
+ const csvValue = (value) => (value || '').replace('[', '').replace(']', '');
31
+ const parseMessage = (message) => {
59
32
  try {
60
- var data = JSON.parse(message);
61
- return data.message.split(',').reduce(function (prev, parts) {
62
- var _a;
63
- var _b = parts.split('='), key = _b[0], value = _b[1];
64
- var val = csvValue(value);
65
- return __assign(__assign({}, prev), (key && val ? (_a = {}, _a[key.trim()] = val, _a) : {}));
33
+ const data = JSON.parse(message);
34
+ return data.message.split(',').reduce((prev, parts) => {
35
+ const [key, value] = parts.split('=');
36
+ const val = csvValue(value);
37
+ return {
38
+ ...prev,
39
+ ...(key && val ? { [key.trim()]: val } : {})
40
+ };
66
41
  }, { logger: data.logger });
67
42
  }
68
43
  catch (err) {
69
44
  return {};
70
45
  }
71
46
  };
72
- var termTypes = Object.values(schema_1.TermTermType);
73
- var parseFilename = function (filepath) {
74
- var filename = filepath.split('.')[0];
75
- var ext = termTypes.includes(filename) ? model_1.SupportedExtensions.xlsx : model_1.SupportedExtensions.csv;
47
+ const termTypes = Object.values(schema_1.TermTermType);
48
+ const parseFilename = (filepath) => {
49
+ const [filename] = filepath.split('.');
50
+ const ext = termTypes.includes(filename) ? model_1.SupportedExtensions.xlsx : model_1.SupportedExtensions.csv;
76
51
  return (0, model_1.fileToExt)(filename, ext);
77
52
  };
78
- var missingLookupPrefix = 'Missing lookup';
79
- var parseLookup = function (_a) {
80
- var column = _a.column, termid = _a.termid, _b = missingLookupPrefix, missingLookup = _a[_b];
81
- return ({
82
- filename: parseFilename(missingLookup),
83
- termId: termid,
84
- column: column
85
- });
86
- };
87
- var parseLogMissingLookups = function (data) {
88
- var lines = data.split('\n').filter(function (log) { return log.includes(missingLookupPrefix); });
89
- var messages = lines.map(parseMessage).filter(function (v) { return Object.keys(v).length > 1; });
53
+ const missingLookupPrefix = 'Missing lookup';
54
+ const parseLookup = ({ column, termid, [missingLookupPrefix]: missingLookup }) => ({
55
+ filename: parseFilename(missingLookup),
56
+ termId: termid,
57
+ column
58
+ });
59
+ const parseLogMissingLookups = (data) => {
60
+ const lines = data.split('\n').filter(log => log.includes(missingLookupPrefix));
61
+ const messages = lines.map(parseMessage).filter(v => Object.keys(v).length > 1);
90
62
  return (0, utils_1.unique)(messages.map(parseLookup));
91
63
  };
92
64
  exports.parseLogMissingLookups = parseLogMissingLookups;
93
- var mapTypeToId = function (nodes) {
94
- return nodes.reduce(function (prev, _a) {
95
- var type = _a["@type"], id = _a["@id"];
96
- prev[type] = prev[type] || [];
97
- prev[type].push(id);
98
- return prev;
99
- }, {});
100
- };
101
- var formatForUpload = function (nodes, typeToId) {
102
- if (typeToId === void 0) { typeToId = mapTypeToId(nodes); }
103
- return nodes.map(function (_a) {
104
- var _b;
105
- var type = _a["@type"], id = _a["@id"], node = __rest(_a, ['@type', '@id']);
106
- return type === schema_1.NodeType.Term
107
- ? { '@type': type, '@id': id }
108
- : (0, utils_1.reduceUndefinedValues)(__assign(__assign({}, (!id || ((_b = typeToId[type]) !== null && _b !== void 0 ? _b : []).includes(id) ? { type: type, id: id } : { '@type': type, '@id': id })), Object.fromEntries(Object.entries(node).map(function (_a) {
109
- var key = _a[0], value = _a[1];
110
- var newValue = (0, schema_1.isExpandable)(value)
111
- ? Array.isArray(value)
112
- ? (0, exports.formatForUpload)(value, typeToId)
113
- : (0, exports.formatForUpload)([value], typeToId)[0]
114
- : value;
115
- return [key, newValue];
116
- }))), true);
117
- });
118
- };
65
+ const mapTypeToId = (nodes) => nodes.reduce((prev, { '@type': type, '@id': id }) => {
66
+ prev[type] = prev[type] || [];
67
+ prev[type].push(id);
68
+ return prev;
69
+ }, {});
70
+ const formatForUpload = (nodes, typeToId = mapTypeToId(nodes)) => nodes.map(({ '@type': type, '@id': id, ...node }) => type === schema_1.NodeType.Term
71
+ ? { '@type': type, '@id': id }
72
+ : (0, utils_1.reduceUndefinedValues)({
73
+ ...(!id || (typeToId[type] ?? []).includes(id) ? { type, id } : { '@type': type, '@id': id }),
74
+ ...Object.fromEntries(Object.entries(node).map(([key, value]) => {
75
+ const newValue = (0, schema_1.isExpandable)(value)
76
+ ? Array.isArray(value)
77
+ ? (0, exports.formatForUpload)(value, typeToId)
78
+ : (0, exports.formatForUpload)([value], typeToId)[0]
79
+ : value;
80
+ return [key, newValue];
81
+ }))
82
+ }, true));
119
83
  exports.formatForUpload = formatForUpload;
120
- var setPrivate = function (_a) {
121
- var source = _a.source, defaultSource = _a.defaultSource, node = __rest(_a, ["source", "defaultSource"]);
122
- return (__assign(__assign({}, node), { dataPrivate: true }));
123
- };
84
+ const setPrivate = ({ source, defaultSource, ...node }) => ({
85
+ ...node,
86
+ dataPrivate: true
87
+ });
124
88
  exports.setPrivate = setPrivate;
@@ -1,22 +1,7 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
2
  Object.defineProperty(exports, "__esModule", { value: true });
18
3
  exports.Reconciliation = exports.ReconciliationLevel = exports.reconciliationsValidatePrivate = exports.reconciliationsValidateExpectedNodes = exports.reconciliationsValidateImpactAssessmentLinks = exports.reconciliationsValidateProductCorrespondence = exports.reconciliationsGetMainErrorMessage = void 0;
19
- var model_base_1 = require("../../db/model.base");
4
+ const model_base_1 = require("../../db/model.base");
20
5
  var validations_1 = require("./validations");
21
6
  Object.defineProperty(exports, "reconciliationsGetMainErrorMessage", { enumerable: true, get: function () { return validations_1.getMainErrorMessage; } });
22
7
  Object.defineProperty(exports, "reconciliationsValidateProductCorrespondence", { enumerable: true, get: function () { return validations_1.validateProductCorrespondence; } });
@@ -28,12 +13,16 @@ var ReconciliationLevel;
28
13
  ReconciliationLevel["success"] = "success";
29
14
  ReconciliationLevel["warning"] = "warning";
30
15
  ReconciliationLevel["danger"] = "danger";
31
- })(ReconciliationLevel = exports.ReconciliationLevel || (exports.ReconciliationLevel = {}));
32
- var Reconciliation = (function (_super) {
33
- __extends(Reconciliation, _super);
34
- function Reconciliation() {
35
- return _super !== null && _super.apply(this, arguments) || this;
36
- }
37
- return Reconciliation;
38
- }(model_base_1.BaseModel));
16
+ })(ReconciliationLevel || (exports.ReconciliationLevel = ReconciliationLevel = {}));
17
+ class Reconciliation extends model_base_1.BaseModel {
18
+ idExpected;
19
+ idRecalculated;
20
+ dataPrivate;
21
+ name;
22
+ level;
23
+ details;
24
+ error;
25
+ uploadStatus;
26
+ uploadPipelineStatus;
27
+ }
39
28
  exports.Reconciliation = Reconciliation;
@@ -1,96 +1,70 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.getMainErrorMessage = exports.validateProductCorrespondence = exports.validatePrivate = exports.validateImpactAssessmentLinks = exports.validateExpectedNodes = exports.EXTRANEOUS = exports.notPrivateError = void 0;
15
- var schema_1 = require("@hestia-earth/schema");
4
+ const schema_1 = require("@hestia-earth/schema");
16
5
  exports.notPrivateError = 'expected-not-private';
17
6
  exports.EXTRANEOUS = 'extraneous';
18
- var isExtraneousError = function (error) { var _a; return (_a = (typeof error === 'string' ? error : error === null || error === void 0 ? void 0 : error.message)) === null || _a === void 0 ? void 0 : _a.includes(exports.EXTRANEOUS); };
19
- var isNotPrivateError = function (error) { return (typeof error === 'string' ? error : error === null || error === void 0 ? void 0 : error.message) === exports.notPrivateError; };
20
- var getType = function (node) { return (node === null || node === void 0 ? void 0 : node['@type']) || (node === null || node === void 0 ? void 0 : node.type); };
21
- var getId = function (node) { return (node === null || node === void 0 ? void 0 : node['@id']) || (node === null || node === void 0 ? void 0 : node.id); };
22
- var filterByType = function (nodeType) { return function (node) { return getType(node) === nodeType; }; };
23
- var getErrorsFromValidationsObj = function (validations) {
24
- return Object.entries(validations)
25
- .filter(function (_a) {
26
- var _errorMsg = _a[0], validationFailed = _a[1];
27
- return !!validationFailed;
28
- })
29
- .map(function (_a) {
30
- var errorMsg = _a[0];
31
- return errorMsg;
7
+ const isExtraneousError = (error) => (typeof error === 'string' ? error : error?.message)?.includes(exports.EXTRANEOUS);
8
+ const isNotPrivateError = (error) => (typeof error === 'string' ? error : error?.message) === exports.notPrivateError;
9
+ const getType = (node) => node?.['@type'] || node?.type;
10
+ const getId = (node) => node?.['@id'] || node?.id;
11
+ const filterByType = (nodeType) => (node) => getType(node) === nodeType;
12
+ const getErrorsFromValidationsObj = validations => Object.entries(validations)
13
+ .filter(([_errorMsg, validationFailed]) => !!validationFailed)
14
+ .map(([errorMsg]) => errorMsg);
15
+ const validateExpectedNodes = (nodes) => {
16
+ const cycles = nodes.filter(node => getType(node) === schema_1.NodeType.Cycle);
17
+ const sites = nodes.filter(node => getType(node) === schema_1.NodeType.Site);
18
+ const impactAssessments = nodes.filter(node => getType(node) === schema_1.NodeType.ImpactAssessment);
19
+ const cycleId = getId(cycles?.[0]);
20
+ const cycleSiteId = getId(cycles?.[0]?.site);
21
+ const siteId = getId(sites?.[0]);
22
+ return getErrorsFromValidationsObj({
23
+ ['More than one Cycle found in expected nodes']: cycles.length > 1,
24
+ ['No Cycle found in expected nodes']: cycles.length < 1,
25
+ ['Cycle missing name field in expected nodes']: cycles.length && !cycles[0].name,
26
+ ['More than one Site found in expected nodes']: sites.length > 1,
27
+ [`Cycle ${cycleId} is not linked to Site ${siteId} in expected nodes`]: cycleSiteId !== siteId,
28
+ ...impactAssessments.reduce((acc, ia) => {
29
+ acc[`ImpactAssessment ${getId(ia)} is not linked to Cycle ${cycleId} in expected nodes`] =
30
+ getId(ia?.cycle) !== cycleId;
31
+ return acc;
32
+ }, {})
32
33
  });
33
34
  };
34
- var validateExpectedNodes = function (nodes) {
35
- var _a;
36
- var _b;
37
- var cycles = nodes.filter(function (node) { return getType(node) === schema_1.NodeType.Cycle; });
38
- var sites = nodes.filter(function (node) { return getType(node) === schema_1.NodeType.Site; });
39
- var impactAssessments = nodes.filter(function (node) { return getType(node) === schema_1.NodeType.ImpactAssessment; });
40
- var cycleId = getId(cycles === null || cycles === void 0 ? void 0 : cycles[0]);
41
- var cycleSiteId = getId((_b = cycles === null || cycles === void 0 ? void 0 : cycles[0]) === null || _b === void 0 ? void 0 : _b.site);
42
- var siteId = getId(sites === null || sites === void 0 ? void 0 : sites[0]);
43
- return getErrorsFromValidationsObj(__assign((_a = {}, _a['More than one Cycle found in expected nodes'] = cycles.length > 1, _a['No Cycle found in expected nodes'] = cycles.length < 1, _a['Cycle missing name field in expected nodes'] = cycles.length && !cycles[0].name, _a['More than one Site found in expected nodes'] = sites.length > 1, _a["Cycle ".concat(cycleId, " is not linked to Site ").concat(siteId, " in expected nodes")] = cycleSiteId !== siteId, _a), impactAssessments.reduce(function (acc, ia) {
44
- acc["ImpactAssessment ".concat(getId(ia), " is not linked to Cycle ").concat(cycleId, " in expected nodes")] =
45
- getId(ia === null || ia === void 0 ? void 0 : ia.cycle) !== cycleId;
46
- return acc;
47
- }, {})));
48
- };
49
35
  exports.validateExpectedNodes = validateExpectedNodes;
50
- var matchedProduct = function (impacts) { return function (product) {
51
- return impacts.filter(function (ia) { return getId(product.term) === getId(ia.product.term); }).length > 1;
52
- }; };
53
- var validateImpactAssessmentLinks = function (nodes) {
54
- var _a;
55
- var _b, _c;
56
- var impactAssessments = nodes.filter(filterByType(schema_1.NodeType.ImpactAssessment));
57
- var cycle = nodes.find(filterByType(schema_1.NodeType.Cycle));
58
- var cycleId = getId(cycle);
59
- return getErrorsFromValidationsObj((_a = {},
60
- _a["Cycle ".concat(cycleId, " has no associated impact assessment")] = !impactAssessments.length,
61
- _a["Cycle ".concat(cycleId, " has no products")] = !((_b = cycle.products) === null || _b === void 0 ? void 0 : _b.length),
62
- _a["Cycle ".concat(cycleId, " has a product with more than one linked impact assessment")] = (_c = cycle.products) === null || _c === void 0 ? void 0 : _c.some(matchedProduct(impactAssessments)),
63
- _a));
36
+ const matchedProduct = (impacts) => (product) => impacts.filter(ia => getId(product.term) === getId(ia.product.term)).length > 1;
37
+ const validateImpactAssessmentLinks = (nodes) => {
38
+ const impactAssessments = nodes.filter(filterByType(schema_1.NodeType.ImpactAssessment));
39
+ const cycle = nodes.find(filterByType(schema_1.NodeType.Cycle));
40
+ const cycleId = getId(cycle);
41
+ return getErrorsFromValidationsObj({
42
+ [`Cycle ${cycleId} has no associated impact assessment`]: !impactAssessments.length,
43
+ [`Cycle ${cycleId} has no products`]: !cycle.products?.length,
44
+ [`Cycle ${cycleId} has a product with more than one linked impact assessment`]: cycle.products?.some(matchedProduct(impactAssessments))
45
+ });
64
46
  };
65
47
  exports.validateImpactAssessmentLinks = validateImpactAssessmentLinks;
66
- var validatePrivate = function (cycle) {
67
- var _a;
68
- return getErrorsFromValidationsObj((_a = {}, _a[exports.notPrivateError] = !cycle.dataPrivate, _a));
69
- };
48
+ const validatePrivate = (cycle) => getErrorsFromValidationsObj({ [exports.notPrivateError]: !cycle.dataPrivate });
70
49
  exports.validatePrivate = validatePrivate;
71
- var validateProductCorrespondence = function (expectedProducts, recalculatedProducts, idRecalculated) {
72
- var missingProducts = expectedProducts.filter(function (pExpected) { return !recalculatedProducts.some(function (pRecalculated) { return getId(pRecalculated) === getId(pExpected); }); });
73
- var extraneousProducts = recalculatedProducts.filter(function (pRecalculated) { return !expectedProducts.some(function (pExpected) { return getId(pRecalculated) === getId(pExpected); }); });
50
+ const validateProductCorrespondence = (expectedProducts, recalculatedProducts, idRecalculated) => {
51
+ const missingProducts = expectedProducts.filter(pExpected => !recalculatedProducts.some(pRecalculated => getId(pRecalculated) === getId(pExpected)));
52
+ const extraneousProducts = recalculatedProducts.filter(pRecalculated => !expectedProducts.some(pExpected => getId(pRecalculated) === getId(pExpected)));
74
53
  return [
75
54
  [missingProducts, 'missing'],
76
55
  [extraneousProducts, exports.EXTRANEOUS]
77
56
  ]
78
- .map(function (_a) {
79
- var products = _a[0], errorType = _a[1];
80
- return products.length
81
- ? "Cycle ".concat(idRecalculated, " has ").concat(errorType, " impact assessment for products: ").concat(products
82
- .map(function (p) { return p['@id']; })
83
- .join(', '))
84
- : null;
85
- })
57
+ .map(([products, errorType]) => products.length
58
+ ? `Cycle ${idRecalculated} has ${errorType} impact assessment for products: ${products
59
+ .map(p => p['@id'])
60
+ .join(', ')}`
61
+ : null)
86
62
  .filter(Boolean);
87
63
  };
88
64
  exports.validateProductCorrespondence = validateProductCorrespondence;
89
- var getMainErrorMessage = function (errors) {
90
- return (errors === null || errors === void 0 ? void 0 : errors.length) === 1 && isExtraneousError(errors[0])
91
- ? 'recalculation-error'
92
- : errors.some(isNotPrivateError)
93
- ? exports.notPrivateError
94
- : 'invalid-nodes';
95
- };
65
+ const getMainErrorMessage = errors => errors?.length === 1 && isExtraneousError(errors[0])
66
+ ? 'recalculation-error'
67
+ : errors.some(isNotPrivateError)
68
+ ? exports.notPrivateError
69
+ : 'invalid-nodes';
96
70
  exports.getMainErrorMessage = getMainErrorMessage;
@@ -1,22 +1,7 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
2
  Object.defineProperty(exports, "__esModule", { value: true });
18
3
  exports.Setting = exports.SettingKey = exports.cacheKey = void 0;
19
- var model_base_1 = require("../../db/model.base");
4
+ const model_base_1 = require("../../db/model.base");
20
5
  exports.cacheKey = 'settings';
21
6
  var SettingKey;
22
7
  (function (SettingKey) {
@@ -28,12 +13,10 @@ var SettingKey;
28
13
  SettingKey["calculationEngine"] = "calculationEngine";
29
14
  SettingKey["users"] = "users";
30
15
  SettingKey["dataReleases"] = "dataReleases";
31
- })(SettingKey = exports.SettingKey || (exports.SettingKey = {}));
32
- var Setting = (function (_super) {
33
- __extends(Setting, _super);
34
- function Setting() {
35
- return _super !== null && _super.apply(this, arguments) || this;
36
- }
37
- return Setting;
38
- }(model_base_1.BaseModel));
16
+ })(SettingKey || (exports.SettingKey = SettingKey = {}));
17
+ class Setting extends model_base_1.BaseModel {
18
+ key;
19
+ value;
20
+ metadata;
21
+ }
39
22
  exports.Setting = Setting;
@@ -59,10 +59,10 @@ export declare class User extends BaseModel {
59
59
  readonly actorId?: string;
60
60
  }
61
61
  export declare const name: ({ firstName, lastName }: Partial<User>) => string;
62
- export declare const isAdmin: (user?: Pick<User, 'role'>) => boolean;
63
- export declare const isReviewer: (user?: Pick<User, 'role'>) => boolean;
64
- export declare const isDeveloper: (user?: Pick<User, 'role'>) => boolean;
65
- export declare const hasPermission: (permission: UserPermission, user?: Pick<User, 'role' | 'permissions'>) => boolean;
62
+ export declare const isAdmin: (user?: Pick<User, "role">) => boolean;
63
+ export declare const isReviewer: (user?: Pick<User, "role">) => boolean;
64
+ export declare const isDeveloper: (user?: Pick<User, "role">) => boolean;
65
+ export declare const hasPermission: (permission: UserPermission, user?: Pick<User, "role" | "permissions">) => boolean;
66
66
  export declare const contains: (users: Partial<User>[], user: Partial<User>) => boolean;
67
67
  export declare const actorId: (user: Partial<User>) => string;
68
68
  export declare const userToActor: (user: Partial<User>, domain?: string) => Partial<IActorJSONLD>;
@@ -1,47 +1,21 @@
1
1
  "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- var __assign = (this && this.__assign) || function () {
18
- __assign = Object.assign || function(t) {
19
- for (var s, i = 1, n = arguments.length; i < n; i++) {
20
- s = arguments[i];
21
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
22
- t[p] = s[p];
23
- }
24
- return t;
25
- };
26
- return __assign.apply(this, arguments);
27
- };
28
2
  Object.defineProperty(exports, "__esModule", { value: true });
29
3
  exports.userToActor = exports.actorId = exports.contains = exports.hasPermission = exports.isDeveloper = exports.isReviewer = exports.isAdmin = exports.name = exports.User = exports.UserPermission = exports.UserRole = exports.MaxUploads = exports.defaultMaxApiCalls = void 0;
30
- var schema_1 = require("@hestia-earth/schema");
31
- var model_base_1 = require("../../db/model.base");
4
+ const schema_1 = require("@hestia-earth/schema");
5
+ const model_base_1 = require("../../db/model.base");
32
6
  exports.defaultMaxApiCalls = 100;
33
7
  var MaxUploads;
34
8
  (function (MaxUploads) {
35
9
  MaxUploads[MaxUploads["New"] = 1] = "New";
36
10
  MaxUploads[MaxUploads["Confirmed"] = 10] = "Confirmed";
37
- })(MaxUploads = exports.MaxUploads || (exports.MaxUploads = {}));
11
+ })(MaxUploads || (exports.MaxUploads = MaxUploads = {}));
38
12
  var UserRole;
39
13
  (function (UserRole) {
40
14
  UserRole["Researcher"] = "default";
41
15
  UserRole["Developer"] = "developer";
42
16
  UserRole["Reviewer"] = "reviewer";
43
17
  UserRole["Admin"] = "admin";
44
- })(UserRole = exports.UserRole || (exports.UserRole = {}));
18
+ })(UserRole || (exports.UserRole = UserRole = {}));
45
19
  var UserPermission;
46
20
  (function (UserPermission) {
47
21
  UserPermission["aggregationsCreate"] = "aggregations-create";
@@ -53,59 +27,79 @@ var UserPermission;
53
27
  UserPermission["reconciliationsRead"] = "reconciliations-view";
54
28
  UserPermission["reconciliationsUpdate"] = "reconciliations-update";
55
29
  UserPermission["reconciliationsDelete"] = "reconciliations-delete";
56
- })(UserPermission = exports.UserPermission || (exports.UserPermission = {}));
57
- var User = (function (_super) {
58
- __extends(User, _super);
59
- function User() {
60
- var _this = _super !== null && _super.apply(this, arguments) || this;
61
- _this.role = UserRole.Researcher;
62
- _this.maxUploads = MaxUploads.New;
63
- _this.maxApiCalls = exports.defaultMaxApiCalls;
64
- _this.dataPrivate = false;
65
- _this.validFilesCount = 0;
66
- _this.canCommitHestiaData = false;
67
- _this.permissions = [];
68
- _this.emailNotificationsSuccess = false;
69
- _this.emailNotificationsFailure = false;
70
- _this.emailNotificationsFeedback = false;
71
- _this.autoSubmitPrivateSubmissions = false;
72
- _this.metadata = {};
73
- return _this;
74
- }
75
- return User;
76
- }(model_base_1.BaseModel));
30
+ })(UserPermission || (exports.UserPermission = UserPermission = {}));
31
+ class User extends model_base_1.BaseModel {
32
+ email;
33
+ firstName;
34
+ lastName;
35
+ displayName;
36
+ password;
37
+ token;
38
+ role = UserRole.Researcher;
39
+ maxUploads = MaxUploads.New;
40
+ maxApiCalls = exports.defaultMaxApiCalls;
41
+ dataPrivate = false;
42
+ validFilesCount = 0;
43
+ canCommitHestiaData = false;
44
+ permissions = [];
45
+ emailNotificationsSuccess = false;
46
+ emailNotificationsFailure = false;
47
+ emailNotificationsFeedback = false;
48
+ autoSubmitPrivateSubmissions = false;
49
+ confirmToken;
50
+ confirmedAt;
51
+ lastActiveAt;
52
+ scopusID;
53
+ googleID;
54
+ linkedInID;
55
+ gitlabID;
56
+ gitlabUsername;
57
+ orcid;
58
+ website;
59
+ city;
60
+ country;
61
+ primaryInstitution;
62
+ metadata = {};
63
+ admin;
64
+ name;
65
+ actorId;
66
+ }
77
67
  exports.User = User;
78
- var name = function (_a) {
79
- var firstName = _a.firstName, lastName = _a.lastName;
80
- return [firstName, lastName].filter(Boolean).join(' ');
81
- };
68
+ const name = ({ firstName, lastName }) => [firstName, lastName].filter(Boolean).join(' ');
82
69
  exports.name = name;
83
- var isAdmin = function (user) { return (user === null || user === void 0 ? void 0 : user.role) === UserRole.Admin; };
70
+ const isAdmin = (user) => user?.role === UserRole.Admin;
84
71
  exports.isAdmin = isAdmin;
85
- var isReviewer = function (user) { return [UserRole.Reviewer, UserRole.Admin].includes(user === null || user === void 0 ? void 0 : user.role); };
72
+ const isReviewer = (user) => [UserRole.Reviewer, UserRole.Admin].includes(user?.role);
86
73
  exports.isReviewer = isReviewer;
87
- var isDeveloper = function (user) {
88
- return [UserRole.Developer, UserRole.Reviewer, UserRole.Admin].includes(user === null || user === void 0 ? void 0 : user.role);
89
- };
74
+ const isDeveloper = (user) => [UserRole.Developer, UserRole.Reviewer, UserRole.Admin].includes(user?.role);
90
75
  exports.isDeveloper = isDeveloper;
91
- var hasPermission = function (permission, user) { var _a; return (0, exports.isAdmin)(user) || ((_a = user === null || user === void 0 ? void 0 : user.permissions) !== null && _a !== void 0 ? _a : []).includes(permission); };
76
+ const hasPermission = (permission, user) => (0, exports.isAdmin)(user) || (user?.permissions ?? []).includes(permission);
92
77
  exports.hasPermission = hasPermission;
93
- var contains = function (users, user) { return users.some(function (u) { return u.email === user.email; }); };
78
+ const contains = (users, user) => users.some(u => u.email === user.email);
94
79
  exports.contains = contains;
95
- var actorId = function (user) { return "".concat((user._id || user.id).toString()); };
80
+ const actorId = (user) => `${(user._id || user.id).toString()}`;
96
81
  exports.actorId = actorId;
97
- var jsonLDContext = function (type, domain) { return "".concat(domain, "/schema/").concat(type, ".jsonld"); };
98
- var addIfDefined = function (key, value) {
99
- var _a;
100
- return (!!value ? (_a = {}, _a[key] = value, _a) : {});
101
- };
102
- var profileData = function (user) {
103
- return user.dataPrivate
104
- ? {}
105
- : __assign(__assign(__assign(__assign(__assign(__assign({ email: user.email, firstName: user.firstName, lastName: user.lastName, name: user.displayName || (0, exports.name)(user) }, addIfDefined('scopusID', user.scopusID)), addIfDefined('orcid', user.orcid)), addIfDefined('primaryInstitution', user.primaryInstitution)), addIfDefined('city', user.city)), addIfDefined('country', user.country ? { type: schema_1.NodeType.Term, name: user.country } : undefined)), addIfDefined('website', user.website ? { '@id': user.website } : undefined));
106
- };
107
- var userToActor = function (user, domain) {
108
- if (domain === void 0) { domain = 'https://hestia.earth'; }
109
- return (__assign({ '@context': jsonLDContext(schema_1.NodeType.Actor, domain), '@type': schema_1.NodeType.Actor, '@id': (0, exports.actorId)(user), dataPrivate: false }, profileData(user)));
110
- };
82
+ const jsonLDContext = (type, domain) => `${domain}/schema/${type}.jsonld`;
83
+ const addIfDefined = (key, value) => (!!value ? { [key]: value } : {});
84
+ const profileData = (user) => user.dataPrivate
85
+ ? {}
86
+ : {
87
+ email: user.email,
88
+ firstName: user.firstName,
89
+ lastName: user.lastName,
90
+ name: user.displayName || (0, exports.name)(user),
91
+ ...addIfDefined('scopusID', user.scopusID),
92
+ ...addIfDefined('orcid', user.orcid),
93
+ ...addIfDefined('primaryInstitution', user.primaryInstitution),
94
+ ...addIfDefined('city', user.city),
95
+ ...addIfDefined('country', user.country ? { type: schema_1.NodeType.Term, name: user.country } : undefined),
96
+ ...addIfDefined('website', user.website ? { '@id': user.website } : undefined)
97
+ };
98
+ const userToActor = (user, domain = 'https://hestia.earth') => ({
99
+ '@context': jsonLDContext(schema_1.NodeType.Actor, domain),
100
+ '@type': schema_1.NodeType.Actor,
101
+ '@id': (0, exports.actorId)(user),
102
+ dataPrivate: false,
103
+ ...profileData(user)
104
+ });
111
105
  exports.userToActor = userToActor;