vrack2-core 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +33 -4
  2. package/docs/Bootstrap.md +77 -0
  3. package/docs/Container.md +124 -0
  4. package/docs/Device.md +272 -0
  5. package/docs/FastStart.md +111 -0
  6. package/docs/Structure.md +148 -0
  7. package/lib/Bootstrap.d.ts +79 -0
  8. package/lib/Bootstrap.js +103 -0
  9. package/lib/Container.d.ts +202 -6
  10. package/lib/Container.js +295 -27
  11. package/lib/IServiceStructure.d.ts +8 -0
  12. package/lib/IStructureDevice.d.ts +5 -0
  13. package/lib/ImportManager.d.ts +85 -3
  14. package/lib/ImportManager.js +122 -16
  15. package/lib/MainProcess.d.ts +30 -3
  16. package/lib/MainProcess.js +28 -6
  17. package/lib/Utility.d.ts +15 -21
  18. package/lib/Utility.js +40 -40
  19. package/lib/actions/Action.d.ts +10 -0
  20. package/lib/actions/Action.js +10 -0
  21. package/lib/actions/BasicAction.d.ts +60 -0
  22. package/lib/actions/BasicAction.js +62 -0
  23. package/lib/actions/GlobalAction.d.ts +5 -0
  24. package/lib/actions/GlobalAction.js +5 -0
  25. package/lib/actions/IAction.d.ts +7 -0
  26. package/lib/actions/ILocalAction.d.ts +7 -0
  27. package/lib/boot/BootClass.d.ts +93 -0
  28. package/lib/boot/BootClass.js +101 -0
  29. package/lib/boot/DeviceFileStorage.d.ts +38 -0
  30. package/lib/boot/DeviceFileStorage.js +112 -0
  31. package/lib/boot/DeviceManager.d.ts +190 -0
  32. package/lib/boot/DeviceManager.js +311 -0
  33. package/lib/boot/DeviceMetrics.d.ts +82 -0
  34. package/lib/boot/DeviceMetrics.js +128 -0
  35. package/lib/boot/StructureStorage.d.ts +59 -0
  36. package/lib/boot/StructureStorage.js +125 -0
  37. package/lib/errors/CoreError.d.ts +42 -25
  38. package/lib/errors/CoreError.js +44 -24
  39. package/lib/errors/ErrorManager.d.ts +18 -20
  40. package/lib/errors/ErrorManager.js +23 -22
  41. package/lib/index.d.ts +20 -4
  42. package/lib/index.js +28 -4
  43. package/lib/metrics/BasicMetric.d.ts +49 -0
  44. package/lib/metrics/BasicMetric.js +79 -0
  45. package/lib/metrics/IMetricSettings.d.ts +32 -0
  46. package/lib/metrics/IMetricSettings.js +2 -0
  47. package/lib/metrics/IvMs.d.ts +9 -0
  48. package/lib/metrics/IvMs.js +22 -0
  49. package/lib/metrics/IvS.d.ts +9 -0
  50. package/lib/metrics/IvS.js +22 -0
  51. package/lib/metrics/IvUs.d.ts +9 -0
  52. package/lib/metrics/IvUs.js +22 -0
  53. package/lib/metrics/Metric.d.ts +17 -0
  54. package/lib/metrics/Metric.js +27 -0
  55. package/lib/ports/BasicPort.d.ts +39 -0
  56. package/lib/ports/BasicPort.js +39 -0
  57. package/lib/ports/ILocalPort.d.ts +7 -0
  58. package/lib/ports/IPort.d.ts +7 -0
  59. package/lib/ports/Port.d.ts +10 -0
  60. package/lib/ports/Port.js +10 -0
  61. package/lib/ports/ReturnPort.d.ts +5 -0
  62. package/lib/ports/ReturnPort.js +5 -0
  63. package/lib/service/Device.d.ts +213 -78
  64. package/lib/service/Device.js +185 -83
  65. package/lib/service/DeviceConnect.d.ts +4 -8
  66. package/lib/service/DeviceConnect.js +4 -8
  67. package/lib/service/DevicePort.d.ts +15 -6
  68. package/lib/service/DevicePort.js +29 -12
  69. package/lib/service/IDeviceEvent.d.ts +4 -1
  70. package/lib/validator/IValidationProblem.d.ts +7 -0
  71. package/lib/validator/IValidationRule.d.ts +12 -0
  72. package/lib/validator/IValidationSubrule.d.ts +2 -0
  73. package/lib/validator/Rule.d.ts +6 -2
  74. package/lib/validator/Rule.js +12 -2
  75. package/lib/validator/Validator.d.ts +48 -3
  76. package/lib/validator/Validator.js +70 -18
  77. package/lib/validator/types/AnyType.d.ts +17 -0
  78. package/lib/validator/types/AnyType.js +34 -0
  79. package/lib/validator/types/ArrayType.d.ts +37 -4
  80. package/lib/validator/types/ArrayType.js +42 -6
  81. package/lib/validator/types/BasicType.d.ts +67 -7
  82. package/lib/validator/types/BasicType.js +74 -8
  83. package/lib/validator/types/BooleanType.d.ts +23 -0
  84. package/lib/validator/types/BooleanType.js +47 -0
  85. package/lib/validator/types/FunctionType.d.ts +17 -0
  86. package/lib/validator/types/FunctionType.js +38 -0
  87. package/lib/validator/types/NumberType.d.ts +40 -5
  88. package/lib/validator/types/NumberType.js +53 -14
  89. package/lib/validator/types/ObjectType.d.ts +32 -5
  90. package/lib/validator/types/ObjectType.js +42 -8
  91. package/lib/validator/types/StringType.d.ts +30 -5
  92. package/lib/validator/types/StringType.js +33 -7
  93. package/package.json +15 -14
  94. package/src/Bootstrap.ts +122 -0
  95. package/src/Container.ts +411 -43
  96. package/src/IServiceStructure.ts +9 -0
  97. package/src/IStructureDevice.ts +5 -0
  98. package/src/ImportManager.ts +119 -11
  99. package/src/MainProcess.ts +53 -8
  100. package/src/Utility.ts +35 -36
  101. package/src/actions/Action.ts +12 -0
  102. package/src/actions/BasicAction.ts +63 -0
  103. package/src/actions/GlobalAction.ts +5 -0
  104. package/src/actions/IAction.ts +7 -0
  105. package/src/actions/ILocalAction.ts +7 -0
  106. package/src/boot/BootClass.ts +117 -0
  107. package/src/boot/DeviceFileStorage.ts +96 -0
  108. package/src/boot/DeviceManager.ts +346 -0
  109. package/src/boot/DeviceMetrics.ts +129 -0
  110. package/src/boot/StructureStorage.ts +108 -0
  111. package/src/errors/CoreError.ts +52 -26
  112. package/src/errors/ErrorManager.ts +46 -33
  113. package/src/index.ts +30 -6
  114. package/src/metrics/BasicMetric.ts +84 -0
  115. package/src/metrics/IMetricSettings.ts +38 -0
  116. package/src/metrics/IvMs.ts +18 -0
  117. package/src/metrics/IvS.ts +18 -0
  118. package/src/metrics/IvUs.ts +17 -0
  119. package/src/metrics/Metric.ts +25 -0
  120. package/src/ports/BasicPort.ts +39 -0
  121. package/src/ports/ILocalPort.ts +7 -0
  122. package/src/ports/IPort.ts +7 -0
  123. package/src/ports/Port.ts +11 -1
  124. package/src/ports/ReturnPort.ts +5 -0
  125. package/src/service/Device.ts +234 -103
  126. package/src/service/DeviceConnect.ts +4 -8
  127. package/src/service/DevicePort.ts +30 -11
  128. package/src/service/IDeviceEvent.ts +4 -1
  129. package/src/validator/IValidationProblem.ts +7 -0
  130. package/src/validator/IValidationRule.ts +12 -0
  131. package/src/validator/IValidationSubrule.ts +3 -0
  132. package/src/validator/Rule.ts +16 -2
  133. package/src/validator/Validator.ts +74 -23
  134. package/src/validator/types/AnyType.ts +32 -0
  135. package/src/validator/types/ArrayType.ts +43 -7
  136. package/src/validator/types/BasicType.ts +78 -9
  137. package/src/validator/types/BooleanType.ts +49 -0
  138. package/src/validator/types/FunctionType.ts +39 -0
  139. package/src/validator/types/NumberType.ts +53 -15
  140. package/src/validator/types/ObjectType.ts +52 -14
  141. package/src/validator/types/StringType.ts +34 -10
  142. package/docs/RU-README.md +0 -6
  143. package/lib/DeviceManager.d.ts +0 -32
  144. package/lib/DeviceManager.js +0 -143
  145. package/lib/test.d.ts +0 -1
  146. package/lib/test.js +0 -58
  147. package/src/DeviceManager.ts +0 -124
  148. package/src/test.ts +0 -82
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright © 2024 Boris Bobylev. All rights reserved.
4
+ * Licensed under the Apache License, Version 2.0
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ const BootClass_1 = __importDefault(require("./BootClass"));
20
+ const Rule_1 = __importDefault(require("../validator/Rule"));
21
+ const fs_1 = require("fs");
22
+ const path_1 = __importDefault(require("path"));
23
+ const ImportManager_1 = __importDefault(require("../ImportManager"));
24
+ const ErrorManager_1 = __importDefault(require("../errors/ErrorManager"));
25
+ ErrorManager_1.default.register('StructureStorage', 'FKb5raEUDFgU', 'SS_STRUCT_NOT_FOUND', 'Structure ID not found', {
26
+ id: Rule_1.default.string().require().example('vrack').description('Structure id')
27
+ });
28
+ /**
29
+ * A boot class for storing the structure of a container.
30
+ *
31
+ * When a container is created, it is assigned a unique identifier.
32
+ * This identifier is used as parameters of methods.
33
+ *
34
+ * @see getById
35
+ * @see updateById
36
+ *
37
+ * When the container is loaded it calls “beforeLoaded”.
38
+ * At this point it updates the structure from disk to the structure
39
+ * of the container itself and writes the changes
40
+ *
41
+ * @see beforeLoadedUpdate
42
+ *
43
+ * */
44
+ class StructureStorage extends BootClass_1.default {
45
+ checkOptions() {
46
+ return {
47
+ structureDir: Rule_1.default.string().require().default('./structure')
48
+ };
49
+ }
50
+ process() {
51
+ if (!(0, fs_1.existsSync)(this.options.structureDir))
52
+ (0, fs_1.mkdirSync)(this.options.structureDir, { recursive: true });
53
+ this.Container.on('beforeLoaded', this.beforeLoadedUpdate.bind(this));
54
+ }
55
+ /**
56
+ * Updates the structure on disk using the structure of
57
+ * the container itself when it is loaded
58
+ *
59
+ *
60
+ * @see StructureStorage.process
61
+ */
62
+ beforeLoadedUpdate() {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ const fp = this.makeFilePath(this.Container.id);
65
+ let structure = {};
66
+ try {
67
+ if ((0, fs_1.existsSync)(fp))
68
+ structure = ImportManager_1.default.importJSON(fp);
69
+ const cStruct = yield this.Container.getStructure();
70
+ this.updateStructure(cStruct, structure, this.Container.id);
71
+ }
72
+ catch (error) {
73
+ this.error(error);
74
+ }
75
+ });
76
+ }
77
+ /**
78
+ * Returns structure by container identifier
79
+ *
80
+ * @param id Container ID
81
+ */
82
+ getById(id) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const fp = this.makeFilePath(id);
85
+ if (!(0, fs_1.existsSync)(fp))
86
+ throw ErrorManager_1.default.make('SS_STRUCT_NOT_FOUND', { id });
87
+ return ImportManager_1.default.importJSON(fp);
88
+ });
89
+ }
90
+ /**
91
+ * Updating the container structure
92
+ *
93
+ * @param id Container ID
94
+ * @param structure updated container structure object
95
+ */
96
+ updateById(id, structure) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ const cStruct = yield this.getById(id);
99
+ this.updateStructure(cStruct, structure, id);
100
+ });
101
+ }
102
+ /**
103
+ * Updates the display structure parameter from the file structure
104
+ *
105
+ * @param cStruct now container structure
106
+ * @param structure new structure
107
+ */
108
+ updateStructure(cStruct, structure, id) {
109
+ for (const dID in cStruct) {
110
+ if (structure[dID] && structure[dID].display)
111
+ cStruct[dID].display = structure[dID].display;
112
+ }
113
+ const fp = this.makeFilePath(id);
114
+ (0, fs_1.writeFileSync)(fp, JSON.stringify(cStruct));
115
+ }
116
+ /**
117
+ * Forms the path to the structure file by its identifier
118
+ *
119
+ * @param id Container ID
120
+ */
121
+ makeFilePath(id) {
122
+ return path_1.default.join(this.options.structureDir, id + '.json');
123
+ }
124
+ }
125
+ exports.default = StructureStorage;
@@ -1,52 +1,69 @@
1
1
  /**
2
- * Базовый класс для реализаиции ошибок с возможностью
3
- * импортирования и экспортирования классов ошибок для
4
- * клиент-серверных операций.
2
+ * Base class for error realization with the ability to
3
+ * import and export error classes for client-server operations.
5
4
  *
6
- * В VRack очень много передается по сети в виде JSON. Поскольку
7
- * в чистом виде ошибки не преобрзауются в JSON, были сделаны методы
8
- * для экспортирования и импортирования с сохранения основных важных свойств.
5
+ * In VRack, a lot of things are transmitted over the network as JSON.
6
+ * Since pure errors are not converted to JSON, methods were made to export and
7
+ * import them while preserving the main important properties.
9
8
  *
10
- * Если импортируемая ошибка имеет свойства которых нет в базовом классе, буду добавлены.
11
- * Для получения неизвестных свойств можно воспользоватся функцией (для typescript) getUnknownProperty
12
- *
13
- * Для работы с ошибками VRack рекомендуется использовать ErrorManager
9
+ * If the imported error has properties that are not in the base class,
10
+ * they will be added. To get unknown properties you can use the function
11
+ * (for typescript) getUnknownProperty.
14
12
  *
15
13
  */
