@gisatcz/ptr-be-core 0.0.1-dev.7 → 0.0.1-dev.9

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,5 +1,8 @@
1
+ import { DateTime } from 'luxon';
1
2
  import pino from 'pino';
2
3
  import pretty from 'pino-pretty';
4
+ import { randomUUID } from 'crypto';
5
+ import _ from 'lodash';
3
6
 
4
7
  /**
5
8
  * Check if the value in included in enum posibilities.
@@ -96,6 +99,206 @@ const flattenObject = (obj, prefix = '') => {
96
99
  }, {});
97
100
  };
98
101
 
102
+ /**
103
+ * Extract message from exception error (try-catch)
104
+ * @param error error from catch block as any
105
+ * @returns
106
+ */
107
+ const messageFromError = (error) => error["message"];
108
+ /**
109
+ * We miss a API parameter needed to process action
110
+ */
111
+ class InvalidRequestError extends Error {
112
+ constructor(message) {
113
+ super(`Invalid Request: ${message}`);
114
+ }
115
+ }
116
+ /**
117
+ * Where client has general authorization issue
118
+ */
119
+ class AuthorizationError extends Error {
120
+ constructor() {
121
+ super(`Authorization has failed.`);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Return epoch timestamp
127
+ * @param regime Set if you want milisecond format or second format
128
+ * @returns
129
+ */
130
+ const nowTimestamp = (regime = "milisecond") => {
131
+ const timestamp = DateTime.now().toMillis();
132
+ return regime === "second" ? Math.round((timestamp / 1000)) : timestamp;
133
+ };
134
+ /**
135
+ * Convert epoch time value into ISO format
136
+ * @param epochValue Epoch value of the timestamp
137
+ * @returns ISO format of the date
138
+ */
139
+ const epochToIsoFormat = (epochValue) => DateTime.fromMillis(epochValue).toISO();
140
+ /**
141
+ * Return epoch timestamp
142
+ * @param regime Set if you want milisecond format or second format
143
+ * @returns
144
+ */
145
+ const nowTimestampIso = () => {
146
+ const timestamp = DateTime.now().toISO();
147
+ return timestamp;
148
+ };
149
+ /**
150
+ * Check if input date is valid for ISO format
151
+ * @param dateToCheck
152
+ * @returns
153
+ */
154
+ const hasIsoFormat = (dateToCheck) => {
155
+ try {
156
+ const toDate = new Date(Date.parse(dateToCheck));
157
+ const isoCheck = toDate.toISOString().includes(dateToCheck);
158
+ return isoCheck;
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ };
164
+ /**
165
+ * Convert date in ISO formtat to milisecond timestamp
166
+ * @param isoDate Date in ISO 8601 format
167
+ * @returns Timestamp representing the date in miliseconds
168
+ */
169
+ const isoDateToTimestamp = (isoDate) => DateTime.fromISO(isoDate).toMillis();
170
+ /**
171
+ * Format ISO 8601 interval to from-to values
172
+ * @param interval Defined inteval in ISO format (from/to) of the UTC
173
+ * @returns Tuple - from timestamp and to timestamp
174
+ */
175
+ const isoIntervalToTimestamps = (interval) => {
176
+ // Split the interval into two parts
177
+ const intervals = interval.split("/");
178
+ // interval as a single year has just one part
179
+ if (intervals.length == 1) {
180
+ const newIso = `${interval}-01-01/${interval}-12-31`;
181
+ return isoIntervalToTimestamps(newIso);
182
+ }
183
+ // interval with two parts or less than one
184
+ else if (intervals.length > 2 || intervals.length < 1)
185
+ throw new InvalidRequestError("Interval can have only two parameters");
186
+ // valid interval with two parts
187
+ else {
188
+ if (!intervals.every(interval => hasIsoFormat(interval)))
189
+ throw new InvalidRequestError("Parameter utcIntervalIso is not ISO 8601 time interval (date01/date02) or year");
190
+ const [int1, int2] = intervals.map(intervalIso => {
191
+ const cleared = intervalIso.replace(" ", "");
192
+ return isoDateToTimestamp(cleared);
193
+ });
194
+ return [int1, int2];
195
+ }
196
+ };
197
+
198
+ // TODO: Cover by tests
199
+ // TODO: mode to ptr-be-core as general CSV methods
200
+ /**
201
+ * Parses a single line of CSV-formatted strings into an array of trimmed string values.
202
+ *
203
+ * @param csvStingsLine - A string representing a single line of comma-separated values.
204
+ * @returns An array of strings, each representing a trimmed value from the CSV line.
205
+ */
206
+ const csvParseStrings = (csvStingsLine) => {
207
+ return csvStingsLine.split(",").map((value) => value.trim());
208
+ };
209
+ /**
210
+ * Parses a comma-separated string of numbers into an array of numbers.
211
+ *
212
+ * @param csvNumbersLine - A string containing numbers separated by commas (e.g., "1, 2, 3.5").
213
+ * @returns An array of numbers parsed from the input string.
214
+ */
215
+ const csvParseNumbers = (csvNumbersLine) => {
216
+ return csvNumbersLine.split(",").map((value) => parseFloat(value.trim()));
217
+ };
218
+
219
+ /**
220
+ * Finds the first node in the provided list that contains the specified label.
221
+ *
222
+ * Searches the given array of FullPantherEntity objects and returns the first entity
223
+ * whose `labels` array includes the provided label.
224
+ *
225
+ * @param nodes - Array of FullPantherEntity objects to search through.
226
+ * @param label - Label to match; may be a UsedDatasourceLabels or UsedNodeLabels.
227
+ * @returns The first FullPantherEntity whose `labels` includes `label`, or `undefined`
228
+ * if no such entity is found.
229
+ *
230
+ * @remarks
231
+ * - The search stops at the first match (uses `Array.prototype.find`).
232
+ * - Label comparison is exact (uses `Array.prototype.includes`), so it is case-sensitive
233
+ * and requires the same string instance/value.
234
+ *
235
+ * @example
236
+ * const result = findNodeByLabel(nodes, 'datasource-main');
237
+ * if (result) {
238
+ * // found a node that has the 'datasource-main' label
239
+ * }
240
+ */
241
+ const findNodeByLabel = (nodes, label) => {
242
+ return nodes.find(n => n.labels.includes(label));
243
+ };
244
+ /**
245
+ * Filters an array of FullPantherEntity objects, returning only those that contain the specified label.
246
+ *
247
+ * The function performs a shallow, non-mutating filter: it returns a new array and does not modify the input.
248
+ * Matching is done using Array.prototype.includes on each entity's `labels` array (strict equality).
249
+ *
250
+ * @param nodes - The array of entities to filter.
251
+ * @param label - The label to match; can be a UsedDatasourceLabels or UsedNodeLabels value.
252
+ * @returns A new array containing only the entities whose `labels` array includes the provided label.
253
+ *
254
+ * @remarks
255
+ * Time complexity is O(n * m) where n is the number of entities and m is the average number of labels per entity.
256
+ *
257
+ * @example
258
+ * ```ts
259
+ * const matched = filterNodeByLabel(entities, 'MY_LABEL');
260
+ * ```
261
+ */
262
+ const filterNodeByLabel = (nodes, label) => {
263
+ return nodes.filter(n => n.labels.includes(label));
264
+ };
265
+ /**
266
+ * Finds the first edge in the provided array whose label strictly equals the given label.
267
+ *
268
+ * @param edges - Array of GraphEdge objects to search.
269
+ * @param label - The UsedEdgeLabels value to match against each edge's `label` property.
270
+ * @returns The first matching GraphEdge if found; otherwise `undefined`.
271
+ *
272
+ * @example
273
+ * const edge = findEdgeByLabel(edges, 'dependency');
274
+ * if (edge) {
275
+ * // handle found edge
276
+ * }
277
+ */
278
+ const findEdgeByLabel = (edges, label) => {
279
+ return edges.find(e => e.label === label);
280
+ };
281
+ /**
282
+ * Filters a list of GraphEdge objects by a specific edge label.
283
+ *
284
+ * Returns a new array containing only those edges whose `label` property
285
+ * strictly equals the provided `label` argument. The original `edges`
286
+ * array is not mutated.
287
+ *
288
+ * @param edges - Array of GraphEdge objects to filter.
289
+ * @param label - The label to match; comparison is performed using strict (`===`) equality.
290
+ * @returns A new array of GraphEdge objects whose `label` matches the provided label. Returns an empty array if no edges match.
291
+ *
292
+ * @remarks
293
+ * Time complexity: O(n), where n is the number of edges.
294
+ *
295
+ * @example
296
+ * // const result = filterEdgeByLabel(edges, 'CONNECTS');
297
+ */
298
+ const filterEdgeByLabel = (edges, label) => {
299
+ return edges.filter(e => e.label === label);
300
+ };
301
+
99
302
  /**
100
303
  * What types of graph nodes we use in metadata model
101
304
  */
@@ -154,29 +357,6 @@ var UsedTimeseriesSteps;
154
357
  UsedTimeseriesSteps["Day"] = "day";
155
358
  })(UsedTimeseriesSteps || (UsedTimeseriesSteps = {}));
156
359
 
157
- /**
158
- * Extract message from exception error (try-catch)
159
- * @param error error from catch block as any
160
- * @returns
161
- */
162
- const messageFromError = (error) => error["message"];
163
- /**
164
- * We miss a API parameter needed to process action
165
- */
166
- class InvalidRequestError extends Error {
167
- constructor(message) {
168
- super(`Invalid Request: ${message}`);
169
- }
170
- }
171
- /**
172
- * Where client has general authorization issue
173
- */
174
- class AuthorizationError extends Error {
175
- constructor() {
176
- super(`Authorization has failed.`);
177
- }
178
- }
179
-
180
360
  // logger.ts
181
361
  const DEFAULT_LOG_OPTIONS = {
182
362
  label: 'App'
@@ -204,5 +384,522 @@ class AppLogger {
204
384
  }
205
385
  }
206
386
 
207
- export { AppLogger, AuthorizationError, InvalidRequestError, UsedDatasourceLabels, UsedEdgeLabels, UsedNodeLabels, UsedTimeseriesSteps, enumCombineValuesToString, enumValuesToArray, enumValuesToString, flattenObject, isInEnum, messageFromError, notEmptyString, randomNumberBetween, removeDuplicitiesFromArray, sortStringArray };
387
+ /**
388
+ * Validates the provided labels to ensure they are an array of strings and that each label
389
+ * is a valid value within the specified enums (`UsedNodeLabels` or `UsedDatasourceLabels`).
390
+ *
391
+ * @param labels - The input to validate, expected to be an array of strings.
392
+ * @throws {InvalidRequestError} If `labels` is not an array.
393
+ * @throws {InvalidRequestError} If any label in the array is not a valid value in the combined enums.
394
+ */
395
+ const validateNodeLabels = (labels) => {
396
+ if (labels === undefined || labels === null) {
397
+ throw new InvalidRequestError("Graph node labels are required.");
398
+ }
399
+ if (!_.isArray(labels))
400
+ throw new InvalidRequestError(`Graph node labels must be an array of strings.`);
401
+ if (labels.length === 0)
402
+ throw new InvalidRequestError("Graph node labels array must contain at least one label.");
403
+ for (const label of labels) {
404
+ if (!isInEnum(label, UsedNodeLabels) && !isInEnum(label, UsedDatasourceLabels))
405
+ throw new InvalidRequestError(`Label ${label} is not supported. Value must be one of: ${enumCombineValuesToString([UsedNodeLabels, UsedDatasourceLabels])}`);
406
+ }
407
+ };
408
+ /**
409
+ * Validate a graph edge label.
410
+ *
411
+ * The value is first checked for presence (not `undefined`/`null`), then for type (`string`).
412
+ * The string is normalised using `toLocaleLowerCase()` and validated against the `UsedEdgeLabels` enum.
413
+ *
414
+ * @param label - The value to validate; expected to be a string representing an edge label.
415
+ *
416
+ * @throws {InvalidRequestError} If `label` is `undefined` or `null`.
417
+ * @throws {InvalidRequestError} If `label` is not a `string`.
418
+ * @throws {InvalidRequestError} If the normalised label is not one of the supported values in `UsedEdgeLabels`.
419
+ *
420
+ * @example
421
+ * validateEdgeLabel('CONNECTS'); // succeeds if 'connects' exists in UsedEdgeLabels
422
+ *
423
+ * @remarks
424
+ * Membership is determined via `isInEnum` and error messages include the allowed values (via `enumCombineValuesToString`).
425
+ */
426
+ const validateEdgeLabel = (label) => {
427
+ if (label === undefined || label === null) {
428
+ throw new InvalidRequestError("Graph edge label is required.");
429
+ }
430
+ if (typeof label !== "string") {
431
+ throw new InvalidRequestError(`Graph edge label must be a string.`);
432
+ }
433
+ const normalisedLabel = label.toLocaleLowerCase();
434
+ if (!isInEnum(normalisedLabel, UsedEdgeLabels)) {
435
+ throw new InvalidRequestError(`Graph edge label '${normalisedLabel}' is not supported. Value must be one of: ${enumCombineValuesToString([UsedEdgeLabels])}`);
436
+ }
437
+ };
438
+
439
+ /**
440
+ * Extract and parse basic entitry from request body
441
+ * This parse function is used in other parsers, becuase basic entity is part of other models
442
+ * @param bodyRaw Body from http request
443
+ * @param key Optional - key value for existing recods in database
444
+ * @returns Parsed entity - all unwanted parameters are gone
445
+ */
446
+ const parseBasicNodeFromBody = (bodyRaw) => {
447
+ const { labels, nameInternal, nameDisplay, description, key } = bodyRaw;
448
+ validateNodeLabels(labels);
449
+ const basicGraphResult = {
450
+ lastUpdatedAt: nowTimestamp(),
451
+ key: key ?? randomUUID(),
452
+ nameInternal: nameInternal ?? "",
453
+ nameDisplay: nameDisplay ?? "",
454
+ description: description ?? "",
455
+ labels: labels
456
+ };
457
+ return basicGraphResult;
458
+ };
459
+ /**
460
+ * Parse node of type area tree level
461
+ * @param levelBody Content from request
462
+ * @returns Parsed area tree level
463
+ */
464
+ const paseHasLevels = (levelBody) => {
465
+ const { level } = levelBody;
466
+ const result = {
467
+ level
468
+ };
469
+ return result;
470
+ };
471
+ /**
472
+ * Parse body to period entity
473
+ * @param bodyRaw Request body content - can be anything
474
+ * @returns Parsed entity - all unwanted parameters are gone
475
+ */
476
+ const parseWithInterval = (bodyRaw) => {
477
+ const { intervalISO, } = bodyRaw;
478
+ if (!intervalISO)
479
+ throw new InvalidRequestError("Period must have UTC interval in ISO format");
480
+ const [from, to] = isoIntervalToTimestamps(intervalISO);
481
+ const intervalResult = {
482
+ validIntervalIso: intervalISO,
483
+ validFrom: from,
484
+ validTo: to
485
+ };
486
+ return intervalResult;
487
+ };
488
+ const parseWithConfiguration = (bodyRaw, required = false) => {
489
+ const { configuration } = bodyRaw;
490
+ if (!configuration && required)
491
+ throw new InvalidRequestError("Configuration is required");
492
+ if (!configuration)
493
+ return;
494
+ return { configuration: typeof configuration === 'string' ? configuration : JSON.stringify(configuration) };
495
+ };
496
+ /**
497
+ * Parse body to place entity
498
+ * @param bodyRaw Request body content - can be anything
499
+ * @returns
500
+ */
501
+ const parseHasGeometry = (bodyRaw) => {
502
+ const { bbox, geometry, } = bodyRaw;
503
+ /**
504
+ * Convert bbox from CSV string to array of 4 coordinates
505
+ * @returns Parsed bounding box from CSV string
506
+ */
507
+ const bboxFromCSV = () => {
508
+ const bboxFromCSV = csvParseNumbers(bbox);
509
+ if (bboxFromCSV.length !== 4)
510
+ throw new InvalidRequestError("bbox must be an array of 4 numbers");
511
+ return bboxFromCSV;
512
+ };
513
+ const geometryResult = {
514
+ bbox: bbox ? bboxFromCSV() : [],
515
+ geometry: geometry ?? ""
516
+ };
517
+ return geometryResult;
518
+ };
519
+ /**
520
+ * Parses the input object and extracts the `url` property.
521
+ * If the `url` property is not present or is undefined, it returns `null` for `url`.
522
+ *
523
+ * @param bodyRaw - The raw input object that may contain a `url` property.
524
+ * @returns An object with a single `url` property, which is either the extracted value or `null`.
525
+ */
526
+ const parseHasUrl = (bodyRaw, isRequired = true) => {
527
+ const { url } = bodyRaw;
528
+ if (isRequired && !url)
529
+ throw new InvalidRequestError("Url is required for the node");
530
+ if (!url)
531
+ return;
532
+ return { url };
533
+ };
534
+ /**
535
+ * Parses the `specificName` property from the provided object and returns it wrapped in a `HasSpecificName` type.
536
+ *
537
+ * @param bodyRaw - The raw input object potentially containing the `specificName` property.
538
+ * @param isRequired - If `true`, throws an `InvalidRequestError` when `specificName` is missing. Defaults to `false`.
539
+ * @returns An object with the `specificName` property if present, or `undefined` if not required and missing.
540
+ * @throws {InvalidRequestError} If `isRequired` is `true` and `specificName` is not provided.
541
+ */
542
+ const parseHasSpecificName = (bodyRaw, isRequired = false) => {
543
+ const { specificName } = bodyRaw;
544
+ if (isRequired && !specificName)
545
+ throw new InvalidRequestError("Property specificName is required for the node");
546
+ if (!specificName)
547
+ return;
548
+ return { specificName };
549
+ };
550
+ /**
551
+ * Parses the `color` property from the provided `bodyRaw` object and returns it
552
+ * wrapped in an object if it exists. If the `isRequired` flag is set to `true`
553
+ * and the `color` property is missing, an error is thrown.
554
+ *
555
+ * @param bodyRaw - The raw input object containing the `color` property.
556
+ * @param isRequired - A boolean indicating whether the `color` property is required.
557
+ * Defaults to `false`.
558
+ * @returns An object containing the `color` property if it exists, or `undefined` if not required.
559
+ * @throws {InvalidRequestError} If `isRequired` is `true` and the `color` property is missing.
560
+ */
561
+ const parseWithColor = (bodyRaw, isRequired = false) => {
562
+ const { color } = bodyRaw;
563
+ if (isRequired && !color)
564
+ throw new InvalidRequestError("Property color is required for the node");
565
+ if (!color)
566
+ return;
567
+ return { color };
568
+ };
569
+ /**
570
+ * Parses the provided raw body object to extract unit and valueType properties.
571
+ * Ensures that the required properties are present if `isRequired` is set to true.
572
+ *
573
+ * @param bodyRaw - The raw input object containing the properties to parse.
574
+ * @param isRequired - A boolean indicating whether the `unit` and `valueType` properties are mandatory.
575
+ * Defaults to `false`.
576
+ * @returns An object containing the `unit` and `valueType` properties, or `null` if they are not provided.
577
+ * @throws {InvalidRequestError} If `isRequired` is true and either `unit` or `valueType` is missing.
578
+ */
579
+ const parseWithUnits = (bodyRaw, isRequired = false) => {
580
+ const { unit, valueType } = bodyRaw;
581
+ if (isRequired && (!unit || !valueType))
582
+ throw new InvalidRequestError("Properties unit and valueType are required for the node");
583
+ return { unit: unit ?? null, valueType: valueType ?? null };
584
+ };
585
+ /**
586
+ * Parse and validate the `documentId` property from a raw request body.
587
+ *
588
+ * Extracts `documentId` from `bodyRaw` and returns it as an object matching
589
+ * HasDocumentId, wrapped in the Unsure type. If `documentId` is missing or
590
+ * falsy, the function throws an InvalidRequestError.
591
+ *
592
+ * @param bodyRaw - The raw request body (e.g. parsed JSON) expected to contain `documentId`.
593
+ * @returns Unsure<HasDocumentId> — an object with the `documentId` property.
594
+ * @throws {InvalidRequestError} Thrown when `documentId` is not present on `bodyRaw`.
595
+ */
596
+ const parseHasDocumentId = (bodyRaw) => {
597
+ const { documentId } = bodyRaw;
598
+ if (!documentId)
599
+ throw new InvalidRequestError("Property documentId is required for the node");
600
+ return { documentId };
601
+ };
602
+ /**
603
+ * Parse timeseries information from a raw request body.
604
+ *
605
+ * Delegates interval parsing to `parseWithInterval(bodyRaw)` and then
606
+ * attaches the `step` value from the provided `bodyRaw` to the resulting
607
+ * timeseries object. The function does not mutate the input object.
608
+ *
609
+ * @param bodyRaw - Raw request payload (unknown/loose shape). Expected to
610
+ * contain whatever fields `parseWithInterval` requires and
611
+ * optionally a `step` property.
612
+ * @returns A `HasTimeseries` object composed of the interval-related fields
613
+ * returned by `parseWithInterval` plus the `step` property from
614
+ * `bodyRaw` (which may be `undefined` if not present).
615
+ * @throws Rethrows any errors produced by `parseWithInterval` when the input
616
+ * body is invalid for interval parsing.
617
+ */
618
+ const parseWithTimeseries = (bodyRaw) => {
619
+ const timeseriesIntervals = parseWithInterval(bodyRaw);
620
+ const { step } = bodyRaw;
621
+ if (!step)
622
+ throw new InvalidRequestError("Property step is required for timeseries datasource");
623
+ return { ...timeseriesIntervals, step };
624
+ };
625
+ /**
626
+ * Parses the `bands`, `bandNames`, and `bandPeriods` properties from the provided raw input object.
627
+ *
628
+ * - If `required` is `true`, throws an `InvalidRequestError` if any of the properties are missing.
629
+ * - Converts CSV strings to arrays:
630
+ * - `bands` is parsed as an array of numbers.
631
+ * - `bandNames` and `bandPeriods` are parsed as arrays of trimmed strings.
632
+ * - Returns an object containing any of the parsed properties that were present in the input.
633
+ *
634
+ * @param bodyRaw - The raw input object potentially containing `bands`, `bandNames`, and `bandPeriods` as CSV strings.
635
+ * @param required - If `true`, all three properties are required and an error is thrown if any are missing. Defaults to `false`.
636
+ * @returns An object with the parsed properties, or `undefined` if none are present.
637
+ * @throws {InvalidRequestError} If `required` is `true` and any property is missing.
638
+ */
639
+ const parseHasBands = (bodyRaw, required = false) => {
640
+ const { bands, bandNames, bandPeriods } = bodyRaw;
641
+ let result;
642
+ if (required && (!bands || !bandNames || !bandPeriods))
643
+ throw new InvalidRequestError("Bands, bandNames and bandPeriods are required for the node");
644
+ if (bands) {
645
+ result = result ?? {};
646
+ Object.assign(result, { bands: csvParseNumbers(bands) });
647
+ }
648
+ if (bandNames) {
649
+ result = result ?? {};
650
+ Object.assign(result, { bandNames: csvParseStrings(bandNames) });
651
+ }
652
+ if (bandPeriods) {
653
+ result = result ?? {};
654
+ Object.assign(result, { bandPeriods: csvParseStrings(bandPeriods) });
655
+ }
656
+ return result;
657
+ };
658
+ /**
659
+ * Parse single graph node from body entity
660
+ * @param bodyNodeEntity Entity from request body
661
+ * @returns Parsed object for specific node
662
+ */
663
+ const parseSinglePantherNode = (bodyNodeEntity) => {
664
+ // Parse basic node properties first
665
+ let node = parseBasicNodeFromBody(bodyNodeEntity);
666
+ // Parse additional properties for specific node types
667
+ // single for loop is used to avoid multiple labels array iterations
668
+ for (const label of node.labels) {
669
+ // If node is a Period, add interval information
670
+ if (label === UsedNodeLabels.Period)
671
+ node = { ...node, ...parseWithInterval(bodyNodeEntity) };
672
+ // If node is a Place, add geographic information
673
+ if (label === UsedNodeLabels.Place)
674
+ node = { ...node, ...parseHasGeometry(bodyNodeEntity) };
675
+ // If node is a Datasource or Application, add configuration when available
676
+ if (label === UsedNodeLabels.Datasource || label === UsedNodeLabels.Application) {
677
+ const parsedConfiguration = parseWithConfiguration(bodyNodeEntity, false);
678
+ node = parsedConfiguration ? { ...node, ...parsedConfiguration } : node;
679
+ }
680
+ // If node is a online Datasource, add URL information
681
+ const datasourcesWithUrl = [
682
+ UsedDatasourceLabels.COG,
683
+ UsedDatasourceLabels.WMS,
684
+ UsedDatasourceLabels.MVT,
685
+ UsedDatasourceLabels.WFS,
686
+ UsedDatasourceLabels.WMTS,
687
+ UsedDatasourceLabels.Geojson
688
+ ];
689
+ // If node is a Datasource with URL, add URL information
690
+ if (datasourcesWithUrl.includes(label)) {
691
+ const parsedUrl = parseHasUrl(bodyNodeEntity, true);
692
+ node = parsedUrl ? { ...node, ...parsedUrl } : node;
693
+ }
694
+ // If node is a Datasource with bands, add bands information
695
+ const datasourcesWithPossibleBands = [
696
+ UsedDatasourceLabels.COG,
697
+ ];
698
+ // If node is a Datasource can have bands, add them
699
+ if (datasourcesWithPossibleBands.includes(label)) {
700
+ const parsedBands = parseHasBands(bodyNodeEntity, false);
701
+ node = parsedBands ? { ...node, ...parsedBands } : node;
702
+ }
703
+ // If node is a Style, add specific name information
704
+ if (label === UsedNodeLabels.Style || label === UsedDatasourceLabels.MapStyle) {
705
+ const parsedSpecificName = parseHasSpecificName(bodyNodeEntity, true);
706
+ node = parsedSpecificName ? { ...node, ...parsedSpecificName } : node;
707
+ }
708
+ // If node is a Datasource with timeseries, add timeseries information
709
+ if (label === UsedDatasourceLabels.Timeseries) {
710
+ const parsedTimeseries = parseWithTimeseries(bodyNodeEntity);
711
+ node = { ...node, ...parsedTimeseries };
712
+ }
713
+ // If node is a Datasource with document ID, add document ID information
714
+ const datasourcesWithDocumentId = [
715
+ UsedDatasourceLabels.PostGIS,
716
+ UsedDatasourceLabels.Timeseries
717
+ ];
718
+ if (datasourcesWithDocumentId.includes(label)) {
719
+ const parsedDocumentId = parseHasDocumentId(bodyNodeEntity);
720
+ node = { ...node, ...parsedDocumentId };
721
+ }
722
+ // If node is an AreaTreeLevel, add level information
723
+ if (label === UsedNodeLabels.AreaTreeLevel)
724
+ node = { ...node, ...paseHasLevels(bodyNodeEntity) };
725
+ // If node is an Attribute, add color information and units
726
+ if (label === UsedNodeLabels.Attribute) {
727
+ const parsedColor = parseWithColor(bodyNodeEntity, false);
728
+ const parsedUnit = parseWithUnits(bodyNodeEntity, false);
729
+ // Add parsed unit if available
730
+ node = parsedUnit ? {
731
+ ...node,
732
+ ...parsedUnit
733
+ } : node;
734
+ // Add parsed color if available
735
+ node = parsedColor ? {
736
+ ...node,
737
+ ...parsedColor
738
+ } : node;
739
+ }
740
+ }
741
+ return node;
742
+ };
743
+ /**
744
+ * Parse array of graph nodes from request body
745
+ * @param body Array of graph nodes inside http request body
746
+ * @returns Array of parsed graph nodes in correct form
747
+ */
748
+ const parseParsePantherNodes = (body) => {
749
+ const nodeArray = body;
750
+ if (!_.isArray(nodeArray))
751
+ throw new InvalidRequestError("Request: Grah nodes must be an array");
752
+ return nodeArray.map(PantherEntity => parseSinglePantherNode(PantherEntity));
753
+ };
754
+ // TODO: cover by better testing
755
+
756
+ /**
757
+ * Parses a node object from the Arrows JSON format and converts it into a `PantherEntity`.
758
+ *
759
+ * Validates that the node's labels are arrays of supported enum values, and constructs
760
+ * a `PantherEntity` object with the appropriate properties. Throws an `InvalidRequestError`
761
+ * if the labels are not valid.
762
+ *
763
+ * @param node - The node object from the Arrows JSON to parse.
764
+ * @returns A `PantherEntity` object representing the parsed node.
765
+ * @throws {InvalidRequestError} If the node's labels are not an array of supported values.
766
+ */
767
+ const parseNodeFromArrows = (node) => {
768
+ const { labels, properties, id, caption } = node;
769
+ validateNodeLabels(labels);
770
+ const basicGraphResult = parseSinglePantherNode({
771
+ labels: labels,
772
+ key: properties.key ?? id ?? randomUUID(),
773
+ nameDisplay: caption ?? properties.nameDisplay ?? "",
774
+ ...properties
775
+ });
776
+ return basicGraphResult;
777
+ };
778
+ /**
779
+ * Parses an edge object from the Arrows format and converts it into a `GraphEdge`.
780
+ *
781
+ * @param edge - The edge object to parse, containing details about the graph edge.
782
+ * @returns A `GraphEdge` object containing the parsed edge nodes, label, and properties.
783
+ *
784
+ * @throws {InvalidRequestError} If the edge does not have a type (`label`).
785
+ * @throws {InvalidRequestError} If the edge type (`label`) is not supported.
786
+ * @throws {InvalidRequestError} If the edge does not have properties.
787
+ * @throws {InvalidRequestError} If the edge does not have `fromId` or `toId`.
788
+ * @throws {InvalidRequestError} If the `fromId` and `toId` are the same.
789
+ */
790
+ const parseEdgeFromArrows = (edge) => {
791
+ const { fromId: from, toId: to, type, properties } = edge;
792
+ // Determine the label, defaulting to "RelatedTo" if the type is invalid or not provided
793
+ const label = (typeof type === "string" && type.trim().length > 0)
794
+ ? type.trim()
795
+ : UsedEdgeLabels.RelatedTo;
796
+ // validate the edge properties
797
+ if (!isInEnum(label, UsedEdgeLabels))
798
+ throw new InvalidRequestError(`Graph edge type '${label}' is not supported`);
799
+ // edge must have a properties
800
+ if (!properties)
801
+ throw new InvalidRequestError(`Graph edge must have properties`);
802
+ // edge must have fromId and toId
803
+ if (!from || !to)
804
+ throw new InvalidRequestError(`Graph edge must have fromId and toId`);
805
+ if (from === to)
806
+ throw new InvalidRequestError(`Cannot connect two same keys in graph relation (${from} leads to ${to})`);
807
+ // prepare relation tuple
808
+ const result = [from, to];
809
+ // construct the parsed edge object
810
+ const parsedEdge = {
811
+ edgeNodes: result,
812
+ label,
813
+ properties
814
+ };
815
+ // return the parsed edge
816
+ return parsedEdge;
817
+ };
818
+ /**
819
+ * Parses a JSON object representing nodes and relationships (edges) from the Arrows JSON.
820
+ *
821
+ * @param body - The input JSON object to parse. Expected to contain `nodes` and `relationships` arrays.
822
+ * @returns An object containing parsed `nodes` and `edges` arrays.
823
+ * @throws {InvalidRequestError} If the input is not a valid object, or if required properties are missing or not arrays.
824
+ */
825
+ const parseArrowsJson = (body) => {
826
+ // Check if the body is a valid object
827
+ if (typeof body !== "object" || body === null)
828
+ throw new InvalidRequestError("Invalid JSON format");
829
+ // Check if the body contains the required properties
830
+ if (!("nodes" in body) || !("relationships" in body))
831
+ throw new InvalidRequestError("Invalid JSON format: Missing nodes or relationships");
832
+ // Check if nodes and relationships are arrays
833
+ if (!_.isArray(body.nodes) || !_.isArray(body.relationships))
834
+ throw new InvalidRequestError("Invalid JSON format: nodes and relationships must be arrays");
835
+ // Extract nodes and relationships from the body
836
+ const { nodes: rawNodes, relationships: rawEdges } = body;
837
+ // Define default values for nodes and edges
838
+ const nodes = rawNodes ?? [];
839
+ const edges = rawEdges ?? [];
840
+ // Parse nodes and edges using the defined functions
841
+ const parsedNodes = nodes.map((node) => parseNodeFromArrows(node));
842
+ const parsedEdges = edges.map((edge) => parseEdgeFromArrows(edge));
843
+ return {
844
+ nodes: parsedNodes,
845
+ edges: parsedEdges
846
+ };
847
+ };
848
+
849
+ const parseRichEdges = (body) => {
850
+ const parseSingleEdge = (edge) => {
851
+ const { label, fromKey, toKey, properties } = edge;
852
+ if (!label || typeof label !== "string")
853
+ throw new InvalidRequestError("Every graph edge must have string label");
854
+ if (!isInEnum(label, UsedEdgeLabels))
855
+ throw new InvalidRequestError(`Graph edge label is not allowed (${label}). Must be one of: ${enumValuesToString(UsedEdgeLabels)}`);
856
+ if (!fromKey || typeof fromKey !== "string")
857
+ throw new InvalidRequestError("Every graph edge must have string fromKey");
858
+ if (!toKey || typeof toKey !== "string")
859
+ throw new InvalidRequestError("Every graph edge must have string toKey");
860
+ if (fromKey === toKey)
861
+ throw new InvalidRequestError(`Cannot connect two same keys in graph edge (${fromKey})`);
862
+ const parsedEdge = {
863
+ label: label,
864
+ edgeNodes: [fromKey, toKey],
865
+ properties: properties || {}
866
+ };
867
+ return parsedEdge;
868
+ };
869
+ const edgesRaw = body;
870
+ if (!_.isArray(edgesRaw))
871
+ throw new InvalidRequestError("Graph edges must be an array of edges");
872
+ if (edgesRaw.length === 0)
873
+ throw new InvalidRequestError("Graph edges array must not be empty");
874
+ const parsedEdges = edgesRaw.map(edge => parseSingleEdge(edge));
875
+ return parsedEdges;
876
+ };
877
+ /**
878
+ * Parse body to graph relation
879
+ * @param body Body from request
880
+ * @returns Graph relation
881
+ */
882
+ const parseEqualEdges = (body) => {
883
+ const relations = body;
884
+ /**
885
+ * Check single edge relation and parse it
886
+ * @param edgeRelation
887
+ * @returns Parsed edge relation
888
+ */
889
+ const parseSingleEdgeRelation = (edgeRelation) => {
890
+ if (!_.isArray(edgeRelation))
891
+ throw new InvalidRequestError("Every graph relation must be two element string tuple [string, string]");
892
+ if (edgeRelation.length !== 2)
893
+ throw new InvalidRequestError("Every graph relation must be two element string tuple [string, string]");
894
+ if (edgeRelation[0] === edgeRelation[1])
895
+ throw new InvalidRequestError(`Cannot connect two same keys in graph relation (${edgeRelation[0]})`);
896
+ return edgeRelation;
897
+ };
898
+ if (!_.isArray(relations))
899
+ throw new InvalidRequestError("Graph edges must be an array of tuples");
900
+ const validatedGraphEdges = relations.map(edge => parseSingleEdgeRelation(edge));
901
+ return validatedGraphEdges;
902
+ };
903
+
904
+ export { AppLogger, AuthorizationError, InvalidRequestError, UsedDatasourceLabels, UsedEdgeLabels, UsedNodeLabels, UsedTimeseriesSteps, csvParseNumbers, csvParseStrings, enumCombineValuesToString, enumValuesToArray, enumValuesToString, epochToIsoFormat, filterEdgeByLabel, filterNodeByLabel, findEdgeByLabel, findNodeByLabel, flattenObject, hasIsoFormat, isInEnum, isoDateToTimestamp, isoIntervalToTimestamps, messageFromError, notEmptyString, nowTimestamp, nowTimestampIso, parseArrowsJson, parseEqualEdges, parseParsePantherNodes, parseRichEdges, parseSinglePantherNode, randomNumberBetween, removeDuplicitiesFromArray, sortStringArray, validateEdgeLabel, validateNodeLabels };
208
905
  //# sourceMappingURL=index.node.js.map