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
@@ -12,20 +12,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
12
12
  step((generator = generator.apply(thisArg, _arguments || [])).next());
13
13
  });
14
14
  };
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
15
18
  Object.defineProperty(exports, "__esModule", { value: true });
16
19
  exports.EDeviceMessageTypes = void 0;
17
- /**
18
- * Интерфейс списка исходящих портов устройства
19
- // */
20
- // export interface IDeviceOutputList {
21
- // [index: string]: OutputPort;
22
- // }
23
- // /**
24
- // * Интерфейс списка входящих портов устройства
25
- // */
26
- // export interface IDeviceInputList {
27
- // [index: string]: InputPort;
28
- // }
20
+ const CoreError_1 = __importDefault(require("../errors/CoreError"));
21
+ const ImportManager_1 = __importDefault(require("../ImportManager"));
29
22
  var EDeviceMessageTypes;
30
23
  (function (EDeviceMessageTypes) {
31
24
  EDeviceMessageTypes["terminal"] = "terminal";
@@ -36,18 +29,30 @@ var EDeviceMessageTypes;
36
29
  EDeviceMessageTypes["alert"] = "alert";
37
30
  })(EDeviceMessageTypes = exports.EDeviceMessageTypes || (exports.EDeviceMessageTypes = {}));
38
31
  class Device {
32
+ /**
33
+ * @param id Unique ID
34
+ * @param type Device type string
35
+ * @param Container Active loader container
36
+ */
39
37
  constructor(id, type, Container) {
40
- /** Входящие (назначаемые сверху) параметры устройства */
38
+ /**
39
+ * Device options
40
+ *
41
+ * @see checkOptions()
42
+ */
41
43
  this.options = {};
42
44
  /**
43
- * Shares данные устройства (обновляемые данные)
44
- * используется с методом `this.render`
45
+ * This is a fast updating data object - it will be sent
46
+ * to subscribers after the render() call
45
47
  *
46
48
  * @see render()
47
49
  * */
48
50
  this.shares = {};
49
51
  /**
52
+ * This data will be loaded for the specific instance of the device.
53
+ * The device itself determines this data and saves it at the right moment
50
54
  *
55
+ * The structure is determined by the device
51
56
  */
52
57
  this.storage = {};
53
58
  this.id = id;
@@ -59,133 +64,230 @@ class Device {
59
64
  };
60
65
  }
61
66
  /**
62
- * Short device description
67
+ * Device settings
68
+ *
69
+ * Needs to be finalized"
70
+ */
71
+ settings() {
72
+ return {
73
+ channels: ['terminal', 'notify', 'event', 'action', 'alert', 'error', 'render']
74
+ };
75
+ }
76
+ /**
77
+ * Short device description. Can use markdown markup
63
78
  *
64
79
  * @return {string} Device description
65
80
  * */
66
81
  description() {
67
82
  return '';
68
83
  }
69
- /** Список Action-методов устройства */
70
- actions() { return {}; }
71
84
  /**
72
- * Определение списка параметров устройства
85
+ * Device action list
86
+ * Device actions can be called from the container.
87
+ * This is a way to interact with the device from the outside world
73
88
  *
74
- * @returns {Array<Rule>}
89
+ * @example
90
+ * ```
91
+ * return {
92
+ * 'test.action': Action.global().requirements({
93
+ * id: Rule.string().require().default('www').description('Some id')
94
+ * }).description('Test action')
95
+ * }
96
+ * ```
97
+ *
98
+ * A handler must be created for each action. For example, for `test.action` action `actionTestAction` must be created.
75
99
  * */
76
- checkOptions() { return {}; }
100
+ actions() { return {}; }
101
+ /**
102
+ * Defining device metrics.
103
+ *
104
+ * @example
105
+ *
106
+ * ```
107
+ * return {
108
+ * 'test.metric': Metric.inS().retentions('1s:6h').description('Test metric')
109
+ * }
110
+ * ```
111
+ * @see BasicMetric
112
+ */
113
+ metrics() { return {}; }
114
+ /**
115
+ * Run before each device action
116
+ *
117
+ * @param action "device.action" like string
118
+ * @param data data for action
119
+ */
120
+ beforeAction(action, data) { return true; }
77
121
  /**
78
122
  * Prepare options
79
123
  *
80
124
  * this method call before validating options
81
125
  */
82
126
  prepareOptions() { return; }
127
+ /**
128
+ * Defining a list of device parameters
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * return {
133
+ * timeout: Rule.number().integer().min(0).description('Interval timeout').example(0)
134
+ * }
135
+ * ```
136
+ *
137
+ * @returns {Array<Rule>}
138
+ * */
139
+ checkOptions() { return {}; }
140
+ /**
141
+ * Device inputs list
142
+ *
143
+ * Use like this object:
144
+ * {
145
+ * 'group.portname': Port.standart(),
146
+ * 'group.portname': Port.standart()
147
+ * }
148
+ *
149
+ */
83
150
  inputs() { return {}; }
151
+ /**
152
+ * Device output list
153
+ *
154
+ * @see inputs
155
+ */
84
156
  outputs() { return {}; }
85
157
  /**
86
- * Метод является входной точкой для начала инициализации устройства
158
+ * The method is an input point to start device initialization
87
159
  *
88
- * Устройство пройдет только следующие этапы создания устройства:
160
+ * The device will only go through the following device creation steps:
89
161
  *
90
- * - Создания класса
91
- * - Назначение праметров устройства
162
+ * - Creating a class
163
+ * - Assigning device prameters
92
164
  *
93
- * Необходимо использовать для назначения функций вызова динамических портов
94
- * устройства.
165
+ * Must be used to assign functions to call dynamic ports
166
+ * of the device.
95
167
  */
96
168
  preProcess() { return; }
97
169
  /**
98
- * Метод является входной точкой для начала работы устройства
170
+ * The method is an input point for the start of device operation
99
171
  *
100
- * Устройство пройдет следующие этапы создания устройства:
172
+ * The device will go through the following steps to create the device:
101
173
  *
102
- * - Создания класса
103
- * - Назначение праметров устройства
104
- * - Создание портов
105
- * - Назначение функций вызова
106
- * - Создание соединений между устройствами
107
- * - Линковка Shares устройства
174
+ * - Creating a class
175
+ * - Assigning device prameters
176
+ * - Creating ports
177
+ * - Assigning call functions
178
+ * - Creating connections between devices
179
+ * - Linking device Shares
108
180
  *
109
- * Необходимо использовать для осуществления начала основной работы устройства
110
- * например, инициализация подключений, создание таймеров и тп.
181
+ * Must be used to start basic operation of the device
182
+ * e.g. initialization of connections, creation of timers, etc.
111
183
  */
112
184
  process() { return; }
113
185
  /**
114
- * По аналогии с `process` но асинхронный, загрузчик будет ждать выполнения всех
115
- * методов `processPromise` всех устройств.
186
+ * Similar to `process` but asynchronous, the loader will wait for the execution of all the
187
+ * `processPromise` methods of all devices.
116
188
  *
117
- * Используется, когда есть необходимость перед запуском стойки выполнить
118
- * и дождаться выполнения асинхронного кода (инициализация некоторых файловых баз данных и тп)
189
+ * Used when there is a need to execute before starting the rack
190
+ * and wait for asynchronous code to execute (initialization of some file databases, etc.)
119
191
  */
120
192
  processPromise() {
121
193
  return __awaiter(this, void 0, void 0, function* () { return; });
122
194
  }
123
- stop() { return; }
124
- stopPromise() {
125
- return __awaiter(this, void 0, void 0, function* () { return; });
126
- }
127
195
  /**
128
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
129
- * к постановке в очередь устройства на обновление данных `Shares`
196
+ * Myby todo?
197
+ *
198
+ * stop() { return }
199
+ * async stopPromise() { return }
130
200
  */
131
- render() { return this.event('device.render', 'shares', this.shares); }
132
201
  /**
133
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
134
- * к сохранение в локальное файловое хранилище данных `Storage`
202
+ * Queues device shares data updates for external consumers
203
+ *
204
+ * @see shares
135
205
  */
136
- save() { return this.event('device.save', 'storage', this.storage); }
206
+ render() { return this.makeEvent('device.render', 'shares', this.shares, []); }
137
207
  /**
138
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
139
- * к отправке сообщению об ошибке
208
+ * Save device storage
140
209
  *
141
- * @param {string} data Сообщение об ошибке
142
- * @param {any} trace Непосредственно объект ошибки, или объект который поможет разобратся в случившейся ситуации
210
+ * @see storage
143
211
  */
144
- error(data, trace) { return this.event('device.error', data, trace); }
212
+ save() { return this.makeEvent('device.save', 'storage', this.storage, []); }
145
213
  /**
146
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
147
- * к отправке информационного сообщения
214
+ * Write metric value
148
215
  *
149
- * @param {string} data Сообщение об ошибке
150
- * @param {any} trace Дополнительная информация
216
+ * @param path Registered metric path
217
+ * @param value value record
218
+ * @param modify Write modify 'last' | 'first' | 'max' | 'min' | 'avg' | 'sum'
151
219
  */
152
- notify(data, trace) { return this.event('device.notify', data, trace); }
220
+ metric(path, value, modify = 'last') {
221
+ return this.makeEvent('device.metric', path, { value, modify }, []);
222
+ }
153
223
  /**
154
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
155
- * к отправке оповещения
156
- *
157
- * @param {string} data Сообщение об ошибке
158
- * @param {any} trace Дополнительная информация
224
+ * @param data Message
225
+ * @param trace Trace info (object needed)
159
226
  */
160
- alert(data, trace) { return this.event('device.alert', data, trace); }
227
+ terminal(data, trace, ...args) { return this.makeEvent('device.terminal', data, trace, args); }
161
228
  /**
162
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
163
- * к отправке отладочной информации
164
- *
165
- * @param {string} data Сообщение об ошибке
166
- * @param {any} trace Дополнительная информация
229
+ * @param data Message
230
+ * @param trace Trace info (object needed)
167
231
  */
168
- terminal(data, trace) { return this.event('device.terminal', data, trace); }
232
+ notify(data, trace, ...args) { return this.makeEvent('device.notify', data, trace, args); }
169
233
  /**
170
- * Метод заменяется загрузчиком стойки, после чего, вызов этого метода приводит
171
- * к отправке сообщения о событии
234
+ * @param data Message
235
+ * @param trace Trace info (object needed)
236
+ */
237
+ event(data, trace, ...args) { return this.makeEvent('device.event', data, trace, args); }
238
+ /**
239
+ * @param data Message
240
+ * @param trace Trace info (object needed)
241
+ */
242
+ alert(data, trace, ...args) { return this.makeEvent('device.alert', data, trace, args); }
243
+ /**
244
+ * @param data Message
245
+ * @param trace Trace info (object needed)
246
+ */
247
+ error(data, trace, ...args) {
248
+ if (trace instanceof Error)
249
+ trace = CoreError_1.default.objectify(trace);
250
+ return this.makeEvent('device.error', data, trace, args);
251
+ }
252
+ /**
253
+ * Make & emit device event
172
254
  *
173
- * @param {string} data Сообщение об ошибке
174
- * @param {any} trace Дополнительная информация
255
+ * @param type event type
256
+ * @param data event data string
257
+ * @param trace additional information
175
258
  */
176
- event(type, data, trace) {
177
- const nEvent = { id: this.id, data, trace };
259
+ makeEvent(type, data, trace, args) {
260
+ const nEvent = { device: this.id, data, trace };
178
261
  return this.Container.emit(type, nEvent);
179
262
  }
180
263
  /**
181
- * Сообщает стойке, о том, что устройство не может дальше работать
182
- * и произошла критическая ошибка
264
+ * Adding processing for the incoming port
183
265
  *
184
- * Требует создание ошибки устройства DeviceError
266
+ * @param name Port name in 'port.name' format
267
+ * @param action CallBack function to execute
268
+ */
269
+ addInputHandler(name, action) {
270
+ name = ImportManager_1.default.camelize('input.' + name);
271
+ this[name] = action;
272
+ }
273
+ /**
274
+ * Adding a handle for the action
275
+ *
276
+ * @param name Action name in the format 'action.name'
277
+ * @param action CallBack function to execute
278
+ */
279
+ addActionHandler(name, action) {
280
+ name = ImportManager_1.default.camelize('action.' + name);
281
+ this[name] = action;
282
+ }
283
+ /**
284
+ * Informs the rack that the unit cannot continue to operate.
285
+ * and a critical error has occurred
185
286
  *
287
+ * Requires DeviceError to be created
186
288
  */
187
289
  terminate(error, action) {
188
- return this.event('device.terminate', action, error);
290
+ return this.makeEvent('device.terminate', action, error, []);
189
291
  }
190
292
  }
191
293
  exports.default = Device;
@@ -1,21 +1,17 @@
1
1
  import DevicePort from "./DevicePort";
2
2
  /**
3
- * Класс для соедиения портов устройств
4
- *
3
+ * Class for connecting device ports
4
+ * Using inside Container class
5
5
  */
6
6
  export default class {
7
7
  outputLink: DevicePort;
8
8
  inputLink: DevicePort;
9
9
  /**
10
- * Инициализация соединения, требует 2 порта которые привязаны
11
- * к устройствам
12
- *
13
10
  */
14
11
  constructor(output: DevicePort, input: DevicePort);
15
12
  /**
16
- * Вызов входящего порта при вызове соединения
17
- *
18
- * @param {any} data Данные
13
+ * Handles communication between two device ports
14
+ * @param data Data sent by the device when the push port is invoked
19
15
  */
20
16
  push(data: any): any;
21
17
  }
@@ -5,14 +5,11 @@
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  /**
8
- * Класс для соедиения портов устройств
9
- *
8
+ * Class for connecting device ports
9
+ * Using inside Container class
10
10
  */
11
11
  class default_1 {
12
12
  /**
13
- * Инициализация соединения, требует 2 порта которые привязаны
14
- * к устройствам
15
- *
16
13
  */
17
14
  constructor(output, input) {
18
15
  this.outputLink = output;
@@ -21,9 +18,8 @@ class default_1 {
21
18
  this.inputLink.addConnection(this);
22
19
  }
23
20
  /**
24
- * Вызов входящего порта при вызове соединения
25
- *
26
- * @param {any} data Данные
21
+ * Handles communication between two device ports
22
+ * @param data Data sent by the device when the push port is invoked
27
23
  */
28
24
  push(data) {
29
25
  return this.inputLink.push(data);
@@ -1,24 +1,33 @@
1
1
  import IPort from "../ports/IPort";
2
2
  import DeviceConnect from "./DeviceConnect";
3
3
  /**
4
- * Класс для реализации порта устройства
5
- * Порт может быть как входящий так и исходящий
4
+ * A class to implement a device port.
5
+ * The port can be either incoming or outgoing
6
6
  */
7
7
  export default class DevicePort {
8
+ /** Flag to determine if the port is connected */
8
9
  connected: boolean;
10
+ /** Port connection list. One port can have multiple connections */
9
11
  connections: Array<DeviceConnect>;
12
+ /** Port ID */
10
13
  id: string;
14
+ /** Port type */
11
15
  type: string;
16
+ /** Flag determines whether the port should be connected */
12
17
  required: boolean;
18
+ /**
19
+ * Список слушателей порта
20
+ * Используется для захвата порта. Если какие либо данные будут проброшены
21
+ * в порт, они будут переданы для каждого вызнванного слушателя
22
+ */
23
+ listens: Map<number, (data: any) => void>;
13
24
  constructor(id: string, port: IPort);
14
25
  /**
15
- * Добавление связи в порт
26
+ * Adding communication to a port
16
27
  */
17
28
  addConnection(connection: DeviceConnect): void;
18
29
  /**
19
- * Вызов входящего порта при вызове соединения
20
- *
21
- * @param {any} data Данные
30
+ * Calling the incoming port when calling a connection
22
31
  */
23
32
  push(data: any): any;
24
33
  }
@@ -3,39 +3,56 @@
3
3
  * Copyright © 2022 Boris Bobylev. All rights reserved.
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  */
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
6
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ const Utility_1 = __importDefault(require("../Utility"));
7
11
  /**
8
- * Класс для реализации порта устройства
9
- * Порт может быть как входящий так и исходящий
12
+ * A class to implement a device port.
13
+ * The port can be either incoming or outgoing
10
14
  */
11
15
  class DevicePort {
12
16
  constructor(id, port) {
17
+ /** Flag to determine if the port is connected */
13
18
  this.connected = false;
19
+ /** Port connection list. One port can have multiple connections */
14
20
  this.connections = [];
21
+ /**
22
+ * Список слушателей порта
23
+ * Используется для захвата порта. Если какие либо данные будут проброшены
24
+ * в порт, они будут переданы для каждого вызнванного слушателя
25
+ */
26
+ this.listens = new Map();
15
27
  this.id = id;
16
28
  this.type = port.type;
17
29
  this.required = port.required;
18
30
  }
19
31
  /**
20
- * Добавление связи в порт
32
+ * Adding communication to a port
21
33
  */
22
34
  addConnection(connection) {
23
35
  this.connected = true;
24
36
  this.connections.push(connection);
25
37
  }
26
38
  /**
27
- * Вызов входящего порта при вызове соединения
28
- *
29
- * @param {any} data Данные
39
+ * Calling the incoming port when calling a connection
30
40
  */
31
41
  push(data) {
32
- if (this.connected) {
33
- if (this.connections.length === 1)
34
- return this.connections[0].push(data);
35
- for (const conn of this.connections) {
36
- conn.push(data);
37
- }
42
+ // Если у нас есть слушатели порта
43
+ // Передаем им данные и пересоздаем Map
44
+ if (this.listens.size) {
45
+ const res = Utility_1.default.prettyFormat(data);
46
+ for (const ls of this.listens.values())
47
+ ls(res);
48
+ this.listens = new Map();
38
49
  }
50
+ if (!this.connected)
51
+ return;
52
+ if (this.connections.length === 1)
53
+ return this.connections[0].push(data);
54
+ for (const conn of this.connections)
55
+ conn.push(data);
39
56
  }
40
57
  }
41
58
  exports.default = DevicePort;
@@ -1,5 +1,8 @@
1
1
  export default interface IDeviceEvent {
2
- id: string;
2
+ /** Device ID */
3
+ device: string;
4
+ /** event data string */
3
5
  data: string;
6
+ /** additional information */
4
7
  trace: any;
5
8
  }
@@ -1,8 +1,15 @@
1
1
  import IValidationRule from "./IValidationRule";
2
2
  export default interface IValidationProblem {
3
+ /** VRack Error manager short code like a VS_ERROR_DATABASE_NF */
3
4
  type: string;
5
+ /** VRack Error manager error code like a random string */
4
6
  code: string;
7
+ /** Error string (description) */
5
8
  description: string;
9
+ /** Exported validation rule */
6
10
  rule: IValidationRule;
11
+ /** Additional arguments for error */
7
12
  arg: any;
13
+ /** key for getting value from object */
14
+ fieldKey: string;
8
15
  }
@@ -1,9 +1,21 @@
1
1
  import IValidationSubrule from "./IValidationSubrule";
2
2
  export default interface IValidationRule {
3
+ /** VRack Error manager short code like a VS_ERROR_DATABASE_NF */
3
4
  type: string;
5
+ /** VRack Error manager error code like a random string */
4
6
  require: boolean;
7
+ /** Error string (description) */
5
8
  default: any;
9
+ /** Exported validation rule */
6
10
  rules: Array<IValidationSubrule>;
11
+ /** Additional arguments for error */
7
12
  example: any;
13
+ /** key for getting value from object */
8
14
  description: string;
15
+ /**
16
+ * Template for error message string
17
+ * Use like a "{description} field must by like a '123' number "
18
+ * You can use {description} {value} {default} in template
19
+ */
20
+ message: string;
9
21
  }
@@ -1,4 +1,6 @@
1
1
  export default interface IValidationSubrule {
2
+ /** Name of subrule */
2
3
  name: string;
4
+ /** Subrule arguments */
3
5
  args: any;
4
6
  }
@@ -1,12 +1,16 @@
1
+ import AnyType from "./types/AnyType";
1
2
  import ArrayType from "./types/ArrayType";
3
+ import BooleanType from "./types/BooleanType";
4
+ import FunctionType from "./types/FunctionType";
2
5
  import NumberType from "./types/NumberType";
3
6
  import ObjectType from "./types/ObjectType";
4
7
  import StringType from "./types/StringType";
5
- /**
6
- */
7
8
  export default class Rule {
9
+ static any(): AnyType;
8
10
  static number(): NumberType;
9
11
  static string(): StringType;
10
12
  static object(): ObjectType;
11
13
  static array(): ArrayType;
14
+ static boolean(): BooleanType;
15
+ static function(): FunctionType;
12
16
  }
@@ -7,13 +7,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
7
7
  return (mod && mod.__esModule) ? mod : { "default": mod };
8
8
  };
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ const AnyType_1 = __importDefault(require("./types/AnyType"));
10
11
  const ArrayType_1 = __importDefault(require("./types/ArrayType"));
12
+ const BooleanType_1 = __importDefault(require("./types/BooleanType"));
13
+ const FunctionType_1 = __importDefault(require("./types/FunctionType"));
11
14
  const NumberType_1 = __importDefault(require("./types/NumberType"));
12
15
  const ObjectType_1 = __importDefault(require("./types/ObjectType"));
13
16
  const StringType_1 = __importDefault(require("./types/StringType"));
14
- /**
15
- */
16
17
  class Rule {
18
+ static any() {
19
+ return new AnyType_1.default();
20
+ }
17
21
  static number() {
18
22
  return new NumberType_1.default();
19
23
  }
@@ -26,5 +30,11 @@ class Rule {
26
30
  static array() {
27
31
  return new ArrayType_1.default();
28
32
  }
33
+ static boolean() {
34
+ return new BooleanType_1.default();
35
+ }
36
+ static function() {
37
+ return new FunctionType_1.default();
38
+ }
29
39
  }
30
40
  exports.default = Rule;