16
14
  declare class CoreError extends Error {
17
- /** Флаг того что ошибка пренадлежит VRack */
15
+ /** Flag that the error belongs to VRack */
18
16
  vError: boolean;
19
- /** Код ошибки VRack */
17
+ /** Error code */
20
18
  vCode: string;
21
- /** Кородкий код VRack */
19
+ /** Short code */
22
20
  vShort: string;
23
- /** Список дополнительных параметров */
21
+ /** List of additional parameters */
24
22
  vAdd: Array<string>;
25
- /** */
26
- vAddErrors: Array<CoreError>;
23
+ /** Nested errors */
24
+ vAddErrors: Array<Error>;
27
25
  constructor(name: string, message: string, code: string, short: string);
28
26
  /**
29
- * Импортирует ошибку пришедшую по сети в виде JSON объекта
30
- * На всякий случай использует objectify для приходящего объекта
27
+ * Sets the stacktrace of the error above
28
+ * It is necessary for the stacktrace to refer to the
29
+ * required file and not to ErrorManager
30
+ *
31
+ * @param err Error
32
+ * @example Example of assigning a more correct path to the file where the error occurred
33
+ * ```
34
+ * ErrorManager.make('EM_CODE_NOT_FOUND').setTrace(new Error())
35
+ * ```
36
+ */
37
+ setTrace(err: Error): this;
38
+ /**
39
+ * Imports an error that came over the network as a JSON object
40
+ * Uses objectify for the incoming object just in case
31
41
  *
32
42
  * @returns {CoreError} this после модификации
33
43
  */
34
44
  import(error: any): this;
35
45
  /**
36
- * Возвращает объект для передачи его по сети с предварительным
37
- * преобразованием в JSON
46
+ * Returns an object to be transmitted over the network
47
+ * with preliminary conversion to JSON
48
+ *
49
+ * @see objectify
38
50
  */
39
51
  export(): any;
40
- add(err: CoreError): this;
41
52
  /**
42
- * Для Typescript используется для получения неизвестного
43
- * свойства экземпляра после импорта пришедшей ошибки
53
+ * Add nested error
54
+ *
55
+ * @param err Nested error
56
+ */
57
+ add(err: Error): this;
58
+ /**
59
+ * For Typescript it is used to retrieve an unknown
60
+ * instance property after importing an incoming error
44
61
  */
45
62
  getUnknownProperty(field: string): any | undefined;
46
63
  /**
47
- * Возвращает объект для передачи его по сети
64
+ * Returns an object to be transmitted over the network
48
65
  *
49
- * @param {any} error Ошибка для преобразования в объект
66
+ * @param {any} error Error for conversion to an object
50
67
  * */
51
68
  static objectify(error: any): any;
52
69
  }
