vrack2-core 1.0.5 → 1.1.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.
package/README.md CHANGED
@@ -9,7 +9,13 @@ VRack2 Core
9
9
 
10
10
  --------
11
11
 
12
- ### Последнее обновление 1.0.5
12
+ ### Последнее обновление 1.1.0
13
+
14
+ - Переход компиляции на `es2021` - теперь минимальная версия Node.js ≥ 16
15
+ - Добавлен класс `ReactiveRef` для создания переменных с очень простой реактивностью
16
+ - Добавлен класс `UniversalWorkers` для создания воркеров разных типов и работы с ними
17
+
18
+ ### обновление 1.0.5
13
19
  - В Container добавлена ошибка `CTR_IGNORE_SERVICE_AUTORELOAD` её можно использовать, когда не хочется что бы после завершения работы сервиса - сервис автоматически перезапускался
14
20
  - В класс `Device` добавлены
15
21
  - Свойство `works: boolean = true` - если `false` - устройство перестает принимать и отправлять данные через порты
@@ -17,7 +23,7 @@ VRack2 Core
17
23
  - Теперь бинд входящего порта осуществляется по другому. Теперь вместо замены `DevicePort.push` ссылка на хендлер складывается в `DevicePort.bind` и уже после этого происходит вызов `DevicePort.bind()` внутри `DevicePort.push`
18
24
 
19
25
 
20
- ### Последнее обновление 1.0.4
26
+ ### обновление 1.0.4
21
27
 
22
28
  - `BasicType` (класс `Rule`) `require()` deprecated - используем `required()`
23
29
  - **ErrorManager** - Теперь не создаёт ошибку при повторной регистрации с одинаковыми параметрами
package/lib/Bootstrap.js CHANGED
@@ -3,15 +3,6 @@
3
3
  * Copyright © 2024 Boris Bobylev. All rights reserved.
4
4
  * Licensed under the Apache License, Version 2.0
5
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
6
  var __importDefault = (this && this.__importDefault) || function (mod) {
16
7
  return (mod && mod.__esModule) ? mod : { "default": mod };
17
8
  };
