@hestia-earth/schema-convert 30.0.1 → 30.2.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.
@@ -2,9 +2,10 @@
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  var convert_csv_1 = require("../convert-csv");
5
+ var now = new Date().getTime();
5
6
  (0, convert_csv_1.run)(true)
6
7
  .then(function (paths) {
7
- console.log('Done converting', paths.length, 'files.');
8
+ console.log('Done converting', paths.length, 'files in', (new Date().getTime() - now) / 1000, 's');
8
9
  console.log(paths.join('\n'));
9
10
  process.exit(0);
10
11
  })
@@ -2,9 +2,10 @@
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  var convert_csv_1 = require("../convert-csv");
5
+ var now = new Date().getTime();
5
6
  (0, convert_csv_1.run)()
6
7
  .then(function (paths) {
7
- console.log('Done converting', paths.length, 'files.');
8
+ console.log('Done converting', paths.length, 'files in', (new Date().getTime() - now) / 1000, 's');
8
9
  console.log(paths.join('\n'));
9
10
  process.exit(0);
10
11
  })
@@ -2,9 +2,10 @@
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  var convert_json_1 = require("../convert-json");
5
+ var now = new Date().getTime();
5
6
  (0, convert_json_1.run)()
6
7
  .then(function (paths) {
7
- console.log('Done converting', paths.length, 'files.');
8
+ console.log('Done converting', paths.length, 'files in', (new Date().getTime() - now) / 1000, 's');
8
9
  console.log(paths.join('\n'));
9
10
  process.exit(0);
10
11
  })
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ var pivot_file_1 = require("../pivot-file");
5
+ var now = new Date().getTime();
6
+ (0, pivot_file_1.run)()
7
+ .then(function (paths) {
8
+ console.log('Done pivoting', paths.length, 'files in', (new Date().getTime() - now) / 1000, 's');
9
+ console.log(paths.join('\n'));
10
+ process.exit(0);
11
+ })
12
+ .catch(function (err) {
13
+ console.log('Error pivoting files.');
14
+ console.error(err);
15
+ process.exit(1);
16
+ });
package/convert-csv.js CHANGED
@@ -54,24 +54,14 @@ var __read = (this && this.__read) || function (o, n) {
54
54
  Object.defineProperty(exports, "__esModule", { value: true });
55
55
  exports.run = void 0;
56
56
  var fs_1 = require("fs");
57
- var path_1 = require("path");
57
+ var json_schema_1 = require("@hestia-earth/json-schema");
58
+ var file_utils_1 = require("./file-utils");
58
59
  var csv_pivot_1 = require("./csv-pivot");
59
60
  var csv_1 = require("./csv");
60
61
  var _a = __read(process.argv.slice(2), 1), path = _a[0];
61
- var readdir = fs_1.promises.readdir, readFile = fs_1.promises.readFile, writeFile = fs_1.promises.writeFile, lstat = fs_1.promises.lstat;
62
+ var readFile = fs_1.promises.readFile, writeFile = fs_1.promises.writeFile;
62
63
  var encoding = 'utf8';
63
- var listFiles = function (folder) { return __awaiter(void 0, void 0, void 0, function () {
64
- var files;
65
- return __generator(this, function (_a) {
66
- switch (_a.label) {
67
- case 0: return [4 /*yield*/, readdir(folder)];
68
- case 1:
69
- files = _a.sent();
70
- return [2 /*return*/, files.filter(function (file) { return file.endsWith('.jsonld') || file.endsWith('.json'); })];
71
- }
72
- });
73
- }); };
74
- var processFile = function (filepath, pivot) { return __awaiter(void 0, void 0, void 0, function () {
64
+ var processFile = function (schemas, filepath, pivot) { return __awaiter(void 0, void 0, void 0, function () {
75
65
  var data, content, nodes, res, destPath;
76
66
  return __generator(this, function (_a) {
77
67
  switch (_a.label) {
@@ -80,7 +70,7 @@ var processFile = function (filepath, pivot) { return __awaiter(void 0, void 0,
80
70
  data = _a.sent();
81
71
  content = JSON.parse(data.trim());
82
72
  nodes = Array.isArray(content) ? content : 'nodes' in content ? content.nodes : [content];
83
- res = pivot ? (0, csv_pivot_1.toCsvPivot)(nodes) : (0, csv_1.toCsv)(nodes);
73
+ res = pivot ? (0, csv_pivot_1.toCsvPivot)(schemas, nodes) : (0, csv_1.toCsv)(nodes);
84
74
  destPath = filepath.replace('.jsonld', '.csv').replace('.json', '.csv');
85
75
  return [4 /*yield*/, writeFile(destPath, res, encoding)];
86
76
  case 2:
@@ -92,22 +82,15 @@ var processFile = function (filepath, pivot) { return __awaiter(void 0, void 0,
92
82
  var run = function (pivot) {
93
83
  if (pivot === void 0) { pivot = false; }
94
84
  return __awaiter(void 0, void 0, void 0, function () {
95
- var stat, _a, _b, _c;
96
- return __generator(this, function (_d) {
97
- switch (_d.label) {
98
- case 0: return [4 /*yield*/, lstat(path)];
85
+ var schemas, files;
86
+ return __generator(this, function (_a) {
87
+ switch (_a.label) {
88
+ case 0:
89
+ schemas = (0, json_schema_1.loadSchemas)();
90
+ return [4 /*yield*/, (0, file_utils_1.listFiles)(path, '.jsonld', '.json')];
99
91
  case 1:
100
- stat = _d.sent();
101
- _b = (_a = Promise).all;
102
- if (!stat.isDirectory()) return [3 /*break*/, 3];
103
- return [4 /*yield*/, listFiles(path)];
104
- case 2:
105
- _c = (_d.sent()).map(function (file) { return processFile((0, path_1.join)(path, file), pivot); });
106
- return [3 /*break*/, 4];
107
- case 3:
108
- _c = [processFile(path, pivot)];
109
- _d.label = 4;
110
- case 4: return [2 /*return*/, _b.apply(_a, [_c])];
92
+ files = _a.sent();
93
+ return [2 /*return*/, Promise.all(files.map(function (file) { return processFile(schemas, file, pivot); }))];
111
94
  }
112
95
  });
113
96
  });
package/convert-json.js CHANGED
@@ -54,23 +54,13 @@ var __read = (this && this.__read) || function (o, n) {
54
54
  Object.defineProperty(exports, "__esModule", { value: true });
55
55
  exports.run = void 0;
56
56
  var fs_1 = require("fs");
57
- var path_1 = require("path");
58
57
  var json_schema_1 = require("@hestia-earth/json-schema");
58
+ var file_utils_1 = require("./file-utils");
59
59
  var json_1 = require("./json");
60
60
  var _a = __read(process.argv.slice(2), 1), path = _a[0];
61
- var readdir = fs_1.promises.readdir, readFile = fs_1.promises.readFile, writeFile = fs_1.promises.writeFile, lstat = fs_1.promises.lstat;
61
+ var readFile = fs_1.promises.readFile, writeFile = fs_1.promises.writeFile;
62
62
  var encoding = 'utf8';
63
- var listFiles = function (folder) { return __awaiter(void 0, void 0, void 0, function () {
64
- var files;
65
- return __generator(this, function (_a) {
66
- switch (_a.label) {
67
- case 0: return [4 /*yield*/, readdir(folder)];
68
- case 1:
69
- files = _a.sent();
70
- return [2 /*return*/, files.filter(function (file) { return file.endsWith('.csv'); })];
71
- }
72
- });
73
- }); };
63
+ var ext = '.csv';
74
64
  var processFile = function (schemas, filepath) { return __awaiter(void 0, void 0, void 0, function () {
75
65
  var content, nodes, destPath;
76
66
  return __generator(this, function (_a) {
@@ -81,7 +71,7 @@ var processFile = function (schemas, filepath) { return __awaiter(void 0, void 0
81
71
  return [4 /*yield*/, (0, json_1.toJson)(schemas, content)];
82
72
  case 2:
83
73
  nodes = _a.sent();
84
- destPath = filepath.replace('.csv', '.json');
74
+ destPath = filepath.replace(ext, '.json');
85
75
  return [4 /*yield*/, writeFile(destPath, JSON.stringify({ nodes: nodes }, null, 2), encoding)];
86
76
  case 3:
87
77
  _a.sent();
@@ -90,23 +80,15 @@ var processFile = function (schemas, filepath) { return __awaiter(void 0, void 0
90
80
  });
91
81
  }); };
92
82
  var run = function () { return __awaiter(void 0, void 0, void 0, function () {
93
- var stat, schemas, _a, _b, _c;
94
- return __generator(this, function (_d) {
95
- switch (_d.label) {
96
- case 0: return [4 /*yield*/, lstat(path)];
97
- case 1:
98
- stat = _d.sent();
83
+ var schemas, files;
84
+ return __generator(this, function (_a) {
85
+ switch (_a.label) {
86
+ case 0:
99
87
  schemas = (0, json_schema_1.loadSchemas)();
100
- _b = (_a = Promise).all;
101
- if (!stat.isDirectory()) return [3 /*break*/, 3];
102
- return [4 /*yield*/, listFiles(path)];
103
- case 2:
104
- _c = (_d.sent()).map(function (file) { return processFile(schemas, (0, path_1.join)(path, file)); });
105
- return [3 /*break*/, 4];
106
- case 3:
107
- _c = [processFile(schemas, path)];
108
- _d.label = 4;
109
- case 4: return [2 /*return*/, _b.apply(_a, [_c])];
88
+ return [4 /*yield*/, (0, file_utils_1.listFiles)(path, ext)];
89
+ case 1:
90
+ files = _a.sent();
91
+ return [2 /*return*/, Promise.all(files.map(function (file) { return processFile(schemas, file); }))];
110
92
  }
111
93
  });
112
94
  }); };
package/csv-pivot.d.ts CHANGED
@@ -1,9 +1,9 @@
1
+ import { definitions } from '@hestia-earth/json-schema/types';
1
2
  export declare const toCsv: (nodes: any[], keys?: string[], excludeKeys?: string[]) => string;
2
- export declare const pivotNode: (node: any) => Partial<any>;
3
3
  /**
4
4
  * CSV format for data processing.
5
5
  *
6
6
  * @param nodes List of nodes to convert.
7
7
  * @returns CSV content formatted with pivoted blank nodes.
8
8
  */
9
- export declare const toCsvPivot: (nodes: any[]) => string;
9
+ export declare const toCsvPivot: (schemas: definitions, nodes: any[]) => string;
package/csv-pivot.js CHANGED
@@ -1,63 +1,22 @@
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 __read = (this && this.__read) || function (o, n) {
14
- var m = typeof Symbol === "function" && o[Symbol.iterator];
15
- if (!m) return o;
16
- var i = m.call(o), r, ar = [], e;
17
- try {
18
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
19
- }
20
- catch (error) { e = { error: error }; }
21
- finally {
22
- try {
23
- if (r && !r.done && (m = i["return"])) m.call(i);
24
- }
25
- finally { if (e) throw e.error; }
26
- }
27
- return ar;
28
- };
29
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
30
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
31
- if (ar || !(i in from)) {
32
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
33
- ar[i] = from[i];
34
- }
35
- }
36
- return to.concat(ar || Array.prototype.slice.call(from));
37
- };
38
2
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.toCsvPivot = exports.pivotNode = exports.toCsv = void 0;
3
+ exports.toCsvPivot = exports.toCsv = void 0;
40
4
  var json_2_csv_1 = require("json-2-csv");
41
5
  var utils_1 = require("./utils");
42
- var omitKeys = __spreadArray([
43
- '@context',
44
- 'schemaVersion',
45
- 'dataPrivate'
46
- ], __read(['bibliography', 'site', 'cycle', 'impactAssessment', 'defaultSource', 'source'].flatMap(function (k) { return [
47
- "".concat(k, ".id"),
48
- "".concat(k, ".type"),
49
- "".concat(k, ".@type")
50
- ]; })), false);
51
- var convertValue = function (value) {
52
- return Array.isArray(value) ? value.map(String).join(';') : typeof value === 'object' ? JSON.stringify(value) : value;
53
- };
6
+ var json_pivot_1 = require("./json-pivot");
54
7
  var parseValue = function (value) {
55
- var result = convertValue(value);
8
+ var result = (0, utils_1.convertValue)(value);
56
9
  return typeof result === undefined || result === null ? '' : result.toString();
57
10
  };
11
+ var withType = function (nodes) {
12
+ return nodes.map(function (node) {
13
+ var _a;
14
+ return (_a = {}, _a["".concat(node['@type'][0].toLowerCase()).concat(node['@type'].substring(1))] = node, _a);
15
+ });
16
+ };
58
17
  var toCsv = function (nodes, keys, excludeKeys) {
59
- if (excludeKeys === void 0) { excludeKeys = omitKeys; }
60
- return (0, json_2_csv_1.json2csv)(nodes, {
18
+ if (excludeKeys === void 0) { excludeKeys = utils_1.omitKeys; }
19
+ return (0, json_2_csv_1.json2csv)(withType(nodes), {
61
20
  keys: keys,
62
21
  excludeKeys: excludeKeys,
63
22
  emptyFieldValue: '-',
@@ -68,39 +27,11 @@ var toCsv = function (nodes, keys, excludeKeys) {
68
27
  });
69
28
  };
70
29
  exports.toCsv = toCsv;
71
- var arrayKeys = function (node) {
72
- return Object.keys(node).filter(function (key) {
73
- return Array.isArray(node[key]) &&
74
- node[key].length &&
75
- typeof node[key][0] === 'object' &&
76
- ('type' in node[key][0] || '@type' in node[key][0]);
77
- });
78
- };
79
- var termId = function (term) { return (term ? term['@id'] || term.id : undefined); };
80
- var convertTerm = function (term) { return (term ? { methodModel: termId(term) } : {}); };
81
- var pivotList = function (values) {
82
- return values.reduce(function (prev, _a) {
83
- var _b;
84
- var _t = _a["@type"], term = _a.term, methodModel = _a.methodModel, value = _a.value;
85
- var key = termId(term);
86
- var data = (0, utils_1.reduceUndefinedValues)(__assign(__assign({}, convertTerm(methodModel)), { value: convertValue(value) }));
87
- return __assign(__assign({}, prev), (key && Object.keys(data).length ? (_b = {}, _b[key] = (prev[key] || []).concat([data]), _b) : {}));
88
- }, {});
89
- };
90
- var pivotNode = function (node) {
91
- var keys = arrayKeys(node);
92
- return (0, utils_1.reduceUndefinedValues)(__assign(__assign({}, (0, utils_1.omit)(node, __spreadArray(__spreadArray([], __read(omitKeys), false), __read(keys), false))), keys.reduce(function (prev, key) {
93
- var _a;
94
- var value = pivotList(node[key]);
95
- return __assign(__assign({}, prev), (Object.keys(value).length ? (_a = {}, _a[key] = value, _a) : {}));
96
- }, {})));
97
- };
98
- exports.pivotNode = pivotNode;
99
30
  /**
100
31
  * CSV format for data processing.
101
32
  *
102
33
  * @param nodes List of nodes to convert.
103
34
  * @returns CSV content formatted with pivoted blank nodes.
104
35
  */
105
- var toCsvPivot = function (nodes) { return (0, exports.toCsv)(nodes.map(exports.pivotNode)); };
36
+ var toCsvPivot = function (schemas, nodes) { return (0, exports.toCsv)(nodes.map(function (node) { return (0, json_pivot_1.pivotNode)(schemas, node); })); };
106
37
  exports.toCsvPivot = toCsvPivot;
@@ -0,0 +1 @@
1
+ export declare const listFiles: (path: string, ...extensions: string[]) => Promise<string[]>;
package/file-utils.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __read = (this && this.__read) || function (o, n) {
39
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
40
+ if (!m) return o;
41
+ var i = m.call(o), r, ar = [], e;
42
+ try {
43
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
44
+ }
45
+ catch (error) { e = { error: error }; }
46
+ finally {
47
+ try {
48
+ if (r && !r.done && (m = i["return"])) m.call(i);
49
+ }
50
+ finally { if (e) throw e.error; }
51
+ }
52
+ return ar;
53
+ };
54
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
55
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
56
+ if (ar || !(i in from)) {
57
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
58
+ ar[i] = from[i];
59
+ }
60
+ }
61
+ return to.concat(ar || Array.prototype.slice.call(from));
62
+ };
63
+ Object.defineProperty(exports, "__esModule", { value: true });
64
+ exports.listFiles = void 0;
65
+ var fs_1 = require("fs");
66
+ var path_1 = require("path");
67
+ var lstat = fs_1.promises.lstat, readdir = fs_1.promises.readdir;
68
+ var listFiles = function (path) {
69
+ var extensions = [];
70
+ for (var _i = 1; _i < arguments.length; _i++) {
71
+ extensions[_i - 1] = arguments[_i];
72
+ }
73
+ return __awaiter(void 0, void 0, void 0, function () {
74
+ var stat, files, _a, _b, _c;
75
+ return __generator(this, function (_d) {
76
+ switch (_d.label) {
77
+ case 0: return [4 /*yield*/, lstat(path)];
78
+ case 1:
79
+ stat = _d.sent();
80
+ _b = (_a = Promise).all;
81
+ if (!stat.isDirectory()) return [3 /*break*/, 3];
82
+ return [4 /*yield*/, readdir(path)];
83
+ case 2:
84
+ _c = (_d.sent()).map(function (file) { return exports.listFiles.apply(void 0, __spreadArray([(0, path_1.join)(path, file)], __read(extensions), false)); });
85
+ return [3 /*break*/, 4];
86
+ case 3:
87
+ _c = [path];
88
+ _d.label = 4;
89
+ case 4: return [4 /*yield*/, _b.apply(_a, [_c])];
90
+ case 5:
91
+ files = (_d.sent()).flat();
92
+ return [2 /*return*/, files.filter(function (file) { return extensions.includes((0, path_1.extname)(file)); })];
93
+ }
94
+ });
95
+ });
96
+ };
97
+ exports.listFiles = listFiles;
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { toCsvPivot } from './csv-pivot';
2
+ export { pivotNode, pivotNodes } from './json-pivot';
2
3
  export * from './csv';
3
4
  export * from './json';
package/index.js CHANGED
@@ -14,8 +14,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.toCsvPivot = void 0;
17
+ exports.pivotNodes = exports.pivotNode = exports.toCsvPivot = void 0;
18
18
  var csv_pivot_1 = require("./csv-pivot");
19
19
  Object.defineProperty(exports, "toCsvPivot", { enumerable: true, get: function () { return csv_pivot_1.toCsvPivot; } });
20
+ var json_pivot_1 = require("./json-pivot");
21
+ Object.defineProperty(exports, "pivotNode", { enumerable: true, get: function () { return json_pivot_1.pivotNode; } });
22
+ Object.defineProperty(exports, "pivotNodes", { enumerable: true, get: function () { return json_pivot_1.pivotNodes; } });
20
23
  __exportStar(require("./csv"), exports);
21
24
  __exportStar(require("./json"), exports);
@@ -0,0 +1,17 @@
1
+ import { SchemaType, NodeType } from '@hestia-earth/schema';
2
+ import { definitions } from '@hestia-earth/json-schema/types';
3
+ export interface INode {
4
+ type?: SchemaType;
5
+ '@type'?: NodeType;
6
+ [key: string]: any;
7
+ }
8
+ /**
9
+ * Pivot node and return in compacted format.
10
+ *
11
+ * @param schemas The definitions of the HESTIA Schema (`import { loadSchemas } from "@hestia-earth/json-schema"`)
12
+ * @param node The node to pivot.
13
+ * @param keepType To keep the `@type`/`type` key in the pivoted format.
14
+ * @returns
15
+ */
16
+ export declare const pivotNode: (schemas: definitions, { "@type": _type, type, ...node }: INode, keepType?: boolean) => INode;
17
+ export declare const pivotNodes: (schemas: definitions, nodes: any[]) => INode[];
package/json-pivot.js ADDED
@@ -0,0 +1,222 @@
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 __read = (this && this.__read) || function (o, n) {
25
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
26
+ if (!m) return o;
27
+ var i = m.call(o), r, ar = [], e;
28
+ try {
29
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
30
+ }
31
+ catch (error) { e = { error: error }; }
32
+ finally {
33
+ try {
34
+ if (r && !r.done && (m = i["return"])) m.call(i);
35
+ }
36
+ finally { if (e) throw e.error; }
37
+ }
38
+ return ar;
39
+ };
40
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
41
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
42
+ if (ar || !(i in from)) {
43
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
44
+ ar[i] = from[i];
45
+ }
46
+ }
47
+ return to.concat(ar || Array.prototype.slice.call(from));
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.pivotNodes = exports.pivotNode = void 0;
51
+ var schema_1 = require("@hestia-earth/schema");
52
+ var schema_utils_1 = require("@hestia-earth/json-schema/schema-utils");
53
+ var get = require('lodash.get');
54
+ var utils_1 = require("./utils");
55
+ var ignoreKeys = __spreadArray([
56
+ '@context',
57
+ '@type',
58
+ 'type',
59
+ 'added',
60
+ 'addedVersion',
61
+ 'updated',
62
+ 'updatedVersion',
63
+ '_cache',
64
+ // ignore all term keys as only the `@id` is included in the key
65
+ 'term'
66
+ ], __read(schema_1.termFields.map(function (v) { return "term.".concat(v); })), false);
67
+ var headerJoin = '+';
68
+ var headerParentKey = function (key) { return key.split(headerJoin)[0]; };
69
+ var uniqueData = function (value, key) {
70
+ // in some cases, we are getting a list using "inputs.@id", but `get` will not be able to access this
71
+ var parentData = key.includes('.') ? get(value, (0, utils_1.parentKey)(key), undefined) : undefined;
72
+ return Array.isArray(parentData) ? parentData.map(function (d) { return uniqueData(d, (0, utils_1.childkey)(key)); }) : get(value, key, undefined);
73
+ };
74
+ var valueAsString = function (value) {
75
+ return (Array.isArray(value) ? value : [value]).map(function (v) { return "".concat(v); }).join(';');
76
+ };
77
+ var valueAsKey = function (value) { return ([value.match(/[\s\"\'\.;]/g)].some(Boolean) ? "[".concat(value, "]") : value); };
78
+ var pivotValue = function (schemas, nodeType, key, value) {
79
+ var _a;
80
+ var _b, _c;
81
+ // nodeType = Cycle
82
+ // key = emissions
83
+ // value = {'term':{'@id':'gwp100}, 'dates':['2021','2022'], 'value':[10,12]}
84
+ var uniqueFields = (_c = (_b = schema_1.uniquenessFields[nodeType]) === null || _b === void 0 ? void 0 : _b[key]) !== null && _c !== void 0 ? _c : [];
85
+ // uniqueFields = ['term.@id', 'dates']
86
+ var pivotedKey = uniqueFields.length
87
+ ? uniqueFields
88
+ .map(function (field) {
89
+ var data = uniqueData(value, field);
90
+ return typeof data === 'undefined'
91
+ ? undefined
92
+ : field === 'term.@id' || uniqueFields.length === 1
93
+ ? valueAsKey(valueAsString(data))
94
+ : "".concat((0, utils_1.parentKey)(field), "[").concat(valueAsString(data), "]");
95
+ })
96
+ .filter(Boolean)
97
+ .join(headerJoin)
98
+ : '';
99
+ // pivotedKey = 'gwp100+dates[2021;2022]'
100
+ var data = (0, utils_1.omit)((0, exports.pivotNode)(schemas, value, false), __spreadArray(__spreadArray([], __read(uniqueFields), false), __read(ignoreKeys), false));
101
+ return _a = {}, _a[pivotedKey] = data, _a;
102
+ };
103
+ var simplifiedKeys = function (keys) { return (0, utils_1.findNonDuplicates)(keys.map(headerParentKey)); };
104
+ var mergeUnpivotedBlankNode = function (values, existingValue) {
105
+ return Object.assign.apply(Object, __spreadArray(__spreadArray([{}], __read(values.map(function (v) {
106
+ var _a;
107
+ return (_a = {}, _a[v] = {}, _a);
108
+ })), false), [existingValue || {}], false));
109
+ };
110
+ var mergeUnpivotedNodes = function (values, uniqueArrayKey) { return values.map(function (v) {
111
+ var _a;
112
+ return (_a = {}, _a[uniqueArrayKey] = v, _a);
113
+ }); };
114
+ var mergeUnpivotedByType = {
115
+ number: function (values) { return Number(values[0]); },
116
+ string: function (values) { return values[0]; },
117
+ boolean: function (values) { return Boolean(values[0]); },
118
+ null: function () { return null; },
119
+ array: function (values, definition, uniqueArrayKey, existingValue) {
120
+ var _a;
121
+ return ((_a = definition === null || definition === void 0 ? void 0 : definition.items) === null || _a === void 0 ? void 0 : _a.$ref)
122
+ ? mergeUnpivotedByType.$ref(values, definition.items, uniqueArrayKey, existingValue)
123
+ : __spreadArray(__spreadArray([], __read((existingValue || [])), false), __read(values), false).map(function (v) { return mergeUnpivotedByType[definition.items.type || 'string']([v]); })
124
+ .join(';');
125
+ },
126
+ $ref: function (values, _a, uniqueArrayKey, existingValue) {
127
+ var $ref = _a.$ref;
128
+ return (0, schema_1.isBlankNode)({ type: (0, schema_1.refToSchemaType)($ref) })
129
+ ? mergeUnpivotedBlankNode(values, existingValue)
130
+ : mergeUnpivotedNodes(values, uniqueArrayKey);
131
+ }
132
+ };
133
+ var mergeUnpivotedValue = function (definition, uniqueArrayItem, data, nodeValue, pivotedKey) {
134
+ var _a;
135
+ var _b = __read([pivotedKey.split('[')[0], pivotedKey.split('[')[1].replace(']', '').split(';')], 2), key = _b[0], newValues = _b[1];
136
+ var newValueDefinition = (_a = definition === null || definition === void 0 ? void 0 : definition.properties) === null || _a === void 0 ? void 0 : _a[key];
137
+ var uniqueArrayKey = (0, utils_1.childkey)((uniqueArrayItem !== null && uniqueArrayItem !== void 0 ? uniqueArrayItem : []).find(function (v) { return v.startsWith(key); }));
138
+ var valueType = newValueDefinition.type;
139
+ var functionValueType = '$ref' in newValueDefinition ? '$ref' : Array.isArray(valueType) ? valueType[0] : valueType;
140
+ data[key] = mergeUnpivotedByType[functionValueType](newValues, newValueDefinition, uniqueArrayKey, nodeValue[key]);
141
+ return data;
142
+ };
143
+ var unpivotBlankNode = function (definition, uniqueArrayItem, key, value) { return (__assign(__assign({}, value), key
144
+ .split(headerJoin)
145
+ .slice(1)
146
+ .reduce(function (prev, curr) { return mergeUnpivotedValue(definition, uniqueArrayItem, prev, value, curr); }, {}))); };
147
+ /**
148
+ * Pivot list of Blank Node and simplify when only one instance is found
149
+ *
150
+ * @param nodeType
151
+ * @param key
152
+ * @param value
153
+ */
154
+ var pivotBlankNodes = function (schemas, nodeType, key, value) {
155
+ var _a, _b;
156
+ var uniqueFields = (_b = (_a = schema_1.uniquenessFields[nodeType]) === null || _a === void 0 ? void 0 : _a[key]) !== null && _b !== void 0 ? _b : [];
157
+ var data = Object.assign.apply(Object, __spreadArray([{}], __read(value.map(function (val) { return pivotValue(schemas, nodeType, key, val); })), false));
158
+ var dataKeys = Object.keys(data);
159
+ var uniqueKeys = simplifiedKeys(dataKeys);
160
+ return (uniqueFields === null || uniqueFields === void 0 ? void 0 : uniqueFields[0]) === 'term.@id'
161
+ ? Object.fromEntries(Object.entries(data).map(function (_a) {
162
+ var _b, _c, _d, _e;
163
+ var _f = __read(_a, 2), entryKey = _f[0], value = _f[1];
164
+ var isUnique = entryKey !== headerParentKey(entryKey) && uniqueKeys.includes(headerParentKey(entryKey));
165
+ var blankNodeType = (0, schema_utils_1.keyType)(schemas[nodeType], key);
166
+ return [
167
+ isUnique ? headerParentKey(entryKey) : entryKey,
168
+ isUnique
169
+ ? unpivotBlankNode(schemas[blankNodeType], (_e = (_d = (_c = (_b = schemas[nodeType]) === null || _b === void 0 ? void 0 : _b.properties) === null || _c === void 0 ? void 0 : _c[key]) === null || _d === void 0 ? void 0 : _d.uniqueArrayItem) !== null && _e !== void 0 ? _e : [], entryKey, value)
170
+ : value
171
+ ];
172
+ }))
173
+ : data;
174
+ };
175
+ /**
176
+ * Pivot node and return in compacted format.
177
+ *
178
+ * @param schemas The definitions of the HESTIA Schema (`import { loadSchemas } from "@hestia-earth/json-schema"`)
179
+ * @param node The node to pivot.
180
+ * @param keepType To keep the `@type`/`type` key in the pivoted format.
181
+ * @returns
182
+ */
183
+ var pivotNode = function (schemas, _a, keepType) {
184
+ var _type = _a["@type"], type = _a.type, node = __rest(_a, ['@type', "type"]);
185
+ if (keepType === void 0) { keepType = true; }
186
+ return Object.fromEntries(__spreadArray([
187
+ keepType && (_type || type) ? [_type ? '@type' : 'type', _type || type] : null
188
+ ], __read(Object.entries(node)
189
+ .filter(function (_a) {
190
+ var _b = __read(_a, 1), key = _b[0];
191
+ return !ignoreKeys.includes(key) && ((_type || type) !== schema_1.NodeType.Term || !schema_1.termFields.includes(key));
192
+ })
193
+ .map(function (_a) {
194
+ var _b = __read(_a, 2), key = _b[0], value = _b[1];
195
+ return [
196
+ key,
197
+ value === null
198
+ ? null
199
+ : typeof value === 'object'
200
+ ? Array.isArray(value)
201
+ ? value.every(schema_1.isNode)
202
+ ? value.map(function (v) { return (0, exports.pivotNode)(schemas, v, false); })
203
+ : value.every(schema_1.isBlankNode)
204
+ ? pivotBlankNodes(schemas, _type || type, key, value)
205
+ : valueAsString(value)
206
+ : (0, exports.pivotNode)(schemas, value, false) // deep pivoting
207
+ : valueAsString(value)
208
+ ];
209
+ })), false).filter(Boolean));
210
+ };
211
+ exports.pivotNode = pivotNode;
212
+ var pivotNodes = function (schemas, nodes) {
213
+ return nodes.map(function (node) {
214
+ try {
215
+ return (0, exports.pivotNode)(schemas, node);
216
+ }
217
+ catch (err) {
218
+ throw new Error("Error pivoting ".concat(node['@type'] || node.type, " with id \"").concat(node['@id'] || node.id, "\":\n").concat(err.toString()));
219
+ }
220
+ });
221
+ };
222
+ exports.pivotNodes = pivotNodes;
package/json.d.ts CHANGED
@@ -34,16 +34,33 @@ export declare enum ErrorKeys {
34
34
  DuplicatedIdFields = "duplicated-id-fields",
35
35
  ObjectArrayInvalid = "object-array-invalid"
36
36
  }
37
+ interface IConversionParams {
38
+ /**
39
+ * Ignore all internal fields (see `internal: true` in the schema). Defaults to `true`.
40
+ */
41
+ ignoreInternal?: boolean;
42
+ /**
43
+ * Add default values (see `default: true` in the schema). Defaults to `true`.
44
+ */
45
+ addDefaults?: boolean;
46
+ }
47
+ interface IExtendedConversionParams extends IConversionParams {
48
+ /**
49
+ * If it's an existing Node on HESTIA, i.e. the `@id` is used instead of `id`.
50
+ */
51
+ existingNode?: boolean;
52
+ }
37
53
  export declare const throwCSVErrors: <T extends ICSVError>(errors: T[]) => never;
38
54
  export declare const cleanStringValue: (value: string) => string;
39
- export declare const formatNode: (schemas: definitions, type: SchemaType, data: ICSVContent, ignoreInternal: boolean, top?: boolean) => any;
55
+ export declare const formatNode: (schemas: definitions, type: SchemaType, data: ICSVContent, params?: IExtendedConversionParams) => any;
40
56
  export declare const filterEmptyNode: (schemas: definitions, node: any) => boolean;
41
57
  /**
42
58
  * Convert CSV to HESTIA JSON-LD format.
43
59
  *
44
60
  * @param schemas The definitions of the HESTIA Schema (`import { loadSchemas } from "@hestia-earth/json-schema"`)
45
61
  * @param content The content of the CSV as a string
62
+ * @param params Conversion parameters.
46
63
  * @returns A list of JSON-LD content.
47
64
  */
48
- export declare const toJson: (schemas: definitions, content: string) => Promise<any[]>;
65
+ export declare const toJson: (schemas: definitions, content: string, params?: IConversionParams) => Promise<any[]>;
49
66
  export {};
package/json.js CHANGED
@@ -128,7 +128,8 @@ var internalProperties = function (_a) {
128
128
  var isEmptyCell = function (value) { return value === IGNORE_FIELD_KEY || value === ''; };
129
129
  var nonEmptyCell = function (value) { return !isEmptyCell(value); };
130
130
  var isEmptyNode = function (node, schemas) {
131
- var schema = node.type ? schemas[node.type] : null;
131
+ var type = node.type || node['@type'];
132
+ var schema = type ? schemas[type] : null;
132
133
  var properties = Object.keys(node).filter(function (key) { return !types_1.excludedDefaultProperties.includes(key); });
133
134
  var defaultProperties = schema ? getDefaultProperties(schema).map(function (_a) {
134
135
  var property = _a.property;
@@ -359,8 +360,8 @@ exports.cleanStringValue = cleanStringValue;
359
360
  var propertyTypeToValue = {
360
361
  null: function (value) {
361
362
  var args = [];
362
- for (var _a = 1; _a < arguments.length; _a++) {
363
- args[_a - 1] = arguments[_a];
363
+ for (var _i = 1; _i < arguments.length; _i++) {
364
+ args[_i - 1] = arguments[_i];
364
365
  }
365
366
  return (isEmptyCell(value) ? null : propertyTypeToValue.auto.apply(propertyTypeToValue, __spreadArray([value], __read(args), false)));
366
367
  },
@@ -386,35 +387,35 @@ var propertyTypeToValue = {
386
387
  throw new Error('failed to parse boolean, expected true or false');
387
388
  })();
388
389
  },
389
- object: function (value, schemas, _a, _i) {
390
+ object: function (value, schemas, _a, params) {
390
391
  var $ref = _a.$ref, required = _a.required, geojson = _a.geojson;
391
392
  return geojson
392
393
  ? propertyTypeToValue.geojson(value)
393
394
  : $ref
394
- ? propertyTypeToValue.$ref(value, schemas, { $ref: $ref }, _i)
395
- : propertyTypeToValue.required(value, schemas, { required: required }, _i);
395
+ ? propertyTypeToValue.$ref(value, schemas, { $ref: $ref }, params)
396
+ : propertyTypeToValue.required(value, schemas, { required: required }, params);
396
397
  },
397
- array: function (value, schemas, _a, _i) {
398
+ array: function (value, schemas, _a, params) {
398
399
  var items = _a.items;
399
400
  return (Array.isArray(value) ? value : value.split(arrayDelimiter()))
400
401
  .map(handleArrayError(function (val) {
401
402
  return items
402
403
  ? '$ref' in items
403
- ? propertyTypeToValue.object(val, schemas, items, _i)
404
+ ? propertyTypeToValue.object(val, schemas, items, params)
404
405
  : Array.isArray(items.type)
405
406
  ? val === IGNORE_FIELD_KEY
406
407
  ? null
407
- : propertyTypeToValue.auto(val, schemas, items, _i)
408
- : propertyTypeToValue[items.type](val, schemas, items, _i)
408
+ : propertyTypeToValue.auto(val, schemas, items, params)
409
+ : propertyTypeToValue[items.type](val, schemas, items, params)
409
410
  : val;
410
411
  }))
411
412
  .filter(function (val) { return !isEmptyValue(val, schemas); });
412
413
  },
413
414
  // try to determine the type automatically
414
- auto: function (value, schemas, _d, _i) {
415
+ auto: function (value, schemas, _d, params) {
415
416
  // iris are mapped as {@id: val}
416
417
  return (0, utils_1.isIri)(value)
417
- ? propertyTypeToValue.required(value, schemas, { required: ['@id'] }, _i)
418
+ ? propertyTypeToValue.required(value, schemas, { required: ['@id'] }, params)
418
419
  : (0, utils_1.isBoolean)(value)
419
420
  ? propertyTypeToValue.boolean(value)
420
421
  : (0, utils_1.isNumber)(value)
@@ -428,17 +429,21 @@ var propertyTypeToValue = {
428
429
  var data = propertyRequiredValue(value, required);
429
430
  return (0, utils_1.isEmpty)(data) ? {} : data;
430
431
  },
431
- $ref: function (value, schemas, _a, _i) {
432
+ $ref: function (value, schemas, _a, params) {
432
433
  var $ref = _a.$ref;
433
434
  var schemaType = (0, schema_1.refToSchemaType)($ref);
434
435
  var schema = schemaType ? schemas[schemaType] : undefined;
435
436
  var data = schema
436
- ? mapContent(schemas, schema, _i)(schemaRefValue(value, schemaType))
437
+ ? mapContent(schemas, schema, params)(schemaRefValue(value, schemaType))
437
438
  : $ref in propertyTypeToValue
438
439
  ? propertyTypeToValue[$ref](value)
439
440
  : safeParseJSON(value);
440
- var includeDefaults = (0, schema_1.isBlankNode)(data) || schemaType === schema_1.SchemaType.Actor; // only blank nodes or actors allowed
441
- return (0, utils_1.isEmpty)(data) ? {} : !!schema ? extendDataFromSchema(data, schema, schemaType, _i, includeDefaults) : data;
441
+ var addDefaults = (0, schema_1.isBlankNode)(data) || schemaType === schema_1.SchemaType.Actor; // only blank nodes or actors allowed
442
+ return (0, utils_1.isEmpty)(data)
443
+ ? {}
444
+ : !!schema
445
+ ? extendDataFromSchema(data, schema, schemaType, __assign(__assign({}, params), { addDefaults: addDefaults }))
446
+ : data;
442
447
  },
443
448
  geojson: function (value) { return (isEmptyCell(value) ? undefined : parseGeoJSONValue(value)); }
444
449
  };
@@ -488,19 +493,18 @@ var filterProperties = function (data, excludedProps) {
488
493
  };
489
494
  var nodeType = function (id, type, existingNode) {
490
495
  if (existingNode === void 0) { existingNode = false; }
491
- return type ? ((0, schema_1.isTypeNode)(type) ? (existingNode ? { '@type': type } : { id: id, type: type }) : { type: type }) : {};
496
+ return type ? (existingNode ? { '@type': type } : { id: id, type: type }) : {};
492
497
  };
493
- var extendDataFromSchema = function (_a, schema, type, ignoreInternal, addDefaults) {
498
+ var extendDataFromSchema = function (_a, schema, type, _b) {
494
499
  var id = _a.id, _t = _a.type, data = __rest(_a, ["id", "type"]);
495
- if (ignoreInternal === void 0) { ignoreInternal = false; }
496
- if (addDefaults === void 0) { addDefaults = false; }
500
+ var _c = _b === void 0 ? {} : _b, ignoreInternal = _c.ignoreInternal, addDefaults = _c.addDefaults, existingNode = _c.existingNode;
497
501
  return (0, utils_1.reduceUndefinedValues)(__assign(__assign(__assign({}, filterProperties(data, ignoreInternal ? [] : internalProperties(schema))), (addDefaults && !('@id' in data) && schema
498
502
  ? getDefaultProperties(schema, data, ignoreInternal).reduce(function (prev, _a) {
499
503
  var property = _a.property, defaultValue = _a.defaultValue;
500
504
  prev[property] = defaultValue;
501
505
  return prev;
502
506
  }, {})
503
- : {})), nodeType(id, type, '@id' in data)), true);
507
+ : {})), nodeType(id, type, '@id' in data || existingNode)), true);
504
508
  };
505
509
  var validateArrayType = function (schema, def, key, value) {
506
510
  return typeof value !== 'object' ||
@@ -516,7 +520,7 @@ var validateArrayType = function (schema, def, key, value) {
516
520
  }
517
521
  ]);
518
522
  };
519
- var mapContent = function (schemas, schema, ignoreInternal) { return function (json) {
523
+ var mapContent = function (schemas, schema, params) { return function (json) {
520
524
  var values = Object.keys(json)
521
525
  .filter(nonEmptyCell)
522
526
  .map(function (key) {
@@ -531,11 +535,12 @@ var mapContent = function (schemas, schema, ignoreInternal) { return function (j
531
535
  var newValue = key === VALUE_TYPE_KEY
532
536
  ? ''
533
537
  : propertyInvalidFormat(schema, key, value_1, function () {
534
- return Array.isArray(type_1)
535
- ? value_1
536
- : propertyTypeToValue[type_1](value_1, schemas, propertyDefinition_1, ignoreInternal);
538
+ return Array.isArray(type_1) ? value_1 : propertyTypeToValue[type_1](value_1, schemas, propertyDefinition_1, params);
537
539
  });
538
- return { errors: [], value: type_1 !== 'null' && isEmptyValue(newValue, schemas) ? undefined : [key, newValue] };
540
+ return {
541
+ errors: [],
542
+ value: type_1 !== 'null' && isEmptyValue(newValue, schemas) ? undefined : [key, newValue]
543
+ };
539
544
  }
540
545
  catch (err) {
541
546
  var errors_1 = JSON.parse(err.message).errors;
@@ -556,23 +561,26 @@ var mapContent = function (schemas, schema, ignoreInternal) { return function (j
556
561
  return value;
557
562
  })), false).filter(Boolean));
558
563
  }; };
559
- var formatNode = function (schemas, type, data, ignoreInternal, top) {
560
- if (top === void 0) { top = false; }
564
+ var formatNode = function (schemas, type, data, params) {
565
+ if (params === void 0) { params = {}; }
561
566
  var schema = type in schemas && exports.acceptedNodeTypes.includes(type) ? schemas[type] : schemaNotFoundError(type);
562
- var content = mapContent(schemas, schema, ignoreInternal)(data);
563
- return (0, utils_1.reduceUndefinedValues)(__assign({ id: isEmptyCell(data.id) ? undefined : data.id }, extendDataFromSchema(content, schema, type, ignoreInternal, top)), true);
567
+ var content = mapContent(schemas, schema, params)(data);
568
+ return (0, utils_1.reduceUndefinedValues)(__assign({ id: isEmptyCell(data.id) ? undefined : data.id }, extendDataFromSchema(content, schema, type, params)), true);
564
569
  };
565
570
  exports.formatNode = formatNode;
566
571
  var filterEmptyNode = function (schemas, node) {
567
- var schema = node.type ? schemas[node.type] : null;
572
+ var type = node.type || node['@type'];
573
+ var schema = type ? schemas[type] : null;
568
574
  // make sure defaultProperties are not counted
569
575
  return !!schema && !isEmptyNode(node, schemas);
570
576
  };
571
577
  exports.filterEmptyNode = filterEmptyNode;
572
- var convetToNode = function (schemas) { return function (data) {
578
+ var convetToNode = function (schemas, params) { return function (data) {
573
579
  return Object.keys(data)
574
580
  .filter(utils_1.nonEmptyValue)
575
- .map(function (type) { return (0, exports.formatNode)(schemas, (0, schema_1.typeToSchemaType)(type), data[type], true, true); })
581
+ .map(function (type) {
582
+ return (0, exports.formatNode)(schemas, (0, schema_1.typeToSchemaType)(type), data[type], __assign(__assign({}, params), { existingNode: '@id' in data[type] }));
583
+ })
576
584
  .filter(function (node) { return (0, exports.filterEmptyNode)(schemas, node); });
577
585
  }; };
578
586
  /**
@@ -580,20 +588,25 @@ var convetToNode = function (schemas) { return function (data) {
580
588
  *
581
589
  * @param schemas The definitions of the HESTIA Schema (`import { loadSchemas } from "@hestia-earth/json-schema"`)
582
590
  * @param content The content of the CSV as a string
591
+ * @param params Conversion parameters.
583
592
  * @returns A list of JSON-LD content.
584
593
  */
585
- var toJson = function (schemas, content) { return __awaiter(void 0, void 0, void 0, function () {
586
- var nodes;
587
- return __generator(this, function (_a) {
588
- switch (_a.label) {
589
- case 0: return [4 /*yield*/, csvtojson({
590
- delimiter: 'auto',
591
- ignoreColumns: /^$/
592
- }).fromString(content)];
593
- case 1:
594
- nodes = (_a.sent()).flatMap(convetToNode(schemas));
595
- return [2 /*return*/, (0, default_values_1.setDefaultValues)(nodes)];
596
- }
594
+ var toJson = function (schemas, content, params) {
595
+ if (params === void 0) { params = { ignoreInternal: true, addDefaults: true }; }
596
+ return __awaiter(void 0, void 0, void 0, function () {
597
+ var nodes, converted;
598
+ return __generator(this, function (_a) {
599
+ switch (_a.label) {
600
+ case 0: return [4 /*yield*/, csvtojson({
601
+ delimiter: 'auto',
602
+ ignoreColumns: /^$/
603
+ }).fromString(content)];
604
+ case 1:
605
+ nodes = _a.sent();
606
+ converted = nodes.flatMap(convetToNode(schemas, params));
607
+ return [2 /*return*/, (0, default_values_1.setDefaultValues)(converted)];
608
+ }
609
+ });
597
610
  });
598
- }); };
611
+ };
599
612
  exports.toJson = toJson;
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@hestia-earth/schema-convert",
3
- "version": "30.0.1",
3
+ "version": "30.2.0",
4
4
  "description": "HESTIA Schema Converters",
5
5
  "main": "index.js",
6
6
  "typings": "index.d.ts",
7
7
  "bin": {
8
8
  "hestia-convert-to-csv-pivot": "bin/bin-convert-to-csv-pivot.js",
9
9
  "hestia-convert-to-csv": "bin/bin-convert-to-csv.js",
10
- "hestia-convert-to-json": "bin/bin-convert-to-json.js"
10
+ "hestia-convert-to-json": "bin/bin-convert-to-json.js",
11
+ "hestia-pivot-file": "bin/bin-pivot-file.js"
11
12
  },
12
13
  "repository": {
13
14
  "type": "git",
@@ -0,0 +1 @@
1
+ export declare const run: () => Promise<any[]>;
package/pivot-file.js ADDED
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __read = (this && this.__read) || function (o, n) {
39
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
40
+ if (!m) return o;
41
+ var i = m.call(o), r, ar = [], e;
42
+ try {
43
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
44
+ }
45
+ catch (error) { e = { error: error }; }
46
+ finally {
47
+ try {
48
+ if (r && !r.done && (m = i["return"])) m.call(i);
49
+ }
50
+ finally { if (e) throw e.error; }
51
+ }
52
+ return ar;
53
+ };
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.run = void 0;
56
+ var fs_1 = require("fs");
57
+ var path_1 = require("path");
58
+ var json_schema_1 = require("@hestia-earth/json-schema");
59
+ var file_utils_1 = require("./file-utils");
60
+ var json_pivot_1 = require("./json-pivot");
61
+ var csv_pivot_1 = require("./csv-pivot");
62
+ var _a = __read(process.argv.slice(2), 2), path = _a[0], format = _a[1];
63
+ var readFile = fs_1.promises.readFile, writeFile = fs_1.promises.writeFile;
64
+ var encoding = 'utf8';
65
+ var Format;
66
+ (function (Format) {
67
+ Format["csv"] = "csv";
68
+ Format["json"] = "json";
69
+ })(Format || (Format = {}));
70
+ var formats = Object.values(Format);
71
+ if (format && !formats.includes(format)) {
72
+ throw new Error("Invalid format. Please use either ".concat(formats.map(function (v) { return "\"".concat(v, "\""); }).join(' or ')));
73
+ }
74
+ var saveToFileExt = {
75
+ json: function (filepath, nodes) {
76
+ return writeFile(filepath.replace((0, path_1.extname)(filepath), '.json'), JSON.stringify(nodes, null, 2), encoding);
77
+ },
78
+ csv: function (filepath, nodes) { return writeFile(filepath.replace((0, path_1.extname)(filepath), '.csv'), (0, csv_pivot_1.toCsv)(nodes), encoding); }
79
+ };
80
+ var processJsonFile = function (schemas, filepath) { return __awaiter(void 0, void 0, void 0, function () {
81
+ var data, _a, _b, pivoted;
82
+ return __generator(this, function (_c) {
83
+ switch (_c.label) {
84
+ case 0:
85
+ _b = (_a = JSON).parse;
86
+ return [4 /*yield*/, readFile(filepath, encoding)];
87
+ case 1:
88
+ data = _b.apply(_a, [_c.sent()]);
89
+ pivoted = Array.isArray(data)
90
+ ? (0, json_pivot_1.pivotNodes)(schemas, data)
91
+ : 'nodes' in data
92
+ ? { nodes: (0, json_pivot_1.pivotNodes)(schemas, data.nodes) }
93
+ : (0, json_pivot_1.pivotNode)(schemas, data);
94
+ return [2 /*return*/, saveToFileExt[format](filepath, pivoted)];
95
+ }
96
+ });
97
+ }); };
98
+ var processCsvFile = function (schemas, filepath) { return __awaiter(void 0, void 0, void 0, function () {
99
+ var toJson, content, nodes, pivoted;
100
+ return __generator(this, function (_a) {
101
+ switch (_a.label) {
102
+ case 0: return [4 /*yield*/, Promise.resolve().then(function () { return require('./json'); })];
103
+ case 1:
104
+ toJson = (_a.sent()).toJson;
105
+ return [4 /*yield*/, readFile(filepath, encoding)];
106
+ case 2:
107
+ content = _a.sent();
108
+ return [4 /*yield*/, toJson(schemas, content, { ignoreInternal: false, addDefaults: false })];
109
+ case 3:
110
+ nodes = _a.sent();
111
+ pivoted = (0, json_pivot_1.pivotNodes)(schemas, nodes);
112
+ return [2 /*return*/, saveToFileExt[format](filepath, pivoted)];
113
+ }
114
+ });
115
+ }); };
116
+ var processFileExt = {
117
+ '.json': processJsonFile,
118
+ '.jsonld': processJsonFile,
119
+ '.csv': processCsvFile
120
+ };
121
+ var run = function () { return __awaiter(void 0, void 0, void 0, function () {
122
+ var schemas, files;
123
+ return __generator(this, function (_a) {
124
+ switch (_a.label) {
125
+ case 0:
126
+ schemas = (0, json_schema_1.loadSchemas)();
127
+ return [4 /*yield*/, (0, file_utils_1.listFiles)(path, '.csv', '.jsonld', '.json')];
128
+ case 1:
129
+ files = _a.sent();
130
+ return [2 /*return*/, Promise.all(files.map(function (file) { return processFileExt[(0, path_1.extname)(file)](schemas, file); }))];
131
+ }
132
+ });
133
+ }); };
134
+ exports.run = run;
package/utils.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ export declare const omitKeys: string[];
2
+ export declare const parentKey: (key: string) => string;
3
+ export declare const childkey: (key: string) => string;
1
4
  export declare const omit: (data: any, keys: string[]) => any;
2
5
  export declare const isExpandable: (val: any) => any;
3
6
  export declare const isIri: (value?: string) => boolean;
@@ -12,3 +15,6 @@ export declare const keyToLabel: (key: string) => string;
12
15
  export declare const diffInDays: (date1: Date | string, date2: Date | string) => number;
13
16
  export declare const daysBefore: (date?: Date, days?: number) => Date;
14
17
  export declare const daysInYear: (year: number) => 366 | 365;
18
+ export declare const convertValue: (value: any) => any;
19
+ export declare const findDuplicates: (values: string[]) => string[];
20
+ export declare const findNonDuplicates: (values: string[]) => string[];
package/utils.js CHANGED
@@ -10,12 +10,69 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
+ var __read = (this && this.__read) || function (o, n) {
14
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
15
+ if (!m) return o;
16
+ var i = m.call(o), r, ar = [], e;
17
+ try {
18
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
19
+ }
20
+ catch (error) { e = { error: error }; }
21
+ finally {
22
+ try {
23
+ if (r && !r.done && (m = i["return"])) m.call(i);
24
+ }
25
+ finally { if (e) throw e.error; }
26
+ }
27
+ return ar;
28
+ };
29
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
30
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
31
+ if (ar || !(i in from)) {
32
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
33
+ ar[i] = from[i];
34
+ }
35
+ }
36
+ return to.concat(ar || Array.prototype.slice.call(from));
37
+ };
13
38
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.daysInYear = exports.daysBefore = exports.diffInDays = exports.keyToLabel = exports.ellipsis = exports.reduceUndefinedValues = exports.nonEmptyNode = exports.nonEmptyValue = exports.isEmpty = exports.isNumber = exports.isBoolean = exports.isIri = exports.isExpandable = exports.omit = void 0;
39
+ exports.findNonDuplicates = exports.findDuplicates = exports.convertValue = exports.daysInYear = exports.daysBefore = exports.diffInDays = exports.keyToLabel = exports.ellipsis = exports.reduceUndefinedValues = exports.nonEmptyNode = exports.nonEmptyValue = exports.isEmpty = exports.isNumber = exports.isBoolean = exports.isIri = exports.isExpandable = exports.omit = exports.childkey = exports.parentKey = exports.omitKeys = void 0;
40
+ var get = require('lodash.get');
15
41
  var unset = require('lodash.unset');
42
+ exports.omitKeys = __spreadArray([
43
+ '@context',
44
+ 'schemaVersion',
45
+ 'dataPrivate'
46
+ ], __read(['bibliography', 'site', 'cycle', 'impactAssessment', 'defaultSource', 'source'].flatMap(function (k) { return [
47
+ "".concat(k, ".id"),
48
+ "".concat(k, ".type"),
49
+ "".concat(k, ".@type")
50
+ ]; })), false);
51
+ var parentKey = function (key) { return key.split('.')[0]; };
52
+ exports.parentKey = parentKey;
53
+ var childkey = function (key) { return key.split('.').slice(1).join('.'); };
54
+ exports.childkey = childkey;
16
55
  var omit = function (data, keys) {
17
56
  var obj = __assign({}, data);
18
- keys.forEach(function (key) { return unset(obj, key); });
57
+ keys.forEach(function (key) {
58
+ unset(obj, key);
59
+ // handle arrays and notation without array
60
+ var _parentKey = (0, exports.parentKey)(key);
61
+ var _childkey = (0, exports.childkey)(key);
62
+ var parentData = key.includes('.') ? get(obj, _parentKey, undefined) : undefined;
63
+ if (typeof parentData === 'object') {
64
+ if (Array.isArray(parentData)) {
65
+ parentData.forEach(function (_v, index) {
66
+ unset(obj, "".concat(_parentKey, "[").concat(index, "].").concat(_childkey));
67
+ });
68
+ // only keep values that are not empty
69
+ obj[_parentKey] = obj[_parentKey].filter(function (v) { return !(0, exports.isEmpty)(v); });
70
+ }
71
+ if ((0, exports.isEmpty)(obj[_parentKey])) {
72
+ unset(obj, _parentKey);
73
+ }
74
+ }
75
+ });
19
76
  return obj;
20
77
  };
21
78
  exports.omit = omit;
@@ -90,3 +147,17 @@ var daysBefore = function (date, days) {
90
147
  exports.daysBefore = daysBefore;
91
148
  var daysInYear = function (year) { return ((year % 4 === 0 && year % 100 > 0) || year % 400 === 0 ? 366 : 365); };
92
149
  exports.daysInYear = daysInYear;
150
+ var convertValue = function (value) {
151
+ return Array.isArray(value) ? value.map(String).join(';') : typeof value === 'object' ? JSON.stringify(value) : value;
152
+ };
153
+ exports.convertValue = convertValue;
154
+ var count = function (values) { return values.reduce(function (a, b) {
155
+ var _a;
156
+ return (__assign(__assign({}, a), (_a = {}, _a[b] = (a[b] || 0) + 1, _a)));
157
+ }, {}); };
158
+ var duplicates = function (dict) { return Object.keys(dict).filter(function (a) { return dict[a] > 1; }); };
159
+ var nonDuplicates = function (dict) { return Object.keys(dict).filter(function (a) { return dict[a] === 1; }); };
160
+ var findDuplicates = function (values) { return duplicates(count(values)); };
161
+ exports.findDuplicates = findDuplicates;
162
+ var findNonDuplicates = function (values) { return nonDuplicates(count(values)); };
163
+ exports.findNonDuplicates = findNonDuplicates;