@@ -1,44 +1,57 @@
1
1
  "use strict";
2
2
  /*
3
- * Copyright © 2022 Boris Bobylev. All rights reserved.
3
+ * Copyright © 2024 Boris Bobylev. All rights reserved.
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  /**
8
- * Базовый класс для реализаиции ошибок с возможностью
9
- * импортирования и экспортирования классов ошибок для
10
- * клиент-серверных операций.
8
+ * Base class for error realization with the ability to
9
+ * import and export error classes for client-server operations.
11
10
  *
12
- * В VRack очень много передается по сети в виде JSON. Поскольку
13
- * в чистом виде ошибки не преобрзауются в JSON, были сделаны методы
14
- * для экспортирования и импортирования с сохранения основных важных свойств.
11
+ * In VRack, a lot of things are transmitted over the network as JSON.
12
+ * Since pure errors are not converted to JSON, methods were made to export and
13
+ * import them while preserving the main important properties.
15
14
  *
16
- * Если импортируемая ошибка имеет свойства которых нет в базовом классе, буду добавлены.
17
- * Для получения неизвестных свойств можно воспользоватся функцией (для typescript) getUnknownProperty
18
- *
19
- * Для работы с ошибками VRack рекомендуется использовать ErrorManager
15
+ * If the imported error has properties that are not in the base class,
16
+ * they will be added. To get unknown properties you can use the function
17
+ * (for typescript) getUnknownProperty.
20
18
  *
21
19
  */