@@ -65,21 +56,19 @@ class Bootstrap {
65
56
  *
66
57
  * @param Container Container for which loading is performed
67
58
  */
68
- loadBootList(Container) {
69
- return __awaiter(this, void 0, void 0, function* () {
70
- for (const cn in this.config) {
71
- const conf = this.config[cn];
72
- const ExClass = yield ImportManager_1.default.importClass(conf.path);
73
- this.loaded[cn] = new ExClass(cn, ImportManager_1.default.importClassName(conf.path), Container, conf.options);
74
- if (!(this.loaded[cn] instanceof BootClass_1.default)) {
75
- throw _1.ErrorManager.make('BTSP_INSTANCE_OF_INCORRECT', { path: conf.path });
76
- }
59
+ async loadBootList(Container) {
60
+ for (const cn in this.config) {
61
+ const conf = this.config[cn];
62
+ const ExClass = await ImportManager_1.default.importClass(conf.path);
63
+ this.loaded[cn] = new ExClass(cn, ImportManager_1.default.importClassName(conf.path), Container, conf.options);
64
+ if (!(this.loaded[cn] instanceof BootClass_1.default)) {
65
+ throw _1.ErrorManager.make('BTSP_INSTANCE_OF_INCORRECT', { path: conf.path });
77
66
  }
78
- for (const bc in this.loaded)
79
- this.loaded[bc].process();
80
- for (const bc in this.loaded)
81
- yield this.loaded[bc].processPromise();
82
- });
67
+ }
68
+ for (const bc in this.loaded)
69
+ this.loaded[bc].process();
70
+ for (const bc in this.loaded)
71
+ await this.loaded[bc].processPromise();
83
72
  }
84
73
  /**
85
74
  * Getting an initialized class
package/lib/Container.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -125,11 +116,9 @@ class Container extends events_1.default {
125
116
  /**
126
117
  * Run container
127
118
  */
128
- run() {
129
- return __awaiter(this, void 0, void 0, function* () {
130
- yield this.init();
131
- yield this.runProcess();
132
- });
119
+ async run() {
120
+ await this.init();
121
+ await this.runProcess();
133
122
  }
134
123
  /**
135
124
  * Extends service from config file
@@ -173,87 +162,83 @@ class Container extends events_1.default {
173
162
  *
174
163
  * @see structure
175
164
  */
176
- init() {
177
- return __awaiter(this, void 0, void 0, function* () {
178
- if (this.inited)
179
- return;
180
- this.inited = true;
181
- this.emit('configure');
182
- try {
183
- this.fillConfFile();
165
+ async init() {
166
+ if (this.inited)
167
+ return;
168
+ this.inited = true;
169
+ this.emit('configure');
170
+ try {
171
+ this.fillConfFile();
172
+ }
173
+ catch (err) {
174
+ if (err instanceof Error) {
175
+ const ner = ErrorManager_1.default.make('CTR_CONF_EXTENDS_PROBLEM', {}).setTrace(err).add(err);
176
+ throw ner;
184
177
  }
185
- catch (err) {
186
- if (err instanceof Error) {
187
- const ner = ErrorManager_1.default.make('CTR_CONF_EXTENDS_PROBLEM', {}).setTrace(err).add(err);
188
- throw ner;
189
- }
190
- throw err;
178
+ throw err;
179
+ }
180
+ this.emit('beforeInit');
181
+ this.emit('init');
182
+ for (const device of this.service.devices) {
183
+ try {
184
+ this.emit('initDevice', device);
185
+ await this.initDevice(device);
191
186
  }
192
- this.emit('beforeInit');
193
- this.emit('init');
194
- for (const device of this.service.devices) {
195
- try {
196
- this.emit('initDevice', device);
197
- yield this.initDevice(device);
198
- }
199
- catch (error) {
200
- const ner = ErrorManager_1.default.make('CTR_ERROR_INIT_DEVICE', { deviceConfig: device });
201
- ner.add(error);
202
- throw ner;
203
- }
187
+ catch (error) {
188
+ const ner = ErrorManager_1.default.make('CTR_ERROR_INIT_DEVICE', { deviceConfig: device });
189
+ ner.add(error);
190
+ throw ner;
204
191
  }
205
- this.emit('afterInit');
206
- this.emit('beforeConnections');
207
- this.emit('connections');
208
- for (const device of this.service.devices) {
209
- if (!device.connections)
210
- continue;
211
- for (const conn of device.connections) {
212
- this.emit('connection', conn);
213
- this.initConnection(conn);
214
- }
192
+ }
193
+ this.emit('afterInit');
194
+ this.emit('beforeConnections');
195
+ this.emit('connections');
196
+ for (const device of this.service.devices) {
197
+ if (!device.connections)
198
+ continue;
199
+ for (const conn of device.connections) {
200
+ this.emit('connection', conn);
201
+ this.initConnection(conn);
215
202
  }
216
- if (Array.isArray(this.service.connections)) {
217
- for (const conn of this.service.connections) {
218
- this.initConnection(conn);
219
- }
203
+ }
204
+ if (Array.isArray(this.service.connections)) {
205
+ for (const conn of this.service.connections) {
206
+ this.initConnection(conn);
220
207
  }
221
- this.emit('afterConnections');
222
- });
208
+ }
209
+ this.emit('afterConnections');
223
210
  }
224
211
  /**
225
212
  * Run process & processPromise of all devices
226
213
  */
227
- runProcess() {
228
- return __awaiter(this, void 0, void 0, function* () {
229
- if (this.runned)
230
- return;
231
- this.runned = true;
232
- this.emit('beforeProcess');
233
- for (const key in this.devices) {
234
- try {
235
- this.emit('process', key);
236
- this.devices[key].process();
237
- }
238
- catch (error) {
239
- throw ErrorManager_1.default.make('CTR_DEVICE_PROCESS_EXCEPTION', { device: key }).add(error);
240
- }
214
+ async runProcess() {
215
+ if (this.runned)
216
+ return;
217
+ this.runned = true;
218
+ this.emit('beforeProcess');
219
+ for (const key in this.devices) {
220
+ try {
221
+ this.emit('process', key);
222
+ this.devices[key].process();
241
223
  }
242
- this.emit('afterProcess');
243
- this.emit('beforeProcessPromise');
244
- for (const key in this.devices) {
245
- try {
246
- this.emit('processPromise', key);
247
- yield this.devices[key].processPromise();
248
- }
249
- catch (error) {
250
- throw ErrorManager_1.default.make('CTR_DEVICE_PROCESS_PROMISE_EXCEPTION', { device: key }).add(error);
251
- }
224
+ catch (error) {
225
+ throw ErrorManager_1.default.make('CTR_DEVICE_PROCESS_EXCEPTION', { device: key }).add(error);
226
+ }
227
+ }
228
+ this.emit('afterProcess');
229
+ this.emit('beforeProcessPromise');
230
+ for (const key in this.devices) {
231
+ try {
232
+ this.emit('processPromise', key);
233
+ await this.devices[key].processPromise();
234
+ }
235
+ catch (error) {
236
+ throw ErrorManager_1.default.make('CTR_DEVICE_PROCESS_PROMISE_EXCEPTION', { device: key }).add(error);
252
237
  }
253
- this.emit('afterProcessPromise');
254
- this.emit('beforeLoaded');
255
- this.emit('loaded');
256
- });
238
+ }
239
+ this.emit('afterProcessPromise');
240
+ this.emit('beforeLoaded');
241
+ this.emit('loaded');
257
242
  }
258
243
  /**
259
244
  * Check device action and run him
@@ -262,29 +247,25 @@ class Container extends events_1.default {
262
247
  * @param action Device action (as 'action.name')
263
248
  * @param data Data for action
264
249
  */
265
- deviceAction(device, action, data) {
266
- return __awaiter(this, void 0, void 0, function* () {
267
- if (!this.deviceActions[device])
268
- throw ErrorManager_1.default.make('CTR_DEVICE_NF', { device });
269
- const deviceClass = this.devices[device];
270
- const deviceActions = this.deviceActions[device];
271
- const method = ImportManager_1.default.camelize('action.' + action);
272
- if (!deviceActions[action])
273
- throw ErrorManager_1.default.make('CTR_DEVICE_ACTION_NF', { device, action, method });
274
- if (!deviceClass[method])
275
- throw ErrorManager_1.default.make('CTR_DEVICE_ACTION_HANDLER_NF', { device, action });
276
- const actionExport = deviceActions[action].exportRaw();
277
- Validator_1.default.validate(actionExport.requirements, data);
278
- return yield deviceClass[method](data);
279
- });
250
+ async deviceAction(device, action, data) {
251
+ if (!this.deviceActions[device])
252
+ throw ErrorManager_1.default.make('CTR_DEVICE_NF', { device });
253
+ const deviceClass = this.devices[device];
254
+ const deviceActions = this.deviceActions[device];
255
+ const method = ImportManager_1.default.camelize('action.' + action);
256
+ if (!deviceActions[action])
257
+ throw ErrorManager_1.default.make('CTR_DEVICE_ACTION_NF', { device, action, method });
258
+ if (!deviceClass[method])
259
+ throw ErrorManager_1.default.make('CTR_DEVICE_ACTION_HANDLER_NF', { device, action });
260
+ const actionExport = deviceActions[action].exportRaw();
261
+ Validator_1.default.validate(actionExport.requirements, data);
262
+ return await deviceClass[method](data);
280
263
  }
281
264
  /**
282
265
  * Return structure
283
266
  */
284
- getStructure() {
285
- return __awaiter(this, void 0, void 0, function* () {
286
- return this.structure;
287
- });
267
+ async getStructure() {
268
+ return this.structure;
288
269
  }
289
270
  /**
290
271
  * Init one device
@@ -297,103 +278,101 @@ class Container extends events_1.default {
297
278
  * 6. make device inputs ports
298
279
  * 7. make device outputs ports
299
280
  **/
300
- initDevice(dconf) {
301
- return __awaiter(this, void 0, void 0, function* () {
302
- const DM = this.Bootstrap.getBootClass('DeviceManager', DeviceManager_1.default);
303
- const cs = yield DM.get(dconf.type);
304
- //
305
- if (dconf.id === undefined || !dconf.id || typeof dconf.id !== 'string' || !Utility_1.default.isDeviceName(dconf.id)) {
306
- throw ErrorManager_1.default.make('CTR_INCORRECT_DEVICE_ID');
307
- }
308
- // Device id is dublicated
309
- if (dconf.id in this.devices)
310
- throw ErrorManager_1.default.make('CTR_DEVICE_DUBLICATE');
311
- // Create device
312
- const dev = new cs(dconf.id, dconf.type, this);
313
- this.devices[dconf.id] = dev;
314
- // Fill options
315
- for (const key in dconf.options)
316
- dev.options[key] = dconf.options[key];
317
- // try prepare options
318
- try {
319
- dev.prepareOptions();
320
- }
321
- catch (error) {
322
- let message = '';
323
- if (error instanceof Error)
324
- message = error.toString();
325
- const ner = ErrorManager_1.default.make('CTR_ERROR_PREPARE_OPTIONS', { message });
326
- if (error instanceof CoreError_1.default)
327
- ner.add(error);
328
- throw ner;
329
- }
330
- const rules = dev.checkOptions();
331
- // Validating
332
- Validator_1.default.validate(rules, dev.options);
333
- /** create structure */
334
- this.structure[dconf.id] = {
335
- id: dconf.id,
336
- type: dconf.type,
337
- actions: {},
338
- outputs: {},
339
- inputs: {},
340
- ports: [],
341
- settings: {},
342
- metrics: {},
343
- };
344
- dev.preProcess();
345
- // Check actions
346
- this.deviceActions[dev.id] = dev.actions();
347
- for (const action in this.deviceActions[dev.id]) {
348
- const method = ImportManager_1.default.camelize('action.' + action);
349
- if (!(method in dev))
350
- throw ErrorManager_1.default.make('CTR_DEVICE_ACTION_NF', { action, method });
351
- // add structure device action
352
- this.structure[dconf.id].actions[action] = this.deviceActions[dev.id][action].export();
353
- }
354
- this.structure[dconf.id].settings = dev.settings();
355
- // Make Metrics
356
- this.deviceMetrics[dev.id] = dev.metrics();
357
- for (const metric in this.deviceMetrics[dev.id]) {
358
- const raw = this.deviceMetrics[dev.id][metric].export();
359
- const nEvent = { device: dev.id, data: metric, trace: raw };
360
- this.emit('device.register.metric', nEvent);
361
- this.structure[dconf.id].metrics[metric] = raw;
362
- }
363
- // make inputPorts
364
- const iPorts = dev.inputs();
365
- for (const key in iPorts) {
366
- const exp = iPorts[key].export();
367
- const pList = this.getPortList(key, exp);
368
- for (const subkey in pList) {
369
- this.checkPortName(subkey);
370
- const handler = ImportManager_1.default.camelize('input.' + subkey);
371
- this.checkInputHandler(subkey, handler, dev);
372
- const ndp = new DevicePort_1.default(subkey, pList[subkey], dev);
373
- dev.ports.input[subkey] = ndp;
374
- // add structure device input ports
375
- this.structure[dconf.id].inputs[subkey] = [];
376
- this.structure[dconf.id].ports.push(Object.assign({ port: subkey, direct: 'input' }, pList[subkey]));
377
- // биндимся а не заменяем push для контроля внутри push
378
- if (handler in dev)
379
- ndp.bind = dev[handler].bind(dev);
380
- }
281
+ async initDevice(dconf) {
282
+ const DM = this.Bootstrap.getBootClass('DeviceManager', DeviceManager_1.default);
283
+ const cs = await DM.get(dconf.type);
284
+ //
285
+ if (dconf.id === undefined || !dconf.id || typeof dconf.id !== 'string' || !Utility_1.default.isDeviceName(dconf.id)) {
286
+ throw ErrorManager_1.default.make('CTR_INCORRECT_DEVICE_ID');
287
+ }
288
+ // Device id is dublicated
289
+ if (dconf.id in this.devices)
290
+ throw ErrorManager_1.default.make('CTR_DEVICE_DUBLICATE');
291
+ // Create device
292
+ const dev = new cs(dconf.id, dconf.type, this);
293
+ this.devices[dconf.id] = dev;
294
+ // Fill options
295
+ for (const key in dconf.options)
296
+ dev.options[key] = dconf.options[key];
297
+ // try prepare options
298
+ try {
299
+ dev.prepareOptions();
300
+ }
301
+ catch (error) {
302
+ let message = '';
303
+ if (error instanceof Error)
304
+ message = error.toString();
305
+ const ner = ErrorManager_1.default.make('CTR_ERROR_PREPARE_OPTIONS', { message });
306
+ if (error instanceof CoreError_1.default)
307
+ ner.add(error);
308
+ throw ner;
309
+ }
310
+ const rules = dev.checkOptions();
311
+ // Validating
312
+ Validator_1.default.validate(rules, dev.options);
313
+ /** create structure */
314
+ this.structure[dconf.id] = {
315
+ id: dconf.id,
316
+ type: dconf.type,
317
+ actions: {},
318
+ outputs: {},
319
+ inputs: {},
320
+ ports: [],
321
+ settings: {},
322
+ metrics: {},
323
+ };
324
+ dev.preProcess();
325
+ // Check actions
326
+ this.deviceActions[dev.id] = dev.actions();
327
+ for (const action in this.deviceActions[dev.id]) {
328
+ const method = ImportManager_1.default.camelize('action.' + action);
329
+ if (!(method in dev))
330
+ throw ErrorManager_1.default.make('CTR_DEVICE_ACTION_NF', { action, method });
331
+ // add structure device action
332
+ this.structure[dconf.id].actions[action] = this.deviceActions[dev.id][action].export();
333
+ }
334
+ this.structure[dconf.id].settings = dev.settings();
335
+ // Make Metrics
336
+ this.deviceMetrics[dev.id] = dev.metrics();
337
+ for (const metric in this.deviceMetrics[dev.id]) {
338
+ const raw = this.deviceMetrics[dev.id][metric].export();
339
+ const nEvent = { device: dev.id, data: metric, trace: raw };
340
+ this.emit('device.register.metric', nEvent);
341
+ this.structure[dconf.id].metrics[metric] = raw;
342
+ }
343
+ // make inputPorts
344
+ const iPorts = dev.inputs();
345
+ for (const key in iPorts) {
346
+ const exp = iPorts[key].export();
347
+ const pList = this.getPortList(key, exp);
348
+ for (const subkey in pList) {
349
+ this.checkPortName(subkey);
350
+ const handler = ImportManager_1.default.camelize('input.' + subkey);
351
+ this.checkInputHandler(subkey, handler, dev);
352
+ const ndp = new DevicePort_1.default(subkey, pList[subkey], dev);
353
+ dev.ports.input[subkey] = ndp;
354
+ // add structure device input ports
355
+ this.structure[dconf.id].inputs[subkey] = [];
356
+ this.structure[dconf.id].ports.push(Object.assign({ port: subkey, direct: 'input' }, pList[subkey]));
357
+ // биндимся а не заменяем push для контроля внутри push
358
+ if (handler in dev)
359
+ ndp.bind = dev[handler].bind(dev);
381
360
  }
382
- // make output ports
383
- const oPorts = dev.outputs();
384
- for (const key in oPorts) {
385
- const exp = oPorts[key].export();
386
- const pList = this.getPortList(key, exp);
387
- for (const subkey in pList) {
388
- this.checkPortName(subkey);
389
- const ndp = new DevicePort_1.default(subkey, pList[subkey], dev);
390
- dev.ports.output[subkey] = ndp;
391
- // add structure device output ports
392
- this.structure[dconf.id].outputs[subkey] = [];
393
- this.structure[dconf.id].ports.push(Object.assign({ port: subkey, direct: 'output' }, pList[subkey]));
394
- }
361
+ }
362
+ // make output ports
363
+ const oPorts = dev.outputs();
364
+ for (const key in oPorts) {
365
+ const exp = oPorts[key].export();
366
+ const pList = this.getPortList(key, exp);
367
+ for (const subkey in pList) {
368
+ this.checkPortName(subkey);
369
+ const ndp = new DevicePort_1.default(subkey, pList[subkey], dev);
370
+ dev.ports.output[subkey] = ndp;
371
+ // add structure device output ports
372
+ this.structure[dconf.id].outputs[subkey] = [];
373
+ this.structure[dconf.id].ports.push(Object.assign({ port: subkey, direct: 'output' }, pList[subkey]));
395
374
  }
396
- });
375
+ }
397
376
  }
398
377
  /**
399
378
  * Check device input handler
@@ -447,7 +426,6 @@ class Container extends events_1.default {
447
426
  * @return Connection object
448
427
  */
449
428
  toConnection(con) {
450
- var _a, _b;
451
429
  const act = con.split('->');
452
430
  if (act.length !== 2)
453
431
  throw ErrorManager_1.default.make('CTR_CONNECTION_INCORRECT', { connection: con, error: "Syntax connection error, syntax have -> beetwen device" });
@@ -457,9 +435,9 @@ class Container extends events_1.default {
457
435
  throw ErrorManager_1.default.make('CTR_CONNECTION_INCORRECT', { connection: con, error: "Syntax connection error, syntax have more 3 actets on side" });
458
436
  if (outputDeviceActs.length < 2 || inputDeviceActs.length < 2)
459
437
  throw ErrorManager_1.default.make('CTR_CONNECTION_INCORRECT', { connection: con, error: "Syntax connection error, syntax have less 2 actets on side" });
460
- let outputDevice = (_a = outputDeviceActs.shift()) === null || _a === void 0 ? void 0 : _a.trim();
438
+ let outputDevice = outputDeviceActs.shift()?.trim();
461
439
  const outputPort = outputDeviceActs.join('.').trim();
462
- let inputDevice = (_b = inputDeviceActs.shift()) === null || _b === void 0 ? void 0 : _b.trim();
440
+ let inputDevice = inputDeviceActs.shift()?.trim();
463
441
  const inputPort = inputDeviceActs.join('.').trim();
464
442
  if (outputDevice === undefined)
465
443
  outputDevice = '';