22
20
  class CoreError extends Error {
23
21
  constructor(name, message, code, short) {
24
22
  super(message);
25
- /** Флаг того что ошибка пренадлежит VRack */
23
+ /** Flag that the error belongs to VRack */
26
24
  this.vError = true;
27
- /** Код ошибки VRack */
25
+ /** Error code */
28
26
  this.vCode = "";
29
- /** Кородкий код VRack */
27
+ /** Short code */
30
28
  this.vShort = "";
31
- /** Список дополнительных параметров */
29
+ /** List of additional parameters */
32
30
  this.vAdd = [];
33
- /** */
31
+ /** Nested errors */
34
32
  this.vAddErrors = [];
35
33
  this.name = name;
36
34
  this.vCode = code;
37
35
  this.vShort = short;
38
36
  }
39
37
  /**
40
- * Импортирует ошибку пришедшую по сети в виде JSON объекта
41
- * На всякий случай использует objectify для приходящего объекта
38
+ * Sets the stacktrace of the error above
39
+ * It is necessary for the stacktrace to refer to the
40
+ * required file and not to ErrorManager
41
+ *
42
+ * @param err Error
43
+ * @example Example of assigning a more correct path to the file where the error occurred
44
+ * ```
45
+ * ErrorManager.make('EM_CODE_NOT_FOUND').setTrace(new Error())
46
+ * ```
47
+ */
48
+ setTrace(err) {
49
+ this.stack = err.stack;
50
+ return this;
51
+ }
52
+ /**
53
+ * Imports an error that came over the network as a JSON object
54
+ * Uses objectify for the incoming object just in case
42
55
  *
43
56
  * @returns {CoreError} this после модификации
44
57
  */
@@ -48,28 +61,35 @@ class CoreError extends Error {
48
61
  return this;
49
62
  }
50
63
  /**
51
- * Возвращает объект для передачи его по сети с предварительным
52
- * преобразованием в JSON
64
+ * Returns an object to be transmitted over the network
65
+ * with preliminary conversion to JSON
66
+ *
67
+ * @see objectify
53
68
  */
54
69
  export() {
55
70
  return CoreError.objectify(this);
56
71
  }
72
+ /**
73
+ * Add nested error
74
+ *
75
+ * @param err Nested error
76
+ */
57
77
  add(err) {
58
78
  this.vAddErrors.push(CoreError.objectify(err));
59
79
  return this;
60
80
  }
61
81
  /**
62
- * Для Typescript используется для получения неизвестного
63
- * свойства экземпляра после импорта пришедшей ошибки
82
+ * For Typescript it is used to retrieve an unknown
83
+ * instance property after importing an incoming error
64
84
  */
65
85
  getUnknownProperty(field) {
66
86
  const dynamicKey = field;
67
87
  return this[dynamicKey];
68
88
  }
69
89
  /**
70
- * Возвращает объект для передачи его по сети
90
+ * Returns an object to be transmitted over the network
71
91
  *
72
- * @param {any} error Ошибка для преобразования в объект
92
+ * @param {any} error Error for conversion to an object
73
93
  * */
74
94
  static objectify(error) {
75
95
  const result = {};
@@ -1,45 +1,43 @@
1
1
  import BasicType from "../validator/types/BasicType";
2
2
  import CoreError from "./CoreError";
3
3
  /**
4
- * Класс является точкой входа для инициализации исключений
5
- *
6
- * Было принято решение вместо кучи мелких однотипных файлов сделать один класс
7
- * со стандартным функционалом
4
+ * A simple class for creating errors.
5
+ * This centralized class is useful because you can find out t
6
+ * he list of all registered errors and which group/component they belong to.
8
7
  */
9
8
  declare class ErrorManager {
9
+ /**
10
+ * List of registered errors
11
+ */
10
12
  private registeredList;
11
13
  /**
12
- * Регистрирует тип ошибки компонента
13
- *
14
- * Перед тем как менеджер ошибок может создать ошибки, необходимо зарегистрировать ее тип.
15
- *
16
- * @param {string} name Название компонента
17
- * @param {string} code Код ошибки
18
- * @param {string} short Короткий код ошибки
19
- * @param {string} description Описание ошибки
14
+ * Error registration. An error must be registered before creating it
20
15
  *
16
+ * @param name Property for error grouping
17
+ * @param code Unique random string code ID
18
+ * @param short Readable unique identifier
19
+ * @param description Error string (description)
21
20
  */
22
21
  register(name: string, code: string, short: string, description: string, rules?: {
23
22
  [key: string]: BasicType;
24
23
  }): void;
25
24
  /**
26
- * Создание ошибки
27
- *
28
- *
25
+ * Creating an instance of an error
29
26
  *
30
- * @param {string} short
27
+ * @param short
28
+ * @param additional
31
29
  */
32
30
  make(short: string, additional?: {}): CoreError;
33
31
  /**
34
- * Преобразует обычную ошибку в ошибку VRack
32
+ * Converts a normal error to a VRack error
35
33
  *
36
- * @param {Error} error Ошибка для преобразования
34
+ * @param error Ошибка для преобразования
37
35
  */
38
36
  convert(error: any): any;
39
37
  /**
40
- * Возвращает тип ошибки или null
38
+ * Searches for an error by code or short
41
39
  *
42
- * @param {string} short Короткий код ошибки или код ошибки поиска
40
+ * @param short Short error code or search error code
43
41
  */
44
42
  private getRegistered;
45
43
  }
@@ -9,25 +9,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
10
  const CoreError_1 = __importDefault(require("./CoreError"));
11
11
  /**
12
- * Класс является точкой входа для инициализации исключений
13
- *
14
- * Было принято решение вместо кучи мелких однотипных файлов сделать один класс
15
- * со стандартным функционалом
12
+ * A simple class for creating errors.
13
+ * This centralized class is useful because you can find out t
14
+ * he list of all registered errors and which group/component they belong to.
16
15
  */
17
16
  class ErrorManager {
18
17
  constructor() {
18
+ /**
19
+ * List of registered errors
20
+ */
19
21
  this.registeredList = [];
20
22
  }
21
23
  /**
22
- * Регистрирует тип ошибки компонента
23
- *
24
- * Перед тем как менеджер ошибок может создать ошибки, необходимо зарегистрировать ее тип.
25
- *
26
- * @param {string} name Название компонента
27
- * @param {string} code Код ошибки
28
- * @param {string} short Короткий код ошибки
29
- * @param {string} description Описание ошибки
24
+ * Error registration. An error must be registered before creating it
30
25
  *
26
+ * @param name Property for error grouping
27
+ * @param code Unique random string code ID
28
+ * @param short Readable unique identifier
29
+ * @param description Error string (description)
31
30
  */
32
31
  register(name, code, short, description, rules = {}) {
33
32
  const reg1 = this.getRegistered(code);
@@ -38,24 +37,27 @@ class ErrorManager {
38
37
  this.registeredList.push(nr);
39
38
  }
40
39
  /**
41
- * Создание ошибки
42
- *
40
+ * Creating an instance of an error
43
41
  *
44
- *
45
- * @param {string} short
42
+ * @param short
43
+ * @param additional
46
44
  */
47
45
  make(short, additional = {}) {
48
46
  const reg = this.getRegistered(short);
49
47
  if (reg === null)
50
48
  throw this.make('EM_CODE_NOT_FOUND');
51
49
  const ne = new CoreError_1.default(reg.name, reg.description, reg.code, reg.short);
50
+ // Убираем из стека вызовы ErrorManager.make()
51
+ if (typeof Error.captureStackTrace === 'function') {
52
+ Error.captureStackTrace(ne, this.make);
53
+ }
52
54
  ne.vAdd = Object.keys(additional);
53
55
  return Object.assign(ne, additional);
54
56
  }
55
57
  /**
56
- * Преобразует обычную ошибку в ошибку VRack
58
+ * Converts a normal error to a VRack error
57
59
  *
58
- * @param {Error} error Ошибка для преобразования
60
+ * @param error Ошибка для преобразования
59
61
  */
60
62
  convert(error) {
61
63
  if (error.vError)
@@ -65,15 +67,14 @@ class ErrorManager {
65
67
  return ne;
66
68
  }
67
69
  /**
68
- * Возвращает тип ошибки или null
70
+ * Searches for an error by code or short
69
71
  *
70
- * @param {string} short Короткий код ошибки или код ошибки поиска
72
+ * @param short Short error code or search error code
71
73
  */
72
74
  getRegistered(short) {
73
- for (const registered of this.registeredList) {
75
+ for (const registered of this.registeredList)
74
76
  if (registered.code === short || registered.short === short)
75
77
  return registered;
76
- }
77
78
  return null;
78
79
  }
79
80
  }
package/lib/index.d.ts CHANGED
@@ -2,18 +2,34 @@ export { default as ErrorManager } from './errors/ErrorManager';
2
2
  export { default as CoreError } from './errors/CoreError';
3
3
  export { default as Rule } from './validator/Rule';
4
4
  export { default as Validator } from './validator/Validator';
5
- export { default as IValidationProblem } from './validator/IValidationProblem';
6
- export { default as IValidationRule } from './validator/IValidationRule';
7
- export { default as IValidationSubrule } from './validator/IValidationSubrule';
8
5
  export { default as ImportManager } from './ImportManager';
9
- export { default as DeviceManager } from './DeviceManager';
10
6
  export { default as Container } from './Container';
11
7
  export { default as MainProcess } from './MainProcess';
8
+ export { default as Bootstrap } from './Bootstrap';
9
+ export { default as BootClass } from './boot/BootClass';
10
+ export { default as DeviceFileStorage } from './boot/DeviceFileStorage';
11
+ export { default as DeviceManager } from './boot/DeviceManager';
12
+ export { default as StructureStorage } from './boot/StructureStorage';
13
+ export { default as DeviceMetrics } from './boot/DeviceMetrics';
12
14
  export { default as Action } from './actions/Action';
13
15
  export { default as Device } from './service/Device';
14
16
  export { default as DeviceConnect } from './service/DeviceConnect';
15
17
  export { default as DevicePort } from './service/DevicePort';
16
18
  export { default as Port } from './ports/Port';
19
+ export { default as Metric } from './metrics/Metric';
20
+ export { default as BasicPort } from './ports/BasicPort';
21
+ export { default as BasicType } from './validator/types/BasicType';
22
+ export { default as BasicMetric } from './metrics/BasicMetric';
23
+ export { default as BasicAction } from './actions/BasicAction';
24
+ export { default as IMetricSettings } from './metrics/IMetricSettings';
25
+ export { default as IPort } from './ports/IPort';
26
+ export { default as IDeviceEvent } from './service/IDeviceEvent';
27
+ export { default as IValidationProblem } from './validator/IValidationProblem';
28
+ export { default as IValidationRule } from './validator/IValidationRule';
29
+ export { default as IValidationSubrule } from './validator/IValidationSubrule';
30
+ export { default as IServiceStructure } from './IServiceStructure';
31
+ export { default as IStructureDevice } from './IStructureDevice';
32
+ export { StorageTypes } from 'vrack-db';
17
33
  export * from './service/Device';
18
34
  export * from './service/DeviceConnect';
19
35
  export * from './service/DevicePort';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  /*
3
- * Copyright © 2022 Boris Bobylev. All rights reserved.
3
+ * Copyright © 2024 Boris Bobylev. All rights reserved.
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  */
6
6
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
@@ -21,7 +21,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
21
21
  return (mod && mod.__esModule) ? mod : { "default": mod };
22
22
  };
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.Port = exports.DevicePort = exports.DeviceConnect = exports.Device = exports.Action = exports.MainProcess = exports.Container = exports.DeviceManager = exports.ImportManager = exports.Validator = exports.Rule = exports.CoreError = exports.ErrorManager = void 0;
24
+ exports.StorageTypes = exports.BasicAction = exports.BasicMetric = exports.BasicType = exports.BasicPort = exports.Metric = exports.Port = exports.DevicePort = exports.DeviceConnect = exports.Device = exports.Action = exports.DeviceMetrics = exports.StructureStorage = exports.DeviceManager = exports.DeviceFileStorage = exports.BootClass = exports.Bootstrap = exports.MainProcess = exports.Container = exports.ImportManager = exports.Validator = exports.Rule = exports.CoreError = exports.ErrorManager = void 0;
25
25
  /* ---------------- VALIDATOR EXPORT ------------------- */
26
26
  var ErrorManager_1 = require("./errors/ErrorManager");
27
27
  Object.defineProperty(exports, "ErrorManager", { enumerable: true, get: function () { return __importDefault(ErrorManager_1).default; } });
@@ -34,12 +34,24 @@ Object.defineProperty(exports, "Validator", { enumerable: true, get: function ()
34
34
  /* ---------------- BASE OF VRACK ------------------- */
35
35
  var ImportManager_1 = require("./ImportManager");
36
36
  Object.defineProperty(exports, "ImportManager", { enumerable: true, get: function () { return __importDefault(ImportManager_1).default; } });
37
- var DeviceManager_1 = require("./DeviceManager");
38
- Object.defineProperty(exports, "DeviceManager", { enumerable: true, get: function () { return __importDefault(DeviceManager_1).default; } });
39
37
  var Container_1 = require("./Container");
40
38
  Object.defineProperty(exports, "Container", { enumerable: true, get: function () { return __importDefault(Container_1).default; } });
41
39
  var MainProcess_1 = require("./MainProcess");
42
40
  Object.defineProperty(exports, "MainProcess", { enumerable: true, get: function () { return __importDefault(MainProcess_1).default; } });
41
+ /* ---------------- BOOTSTRAP ------------------- */
42
+ var Bootstrap_1 = require("./Bootstrap");
43
+ Object.defineProperty(exports, "Bootstrap", { enumerable: true, get: function () { return __importDefault(Bootstrap_1).default; } });
44
+ var BootClass_1 = require("./boot/BootClass");
45
+ Object.defineProperty(exports, "BootClass", { enumerable: true, get: function () { return __importDefault(BootClass_1).default; } });
46
+ var DeviceFileStorage_1 = require("./boot/DeviceFileStorage");
47
+ Object.defineProperty(exports, "DeviceFileStorage", { enumerable: true, get: function () { return __importDefault(DeviceFileStorage_1).default; } });
48
+ var DeviceManager_1 = require("./boot/DeviceManager");
49
+ Object.defineProperty(exports, "DeviceManager", { enumerable: true, get: function () { return __importDefault(DeviceManager_1).default; } });
50
+ var StructureStorage_1 = require("./boot/StructureStorage");
51
+ Object.defineProperty(exports, "StructureStorage", { enumerable: true, get: function () { return __importDefault(StructureStorage_1).default; } });
52
+ var DeviceMetrics_1 = require("./boot/DeviceMetrics");
53
+ Object.defineProperty(exports, "DeviceMetrics", { enumerable: true, get: function () { return __importDefault(DeviceMetrics_1).default; } });
54
+ /* ---------------- INTERNAL SERVICE ------------------- */
43
55
  var Action_1 = require("./actions/Action");
44
56
  Object.defineProperty(exports, "Action", { enumerable: true, get: function () { return __importDefault(Action_1).default; } });
45
57
  var Device_1 = require("./service/Device");
@@ -50,6 +62,18 @@ var DevicePort_1 = require("./service/DevicePort");
50
62
  Object.defineProperty(exports, "DevicePort", { enumerable: true, get: function () { return __importDefault(DevicePort_1).default; } });
51
63
  var Port_1 = require("./ports/Port");
52
64
  Object.defineProperty(exports, "Port", { enumerable: true, get: function () { return __importDefault(Port_1).default; } });
65
+ var Metric_1 = require("./metrics/Metric");
66
+ Object.defineProperty(exports, "Metric", { enumerable: true, get: function () { return __importDefault(Metric_1).default; } });
67
+ var BasicPort_1 = require("./ports/BasicPort");
68
+ Object.defineProperty(exports, "BasicPort", { enumerable: true, get: function () { return __importDefault(BasicPort_1).default; } });
69
+ var BasicType_1 = require("./validator/types/BasicType");
70
+ Object.defineProperty(exports, "BasicType", { enumerable: true, get: function () { return __importDefault(BasicType_1).default; } });
71
+ var BasicMetric_1 = require("./metrics/BasicMetric");
72
+ Object.defineProperty(exports, "BasicMetric", { enumerable: true, get: function () { return __importDefault(BasicMetric_1).default; } });
73
+ var BasicAction_1 = require("./actions/BasicAction");
74
+ Object.defineProperty(exports, "BasicAction", { enumerable: true, get: function () { return __importDefault(BasicAction_1).default; } });
75
+ var vrack_db_1 = require("vrack-db");
76
+ Object.defineProperty(exports, "StorageTypes", { enumerable: true, get: function () { return vrack_db_1.StorageTypes; } });
53
77
  __exportStar(require("./service/Device"), exports);
54
78
  __exportStar(require("./service/DeviceConnect"), exports);
55
79
  __exportStar(require("./service/DevicePort"), exports);
@@ -0,0 +1,49 @@
1
+ import { StorageTypes } from "vrack-db";
2
+ import IMetricSettings from "./IMetricSettings";
3
+ /**
4
+ * Metric base class. Used internally to define device metrics.
5
+ */
6
+ export default class BasicMetric {
7
+ /**
8
+ * Default metric setting
9
+ */
10
+ protected metric: IMetricSettings;
11
+ /**
12
+ * Defines the type of time storage
13
+ *
14
+ * @param type StorageTypes type like a StorageTypes.Uint64 (default)
15
+ */
16
+ timeStorage(type: StorageTypes): this;
17
+ /**
18
+ * Defines the type of value storage
19
+ *
20
+ * @param type StorageTypes type like a StorageTypes.Uint64 (default)
21
+ */
22
+ valueStorage(type: StorageTypes): this;
23
+ /**
24
+ * Specifies the accuracy and storage period size of Graphite-style metrics
25
+ *
26
+ *
27
+ * @see SingleDB.metric
28
+ * @param req retentions Graphite-style `5s:10m, 1m:2h, 15m:1d, 1h:1w, 6h:1mon, 1d:1y`
29
+ */
30
+ retentions(req: string): this;
31
+ /**
32
+ * Metric Description
33
+ *
34
+ * @param des Short text description of the metric
35
+ */
36
+ description(des: string): this;
37
+ /**
38
+ * To add additional data to the metric, you can specify
39
+ * any object describing the metric in this method.
40
+ *
41
+ * @param add Additional information for the metric
42
+ */
43
+ additional(add: any): this;
44
+ /**
45
+ * Returns the internal metric settings object. Used inside Container
46
+ * @private
47
+ */
48
+ export(): IMetricSettings;
49
+ }