@senior-gestao-empresarial/angular-components 6.12.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/bundles/senior-gestao-empresarial-angular-components.umd.js +454 -255
  2. package/bundles/senior-gestao-empresarial-angular-components.umd.js.map +1 -1
  3. package/bundles/senior-gestao-empresarial-angular-components.umd.min.js +2 -2
  4. package/bundles/senior-gestao-empresarial-angular-components.umd.min.js.map +1 -1
  5. package/components/utils/async-lock.d.ts +6 -0
  6. package/components/websocket/index.d.ts +2 -0
  7. package/components/websocket/models/index.d.ts +1 -0
  8. package/components/websocket/models/primitive-manager.d.ts +19 -0
  9. package/components/websocket/protocols/index.d.ts +2 -0
  10. package/components/websocket/protocols/on-event-options.d.ts +8 -0
  11. package/components/websocket/protocols/primitive-event.d.ts +10 -0
  12. package/components/websocket/user-information.service.d.ts +7 -0
  13. package/components/websocket/websocket.service.d.ts +78 -74
  14. package/esm2015/components/utils/async-lock.js +34 -0
  15. package/esm2015/components/websocket/index.js +2 -1
  16. package/esm2015/components/websocket/models/index.js +2 -0
  17. package/esm2015/components/websocket/models/primitive-manager.js +39 -0
  18. package/esm2015/components/websocket/protocols/index.js +1 -0
  19. package/esm2015/components/websocket/protocols/on-event-options.js +1 -0
  20. package/esm2015/components/websocket/protocols/primitive-event.js +1 -0
  21. package/esm2015/components/websocket/user-information.service.js +34 -0
  22. package/esm2015/components/websocket/websocket.service.js +269 -195
  23. package/esm2015/senior-gestao-empresarial-angular-components.js +4 -3
  24. package/esm5/components/utils/async-lock.js +43 -0
  25. package/esm5/components/websocket/index.js +2 -1
  26. package/esm5/components/websocket/models/index.js +2 -0
  27. package/esm5/components/websocket/models/primitive-manager.js +58 -0
  28. package/esm5/components/websocket/protocols/index.js +1 -0
  29. package/esm5/components/websocket/protocols/on-event-options.js +1 -0
  30. package/esm5/components/websocket/protocols/primitive-event.js +1 -0
  31. package/esm5/components/websocket/user-information.service.js +38 -0
  32. package/esm5/components/websocket/websocket.service.js +326 -255
  33. package/esm5/senior-gestao-empresarial-angular-components.js +4 -3
  34. package/fesm2015/senior-gestao-empresarial-angular-components.js +364 -193
  35. package/fesm2015/senior-gestao-empresarial-angular-components.js.map +1 -1
  36. package/fesm5/senior-gestao-empresarial-angular-components.js +451 -254
  37. package/fesm5/senior-gestao-empresarial-angular-components.js.map +1 -1
  38. package/package.json +3 -3
  39. package/senior-gestao-empresarial-angular-components.d.ts +3 -2
  40. package/senior-gestao-empresarial-angular-components.metadata.json +1 -1
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('primeng/breadcrumb'), require('@angular/router'), require('rxjs'), require('rxjs/operators'), require('moment'), require('@seniorsistemas/angular-components'), require('@angular/common/http'), require('primeng/api'), require('@ngx-translate/core'), require('@seniorsistemas/platform-components'), require('@seniorsistemas/senior-platform-data'), require('@angular/forms'), require('@stomp/stompjs'), require('js-cookie'), require('sockjs-client')) :
3
- typeof define === 'function' && define.amd ? define('@senior-gestao-empresarial/angular-components', ['exports', '@angular/core', '@angular/common', 'primeng/breadcrumb', '@angular/router', 'rxjs', 'rxjs/operators', 'moment', '@seniorsistemas/angular-components', '@angular/common/http', 'primeng/api', '@ngx-translate/core', '@seniorsistemas/platform-components', '@seniorsistemas/senior-platform-data', '@angular/forms', '@stomp/stompjs', 'js-cookie', 'sockjs-client'], factory) :
4
- (global = global || self, factory((global['senior-gestao-empresarial'] = global['senior-gestao-empresarial'] || {}, global['senior-gestao-empresarial']['angular-components'] = {}), global.ng.core, global.ng.common, global.breadcrumb, global.ng.router, global.rxjs, global.rxjs.operators, global.moment_, global.angularComponents, global.ng.common.http, global.api, global.core$1, global.platformComponents, global.seniorPlatformData, global.ng.forms, global.stompjs, global.jsCookie, global.SockJS));
5
- }(this, (function (exports, core, common, breadcrumb, router, rxjs, operators, moment_, angularComponents, http, api, core$1, platformComponents, seniorPlatformData, forms, stompjs, jsCookie, SockJS) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('primeng/breadcrumb'), require('@angular/router'), require('rxjs'), require('rxjs/operators'), require('moment'), require('@seniorsistemas/angular-components'), require('@angular/common/http'), require('primeng/api'), require('@ngx-translate/core'), require('@seniorsistemas/platform-components'), require('@seniorsistemas/senior-platform-data'), require('@angular/forms'), require('@stomp/stompjs'), require('sockjs-client'), require('js-cookie')) :
3
+ typeof define === 'function' && define.amd ? define('@senior-gestao-empresarial/angular-components', ['exports', '@angular/core', '@angular/common', 'primeng/breadcrumb', '@angular/router', 'rxjs', 'rxjs/operators', 'moment', '@seniorsistemas/angular-components', '@angular/common/http', 'primeng/api', '@ngx-translate/core', '@seniorsistemas/platform-components', '@seniorsistemas/senior-platform-data', '@angular/forms', '@stomp/stompjs', 'sockjs-client', 'js-cookie'], factory) :
4
+ (global = global || self, factory((global['senior-gestao-empresarial'] = global['senior-gestao-empresarial'] || {}, global['senior-gestao-empresarial']['angular-components'] = {}), global.ng.core, global.ng.common, global.breadcrumb, global.ng.router, global.rxjs, global.rxjs.operators, global.moment_, global.angularComponents, global.ng.common.http, global.api, global.core$1, global.platformComponents, global.seniorPlatformData, global.ng.forms, global.stompjs, global.SockJS, global.jsCookie));
5
+ }(this, (function (exports, core, common, breadcrumb, router, rxjs, operators, moment_, angularComponents, http, api, core$1, platformComponents, seniorPlatformData, forms, stompjs, SockJS, jsCookie) { 'use strict';
6
6
 
7
7
  /*! *****************************************************************************
8
8
  Copyright (c) Microsoft Corporation.
@@ -7412,320 +7412,517 @@
7412
7412
  return NpsService;
7413
7413
  }());
7414
7414
 
7415
+ var AsyncLock = /** @class */ (function () {
7416
+ function AsyncLock() {
7417
+ this.queue = [];
7418
+ this.acquired = false;
7419
+ }
7420
+ AsyncLock.prototype.acquire = function () {
7421
+ return __awaiter(this, void 0, void 0, function () {
7422
+ var _this = this;
7423
+ return __generator(this, function (_a) {
7424
+ if (!this.acquired) {
7425
+ this.acquired = true;
7426
+ return [2 /*return*/, Promise.resolve()];
7427
+ }
7428
+ else {
7429
+ return [2 /*return*/, new Promise(function (resolve, _) {
7430
+ _this.queue.push(resolve);
7431
+ })];
7432
+ }
7433
+ return [2 /*return*/];
7434
+ });
7435
+ });
7436
+ };
7437
+ AsyncLock.prototype.release = function () {
7438
+ return __awaiter(this, void 0, void 0, function () {
7439
+ var continuation;
7440
+ return __generator(this, function (_a) {
7441
+ if (this.queue.length === 0 && this.acquired) {
7442
+ this.acquired = false;
7443
+ return [2 /*return*/, Promise.resolve()];
7444
+ }
7445
+ continuation = this.queue.shift();
7446
+ return [2 /*return*/, new Promise(function (res) {
7447
+ continuation();
7448
+ res();
7449
+ })];
7450
+ });
7451
+ });
7452
+ };
7453
+ return AsyncLock;
7454
+ }());
7455
+
7456
+ var UserInformationService = /** @class */ (function () {
7457
+ function UserInformationService() {
7458
+ }
7459
+ UserInformationService_1 = UserInformationService;
7460
+ UserInformationService.prototype.getAuthToken = function () {
7461
+ var cookieValue = jsCookie.get(UserInformationService_1.TOKEN_COOKIE_KEY) || '{}';
7462
+ var authToken = JSON.parse(cookieValue);
7463
+ return authToken.access_token;
7464
+ };
7465
+ UserInformationService.prototype.getTenantDomain = function () {
7466
+ var cookieValue = jsCookie.get(UserInformationService_1.TOKEN_COOKIE_KEY) || '{}';
7467
+ var authToken = JSON.parse(cookieValue);
7468
+ return authToken.username.split('@')[1];
7469
+ };
7470
+ UserInformationService.prototype.getWebSocketUrl = function () {
7471
+ var baseUrl = jsCookie.get(UserInformationService_1.BASE_URL_COOKIE_KEY);
7472
+ if (baseUrl && !baseUrl.endsWith('/')) {
7473
+ baseUrl += '/';
7474
+ }
7475
+ return baseUrl + 'websocket';
7476
+ };
7477
+ var UserInformationService_1;
7478
+ UserInformationService.BASE_URL_COOKIE_KEY = 'com.senior.base.url';
7479
+ UserInformationService.TOKEN_COOKIE_KEY = 'com.senior.token';
7480
+ UserInformationService.ɵprov = core.ɵɵdefineInjectable({ factory: function UserInformationService_Factory() { return new UserInformationService(); }, token: UserInformationService, providedIn: "root" });
7481
+ UserInformationService = UserInformationService_1 = __decorate([
7482
+ core.Injectable({
7483
+ providedIn: 'root'
7484
+ })
7485
+ ], UserInformationService);
7486
+ return UserInformationService;
7487
+ }());
7488
+
7489
+ var PrimitiveManager = /** @class */ (function () {
7490
+ function PrimitiveManager(domain, service, primitive) {
7491
+ this.domain = domain;
7492
+ this.service = service;
7493
+ this.primitive = primitive;
7494
+ this.stompSubscriptions = [];
7495
+ this.event$ = new rxjs.Subject();
7496
+ this.subscribed$ = new rxjs.BehaviorSubject(false);
7497
+ }
7498
+ PrimitiveManager.prototype.unsubscribe = function () {
7499
+ var e_1, _a;
7500
+ this.event$.complete();
7501
+ try {
7502
+ for (var _b = __values(this.stompSubscriptions), _c = _b.next(); !_c.done; _c = _b.next()) {
7503
+ var stompSubscription = _c.value;
7504
+ stompSubscription.unsubscribe();
7505
+ }
7506
+ }
7507
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
7508
+ finally {
7509
+ try {
7510
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
7511
+ }
7512
+ finally { if (e_1) throw e_1.error; }
7513
+ }
7514
+ this.subscribed$.complete();
7515
+ };
7516
+ PrimitiveManager.prototype.fireEvent = function (event) {
7517
+ this.event$.next(event);
7518
+ };
7519
+ PrimitiveManager.prototype.subscribe = function () {
7520
+ var _a;
7521
+ var subscriptions = [];
7522
+ for (var _i = 0; _i < arguments.length; _i++) {
7523
+ subscriptions[_i] = arguments[_i];
7524
+ }
7525
+ (_a = this.stompSubscriptions).push.apply(_a, __spread(subscriptions));
7526
+ this.subscribed$.next(true);
7527
+ };
7528
+ PrimitiveManager.prototype.getEventObservable = function () {
7529
+ return this.event$.asObservable();
7530
+ };
7531
+ PrimitiveManager.prototype.getSubscriptionObservable = function () {
7532
+ return this.subscribed$.asObservable();
7533
+ };
7534
+ PrimitiveManager.prototype.hasObservers = function () {
7535
+ // @IMPORTANT: Replace .observers.length === 1 with .observed in rxjs 7.0+
7536
+ return this.event$.observers.length !== 1;
7537
+ };
7538
+ PrimitiveManager.prototype.getObserversCount = function () {
7539
+ return this.event$.observers.length;
7540
+ };
7541
+ return PrimitiveManager;
7542
+ }());
7543
+
7544
+ var RECONNECT_INTERVAL_MILLISECONDS = 3000;
7545
+ var CONNECTION_TIMEOUT_MILLISECONDS = 5000;
7415
7546
  var WebsocketService = /** @class */ (function () {
7416
- function WebsocketService() {
7417
- /** @private */
7418
- this.wasConnected = false;
7419
- /** @private */
7420
- this.isConnected = false;
7421
- /** @private */
7422
- this.isConnecting = false;
7423
- /** @private */
7424
- this.primitiveManagers = new Map();
7425
- /** @private */
7547
+ function WebsocketService(userInformationService) {
7548
+ this.userInformationService = userInformationService;
7426
7549
  this.connected$ = new rxjs.BehaviorSubject(false);
7427
- /** @private */
7428
- this.disconnect$ = new rxjs.Subject();
7429
- /** @private */
7430
- this.reconnect$ = new rxjs.Subject();
7431
- /** @private */
7550
+ this.disconnected$ = new rxjs.Subject();
7551
+ this.reconnected$ = new rxjs.Subject();
7432
7552
  this.error$ = new rxjs.Subject();
7433
7553
  this.subscribed$ = new rxjs.Subject();
7554
+ this.primitiveManagers = new Map();
7555
+ this.connectionLock = new AsyncLock();
7556
+ this.debugEnable = false;
7557
+ this.lostConnection = false;
7434
7558
  }
7435
- WebsocketService_1 = WebsocketService;
7436
7559
  /**
7437
- * Observable responsável por emitir uma notificação quando a conexão websocket é estabelecida pela primeira vez.
7438
- * @return Um `Observable<void>` que emite uma notificação quando a conexão websocket é estabelecida pela primeira vez.
7560
+ * Enables stompjs debug logs and additional info
7439
7561
  */
7440
- WebsocketService.prototype.onConnect = function () {
7441
- return this.connected$.asObservable().pipe(operators.filter(Boolean), operators.map(function () { return undefined; }), operators.take(1));
7562
+ WebsocketService.prototype.enableDebugLogs = function () {
7563
+ this.debugEnable = true;
7442
7564
  };
7443
7565
  /**
7444
- * Observable responsável por emitir uma notificação quando a conexão é desconectada.
7445
- * @return Um `Observable<void>` que emite uma notificação quando a conexão é desconectada.
7566
+ * Manually starts the connection
7446
7567
  */
7447
- WebsocketService.prototype.onDisconnect = function () {
7448
- return this.disconnect$.asObservable();
7568
+ WebsocketService.prototype.connect = function () {
7569
+ return __awaiter(this, void 0, void 0, function () {
7570
+ var stompConfig;
7571
+ var _this = this;
7572
+ return __generator(this, function (_a) {
7573
+ switch (_a.label) {
7574
+ case 0: return [4 /*yield*/, this.connectionLock.acquire()];
7575
+ case 1:
7576
+ _a.sent();
7577
+ _a.label = 2;
7578
+ case 2:
7579
+ _a.trys.push([2, , 3, 5]);
7580
+ if (this.isConnected() || this.isConnecting()) {
7581
+ return [2 /*return*/];
7582
+ }
7583
+ this.lostConnection = false;
7584
+ stompConfig = {
7585
+ webSocketFactory: function () {
7586
+ return new SockJS(_this.getSubscriptionUrl(), null, {
7587
+ timeout: CONNECTION_TIMEOUT_MILLISECONDS
7588
+ });
7589
+ },
7590
+ connectionTimeout: CONNECTION_TIMEOUT_MILLISECONDS,
7591
+ reconnectDelay: RECONNECT_INTERVAL_MILLISECONDS,
7592
+ debug: this.debug.bind(this),
7593
+ onConnect: this.handleOnConnected.bind(this),
7594
+ onDisconnect: this.handleOnDisconnect.bind(this),
7595
+ onWebSocketClose: this.handleOnWebSocketClose.bind(this),
7596
+ onStompError: this.handleOnStompError.bind(this),
7597
+ onWebSocketError: this.handleOnWebSocketError.bind(this)
7598
+ };
7599
+ this.debug('Connecting the Webscoket');
7600
+ this.stompClient = new stompjs.Client(stompConfig);
7601
+ this.stompClient.activate();
7602
+ return [3 /*break*/, 5];
7603
+ case 3: return [4 /*yield*/, this.connectionLock.release()];
7604
+ case 4:
7605
+ _a.sent();
7606
+ return [7 /*endfinally*/];
7607
+ case 5: return [2 /*return*/];
7608
+ }
7609
+ });
7610
+ });
7449
7611
  };
7450
7612
  /**
7451
- * Observable responsável por emitir uma notificação quando a conexão é reconectada.
7452
- * @return Um `Observable<void>` que emite uma notificação quando a conexão é reconectada.
7613
+ * Manually disconnect the websocket. The reconnect loop will be stopped.
7453
7614
  */
7454
- WebsocketService.prototype.onReconnect = function () {
7455
- return this.reconnect$.asObservable();
7615
+ WebsocketService.prototype.disconnect = function () {
7616
+ return __awaiter(this, void 0, void 0, function () {
7617
+ var _a, _b, primitiveManager;
7618
+ var e_1, _c;
7619
+ return __generator(this, function (_d) {
7620
+ switch (_d.label) {
7621
+ case 0:
7622
+ if (!this.isConnected()) {
7623
+ return [2 /*return*/];
7624
+ }
7625
+ return [4 /*yield*/, this.connectionLock.acquire()];
7626
+ case 1:
7627
+ _d.sent();
7628
+ _d.label = 2;
7629
+ case 2:
7630
+ _d.trys.push([2, , 5, 7]);
7631
+ try {
7632
+ for (_a = __values(this.primitiveManagers.values()), _b = _a.next(); !_b.done; _b = _a.next()) {
7633
+ primitiveManager = _b.value;
7634
+ primitiveManager.unsubscribe();
7635
+ }
7636
+ }
7637
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
7638
+ finally {
7639
+ try {
7640
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
7641
+ }
7642
+ finally { if (e_1) throw e_1.error; }
7643
+ }
7644
+ this.primitiveManagers.clear();
7645
+ this.connected$.next(false);
7646
+ if (!this.stompClient) return [3 /*break*/, 4];
7647
+ return [4 /*yield*/, this.stompClient.deactivate()];
7648
+ case 3:
7649
+ _d.sent();
7650
+ _d.label = 4;
7651
+ case 4: return [3 /*break*/, 7];
7652
+ case 5: return [4 /*yield*/, this.connectionLock.release()];
7653
+ case 6:
7654
+ _d.sent();
7655
+ return [7 /*endfinally*/];
7656
+ case 7: return [2 /*return*/];
7657
+ }
7658
+ });
7659
+ });
7456
7660
  };
7457
7661
  /**
7458
- * Observable responsável por emitir uma notificação após o subscribe do evento pela primeira vez.
7459
- * @return Um `Observable<void>` que emite uma notificação após o subscribe do evento pela primeira vez.
7662
+ * Check if the websocket is connected
7663
+ * @return `boolean` representing if the websocket is connected
7460
7664
  */
7461
- WebsocketService.prototype.onSubscribe = function (_a) {
7462
- var _this = this;
7463
- var domain = _a.domain, service = _a.service, primitive = _a.primitive;
7464
- var key = this.getPrimitiveManagerKey(domain, service, primitive);
7465
- return this.onConnect().pipe(operators.switchMap(function () {
7466
- if (_this.primitiveManagers.has(key))
7467
- return _this.primitiveManagers
7468
- .get(key)
7469
- .subscribed$.asObservable()
7470
- .pipe(operators.map(function () { return undefined; }), operators.take(1));
7471
- return _this.subscribed$.asObservable().pipe(operators.filter(function (primitiveManager) {
7472
- return _this.getPrimitiveManagerKey(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive) === key;
7473
- }), operators.map(function () { return undefined; }), operators.take(1));
7474
- }));
7665
+ WebsocketService.prototype.isConnected = function () {
7666
+ if (!this.stompClient) {
7667
+ return false;
7668
+ }
7669
+ return this.stompClient.connected;
7670
+ };
7671
+ /**
7672
+ * Check if the websocket is tring to connect
7673
+ * @return `boolean` representing if the websocket status
7674
+ */
7675
+ WebsocketService.prototype.isConnecting = function () {
7676
+ if (!this.stompClient) {
7677
+ return false;
7678
+ }
7679
+ return !this.stompClient.connected && this.stompClient.active;
7680
+ };
7681
+ /**
7682
+ * Event responsable to emit an event when the connection is established.
7683
+ * Do not forget to unsubscribe the observable when you don't need it anymore.
7684
+ * @return `Observable<boolean>`
7685
+ */
7686
+ WebsocketService.prototype.onConnect = function () {
7687
+ return this.connected$.asObservable()
7688
+ .pipe(operators.filter(function (p) { return p === true; }));
7689
+ };
7690
+ /**
7691
+ * Event responsable to emit an event when the connection is closed.
7692
+ * Do not forget to unsubscribe the observable when you don't need it anymore.
7693
+ * @return `Observable<void>`
7694
+ */
7695
+ WebsocketService.prototype.onDisconnect = function () {
7696
+ return this.disconnected$.asObservable();
7697
+ };
7698
+ /**
7699
+ * Event responsable to emit an event when the connection is reestablished.
7700
+ * Do not forget to unsubscribe the observable when you don't need it anymore.
7701
+ * @return `Observable<void>`
7702
+ */
7703
+ WebsocketService.prototype.onReconnect = function () {
7704
+ return this.reconnected$.asObservable();
7475
7705
  };
7476
7706
  /**
7477
- * Observable responsável por emitir uma notificação quando ocorre algum erro.
7478
- * @return Um `Observable<FrameImpl>` que emite uma notificação quando ocorre algum erro.
7707
+ * Event responsable to emit an event when an error ocurred.
7708
+ * Do not forget to unsubscribe the observable when you don't need it anymore.
7709
+ * @return `Observable<FrameImpl>`
7479
7710
  */
7480
7711
  WebsocketService.prototype.onError = function () {
7481
7712
  return this.error$.asObservable();
7482
7713
  };
7483
7714
  /**
7484
- * @typeParam `<T>` Tipo do objeto que o retorno do `observable` vai devolver.
7485
- * @param {Object} options Objeto de configuração do evento.
7486
- * @param {string} options.domain Domínio da primitiva.
7487
- * @param {string} options.service Serviço da primitiva.
7488
- * @param {string} options.primitive Primitiva que será "observada".
7489
- * @return Um Observable<T> que emite notificações toda vez que o respectivo evento é publicado.
7715
+ * Event responsible to emit an event when a primitive is called.
7716
+ * Do not forget to unsubscribe the observable when you don't need it anymore.
7717
+ * @typeParam `<T>` Object type that will be used in the observable for the `data` property.
7718
+ * @param {OnEventOptions} options Configurations for the event.
7719
+ * @return `Observable<PrimitiveEvent<T>>` Observable that emits an event when the service calls the primitive.
7490
7720
  */
7491
7721
  WebsocketService.prototype.onEvent = function (options) {
7492
7722
  var _this = this;
7493
- this.connect();
7494
7723
  var domain = options.domain, service = options.service, primitive = options.primitive;
7495
- var key = this.getPrimitiveManagerKey(domain, service, primitive);
7724
+ var key = this.buildPrimitiveManagerKey(domain, service, primitive);
7496
7725
  if (this.primitiveManagers.has(key)) {
7497
- return this.primitiveManagers.get(key).event$.asObservable();
7726
+ return this.primitiveManagers.get(key).getEventObservable();
7498
7727
  }
7499
- var primitiveManager = {
7500
- domain: domain,
7501
- service: service,
7502
- primitive: primitive,
7503
- stompSubscriptions: [],
7504
- event$: new rxjs.Subject(),
7505
- subscribed$: new rxjs.BehaviorSubject(false)
7506
- };
7728
+ var primitiveManager = new PrimitiveManager(domain, service, primitive);
7507
7729
  this.primitiveManagers.set(key, primitiveManager);
7508
- this.onConnect()
7509
- .pipe(operators.take(1))
7510
- .subscribe(function () {
7511
- _this.createStompSubscriptions(primitiveManager);
7730
+ this.connect().then(function () {
7731
+ _this.onConnect()
7732
+ .pipe(operators.take(1))
7733
+ .subscribe(function () {
7734
+ _this.createStompSubscriptions(primitiveManager);
7735
+ });
7512
7736
  });
7513
- return primitiveManager.event$
7514
- .asObservable()
7515
- .pipe(operators.finalize(function () { return _this.disconnectPrimitiveOnFinalize(primitiveManager); }));
7737
+ return primitiveManager
7738
+ .getEventObservable()
7739
+ .pipe(operators.finalize(function () { return _this.unsubscribePrimitiveOnFinalize(primitiveManager); }));
7516
7740
  };
7517
- /** @private */
7518
- WebsocketService.prototype.createStompSubscriptions = function (primitiveManager) {
7519
- var withTokenUrl = this.getSubscriptionUrlWithToken(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
7520
- var stompSubscriptionWithToken = this.createStompSubscription(withTokenUrl, primitiveManager);
7521
- var withoutTokenUrl = this.getSubscriptionUrlWithoutToken(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
7522
- var stompSubscriptionWithoutToken = this.createStompSubscription(withoutTokenUrl, primitiveManager);
7523
- primitiveManager.stompSubscriptions = [
7524
- stompSubscriptionWithToken,
7525
- stompSubscriptionWithoutToken
7526
- ];
7527
- primitiveManager.subscribed$.next(true);
7528
- this.subscribed$.next(primitiveManager);
7529
- };
7530
- /** @private */
7531
- WebsocketService.prototype.connect = function () {
7741
+ /**
7742
+ * Event responsible to emit an event when a subscription is created for the primitive.
7743
+ * Do not forget to unsubscribe the observable when you don't need it anymore.
7744
+ * @param {OnEventOptions} options Configurations for the event.
7745
+ * Observable responsável por emitir uma notificação após o subscribe do evento pela primeira vez.
7746
+ * @return `Observable<boolean>` Observable that emits an event when the service calls the primitive.
7747
+ */
7748
+ WebsocketService.prototype.onSubscribe = function (options) {
7532
7749
  var _this = this;
7533
- if (this.isConnected || this.isConnecting)
7534
- return;
7535
- this.createStompClient();
7536
- this.isConnecting = true;
7537
- this._stompClient.connect({}, function () {
7538
- _this.isConnecting = false;
7539
- _this.isConnected = true;
7540
- if (_this.wasConnected) {
7541
- _this.reconnectPrimitives();
7542
- _this.connected$.next(true);
7543
- _this.reconnect$.next();
7750
+ var domain = options.domain, service = options.service, primitive = options.primitive;
7751
+ var key = this.buildPrimitiveManagerKey(domain, service, primitive);
7752
+ return this.onConnect().pipe(operators.take(1), operators.switchMap(function () {
7753
+ if (_this.primitiveManagers.has(key)) {
7754
+ return _this.primitiveManagers
7755
+ .get(key)
7756
+ .getSubscriptionObservable()
7757
+ .pipe(operators.take(1));
7544
7758
  }
7545
- else {
7546
- _this.wasConnected = true;
7547
- _this.connected$.next(true);
7548
- }
7549
- }, function (error) {
7550
- _this.isConnected = false;
7551
- _this.connected$.next(false);
7552
- _this.error$.next(error);
7553
- rxjs.race(_this.disconnect$.pipe(operators.take(1), operators.map(function () { return ({ wasDisconnected: true }); })), rxjs.timer(WebsocketService_1.RECONNECT_INTERVAL).pipe(operators.take(1), operators.switchMap(function () {
7554
- return rxjs.iif(function () { return document.hidden; }, rxjs.fromEvent(document, 'visibilitychange').pipe(operators.first()), rxjs.of(void 0));
7555
- }), operators.map(function () { return ({ wasDisconnected: false }); })))
7556
- .pipe(operators.take(1))
7557
- .subscribe({
7558
- next: function (_a) {
7559
- var wasDisconnected = _a.wasDisconnected;
7560
- if (!wasDisconnected &&
7561
- !(_this.isConnected || _this.isConnecting)) {
7562
- _this.connect();
7563
- }
7564
- }
7565
- });
7566
- });
7759
+ return _this.subscribed$.asObservable().pipe(operators.filter(function (primitiveManager) {
7760
+ return _this.buildPrimitiveManagerKey(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive) === key;
7761
+ }), operators.map(function () { return true; }), operators.take(1));
7762
+ }));
7567
7763
  };
7568
- WebsocketService.prototype.disconnect = function () {
7569
- var e_1, _a, e_2, _b, e_3, _c;
7570
- if (!this.isConnected || this.getObserversCount() > 0) {
7764
+ WebsocketService.prototype.debug = function (message) {
7765
+ var optionalParams = [];
7766
+ for (var _i = 1; _i < arguments.length; _i++) {
7767
+ optionalParams[_i - 1] = arguments[_i];
7768
+ }
7769
+ if (!this.debugEnable) {
7571
7770
  return;
7572
7771
  }
7573
- try {
7574
- for (var _d = __values(this.primitiveManagers.values()), _e = _d.next(); !_e.done; _e = _d.next()) {
7575
- var primitiveManager = _e.value;
7576
- try {
7577
- for (var _f = (e_2 = void 0, __values(primitiveManager.stompSubscriptions)), _g = _f.next(); !_g.done; _g = _f.next()) {
7578
- var stompSubscription = _g.value;
7579
- stompSubscription.unsubscribe();
7580
- }
7581
- }
7582
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
7583
- finally {
7584
- try {
7585
- if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
7586
- }
7587
- finally { if (e_2) throw e_2.error; }
7588
- }
7589
- }
7772
+ console.log.apply(console, __spread(['WS debug: ' + message], optionalParams));
7773
+ };
7774
+ WebsocketService.prototype.info = function (message) {
7775
+ console.info('WS info: ' + message);
7776
+ };
7777
+ WebsocketService.prototype.handleOnConnected = function () {
7778
+ this.info('Webscoket connected');
7779
+ this.connected$.next(true);
7780
+ if (this.lostConnection) {
7781
+ this.info('Webscoket reconnected, recriating subscriptions');
7782
+ this.handleReconnection();
7590
7783
  }
7591
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
7592
- finally {
7593
- try {
7594
- if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
7595
- }
7596
- finally { if (e_1) throw e_1.error; }
7784
+ };
7785
+ WebsocketService.prototype.handleOnDisconnect = function () {
7786
+ this.info('Webscoket disconnected');
7787
+ this.connected$.next(false);
7788
+ this.disconnected$.next();
7789
+ };
7790
+ WebsocketService.prototype.handleOnWebSocketClose = function (data) {
7791
+ if (data.reason && data.reason.toLowerCase().indexOf("go away") !== -1) {
7792
+ this.lostConnection = true;
7793
+ this.handleError('AuthenticationError', new stompjs.FrameImpl({
7794
+ command: data.type,
7795
+ headers: {
7796
+ message: data.reason
7797
+ }
7798
+ }));
7799
+ return;
7597
7800
  }
7598
- try {
7599
- for (var _h = __values(this.primitiveManagers.values()), _j = _h.next(); !_j.done; _j = _h.next()) {
7600
- var primitiveManager = _j.value;
7601
- primitiveManager.event$.complete();
7602
- }
7801
+ if (data.wasClean) {
7802
+ return;
7603
7803
  }
7604
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
7605
- finally {
7606
- try {
7607
- if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
7608
- }
7609
- finally { if (e_3) throw e_3.error; }
7804
+ this.lostConnection = true;
7805
+ };
7806
+ WebsocketService.prototype.handleOnStompError = function (data) {
7807
+ this.handleError('StompError', data);
7808
+ if (this.isAuthenticationError(data)) {
7809
+ this.info('Authentication error, recriating subscriptions');
7810
+ this.handleReconnection();
7610
7811
  }
7611
- this.primitiveManagers.clear();
7612
- this._stompClient.disconnect();
7613
- this._stompClient.deactivate();
7614
- this.isConnected = false;
7615
- this.isConnecting = false;
7616
- this.wasConnected = false;
7617
- this.connected$.next(false);
7618
- this.disconnect$.next();
7619
7812
  };
7620
- /** @private */
7621
- WebsocketService.prototype.getSubscriptionUrlWithToken = function (domain, service, primitive) {
7622
- var tenant = WebsocketService_1.TOKEN
7623
- ? WebsocketService_1.TOKEN.username.split('@')[1]
7624
- : null;
7625
- var token = WebsocketService_1.TOKEN
7626
- ? WebsocketService_1.TOKEN.access_token
7627
- : null;
7628
- return "/topic/" + tenant + "/" + token + "/" + domain + "/" + service + "/" + primitive;
7813
+ WebsocketService.prototype.isAuthenticationError = function (data) {
7814
+ var _a;
7815
+ var errorMessage = (_a = data === null || data === void 0 ? void 0 : data.headers) === null || _a === void 0 ? void 0 : _a.message;
7816
+ if (!errorMessage) {
7817
+ return false;
7818
+ }
7819
+ return errorMessage.toLowerCase().indexOf('forbiddenexception') !== -1;
7629
7820
  };
7630
- /** @private */
7631
- WebsocketService.prototype.getSubscriptionUrlWithoutToken = function (domain, service, primitive) {
7632
- var tenant = WebsocketService_1.TOKEN
7633
- ? WebsocketService_1.TOKEN.username.split('@')[1]
7634
- : null;
7635
- return "/topic/" + tenant + "/" + domain + "/" + service + "/" + primitive;
7821
+ WebsocketService.prototype.handleOnWebSocketError = function (data) {
7822
+ this.handleError('WebSocketError', data);
7636
7823
  };
7637
- /** @private */
7638
- WebsocketService.prototype.createStompSubscription = function (destination, primitiveManager) {
7639
- return this._stompClient.subscribe(destination, function (message) {
7640
- var event = JSON.parse(message.body || '{}');
7641
- primitiveManager.event$.next(event);
7642
- });
7824
+ WebsocketService.prototype.handleError = function (origin, data) {
7825
+ console.error(origin, data);
7826
+ this.error$.next(data);
7643
7827
  };
7644
- /** @private */
7645
- WebsocketService.prototype.createStompClient = function () {
7646
- var ws = new SockJS(WebsocketService_1.WEBSOCKET_URL + "subscription", null, { timeout: WebsocketService_1.CONNECTION_TIMEOUT });
7647
- this._stompClient = stompjs.Stomp.over(ws);
7648
- this._stompClient.debug = function () { return null; };
7828
+ WebsocketService.prototype.handleReconnection = function () {
7829
+ this.lostConnection = false;
7830
+ this.reconnectPrimitives();
7831
+ this.reconnected$.next();
7649
7832
  };
7650
- /** @private */
7651
7833
  WebsocketService.prototype.reconnectPrimitives = function () {
7652
- var e_4, _a;
7834
+ var e_2, _a;
7653
7835
  try {
7654
7836
  for (var _b = __values(this.primitiveManagers.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
7655
7837
  var primitiveManager = _c.value;
7656
7838
  this.createStompSubscriptions(primitiveManager);
7657
7839
  }
7658
7840
  }
7659
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
7841
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
7660
7842
  finally {
7661
7843
  try {
7662
7844
  if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
7663
7845
  }
7664
- finally { if (e_4) throw e_4.error; }
7846
+ finally { if (e_2) throw e_2.error; }
7665
7847
  }
7666
7848
  };
7667
- /** @private */
7849
+ WebsocketService.prototype.buildSubscriptionUrlWithToken = function (domain, service, primitive) {
7850
+ var authToken = this.userInformationService.getAuthToken();
7851
+ var tenant = this.userInformationService.getTenantDomain();
7852
+ return "/topic/" + tenant + "/" + authToken + "/" + domain + "/" + service + "/" + primitive;
7853
+ };
7854
+ WebsocketService.prototype.getSubscriptionUrlWithoutToken = function (domain, service, primitive) {
7855
+ var tenant = this.userInformationService.getTenantDomain();
7856
+ return "/topic/" + tenant + "/" + domain + "/" + service + "/" + primitive;
7857
+ };
7858
+ WebsocketService.prototype.buildPrimitiveManagerKey = function (domain, service, primitive) {
7859
+ return domain + "/" + service + "/" + primitive;
7860
+ };
7861
+ WebsocketService.prototype.unsubscribePrimitiveOnFinalize = function (primitiveManager) {
7862
+ return __awaiter(this, void 0, void 0, function () {
7863
+ var key;
7864
+ return __generator(this, function (_a) {
7865
+ switch (_a.label) {
7866
+ case 0:
7867
+ if (primitiveManager.hasObservers()) {
7868
+ return [2 /*return*/];
7869
+ }
7870
+ primitiveManager.unsubscribe();
7871
+ key = this.buildPrimitiveManagerKey(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
7872
+ this.primitiveManagers.delete(key);
7873
+ return [4 /*yield*/, this.disconnectIfNoMoreObservables()];
7874
+ case 1:
7875
+ _a.sent();
7876
+ return [2 /*return*/];
7877
+ }
7878
+ });
7879
+ });
7880
+ };
7881
+ WebsocketService.prototype.disconnectIfNoMoreObservables = function () {
7882
+ return __awaiter(this, void 0, void 0, function () {
7883
+ return __generator(this, function (_a) {
7884
+ switch (_a.label) {
7885
+ case 0:
7886
+ if (!(this.getObserversCount() === 0)) return [3 /*break*/, 2];
7887
+ this.debug('Manually disconnecting because there are no more observers');
7888
+ return [4 /*yield*/, this.disconnect()];
7889
+ case 1:
7890
+ _a.sent();
7891
+ _a.label = 2;
7892
+ case 2: return [2 /*return*/];
7893
+ }
7894
+ });
7895
+ });
7896
+ };
7668
7897
  WebsocketService.prototype.getObserversCount = function () {
7669
- var e_5, _a;
7670
7898
  var observersCount = 0;
7671
- try {
7672
- for (var _b = __values(this.primitiveManagers.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
7673
- var primitiveManager = _c.value;
7674
- observersCount += primitiveManager.event$.observers.length;
7675
- }
7676
- }
7677
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
7678
- finally {
7679
- try {
7680
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
7681
- }
7682
- finally { if (e_5) throw e_5.error; }
7683
- }
7899
+ this.primitiveManagers.forEach(function (primitiveManager) {
7900
+ observersCount += primitiveManager.getObserversCount();
7901
+ });
7684
7902
  return observersCount;
7685
7903
  };
7686
- /** @private */
7687
- WebsocketService.prototype.disconnectPrimitiveOnFinalize = function (primitiveManager) {
7688
- var e_6, _a;
7689
- // @IMPORTANT: Replace .observers.length === 1 with .observed in rxjs 7.0+
7690
- var hasObservers = !(primitiveManager.event$.observers.length === 1);
7691
- if (hasObservers)
7692
- return;
7693
- primitiveManager.event$.complete();
7694
- try {
7695
- for (var _b = __values(primitiveManager.stompSubscriptions), _c = _b.next(); !_c.done; _c = _b.next()) {
7696
- var stompSubscription = _c.value;
7697
- stompSubscription.unsubscribe();
7698
- }
7699
- }
7700
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
7701
- finally {
7702
- try {
7703
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
7704
- }
7705
- finally { if (e_6) throw e_6.error; }
7706
- }
7707
- primitiveManager.subscribed$.complete();
7708
- var key = this.getPrimitiveManagerKey(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
7709
- this.primitiveManagers.delete(key);
7710
- this.disconnect();
7904
+ WebsocketService.prototype.createStompSubscription = function (destination, primitiveManager) {
7905
+ return this.stompClient.subscribe(destination, function (message) {
7906
+ var event = JSON.parse(message.body || '{}');
7907
+ primitiveManager.fireEvent(event);
7908
+ });
7711
7909
  };
7712
- /** @private */
7713
- WebsocketService.prototype.getPrimitiveManagerKey = function (domain, service, primitive) {
7714
- return domain + "/" + service + "/" + primitive;
7910
+ WebsocketService.prototype.createStompSubscriptions = function (primitiveManager) {
7911
+ var subscriptionUrlWithToken = this.buildSubscriptionUrlWithToken(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
7912
+ var subscriptionUrlWithoutToken = this.getSubscriptionUrlWithoutToken(primitiveManager.domain, primitiveManager.service, primitiveManager.primitive);
7913
+ var stompSubscriptionWithToken = this.createStompSubscription(subscriptionUrlWithToken, primitiveManager);
7914
+ var stompSubscriptionWithoutToken = this.createStompSubscription(subscriptionUrlWithoutToken, primitiveManager);
7915
+ primitiveManager.subscribe(stompSubscriptionWithToken, stompSubscriptionWithoutToken);
7916
+ this.subscribed$.next(primitiveManager);
7917
+ };
7918
+ WebsocketService.prototype.getSubscriptionUrl = function () {
7919
+ return this.userInformationService.getWebSocketUrl() + "/subscription";
7715
7920
  };
7716
- var WebsocketService_1;
7717
- WebsocketService.RECONNECT_INTERVAL = 3000;
7718
- WebsocketService.CONNECTION_TIMEOUT = 15000;
7719
- /** @private */
7720
- WebsocketService.BASE_URL_COOKIE = 'com.senior.base.url';
7721
- /** @private */
7722
- WebsocketService.TOKEN_COOKIE = 'com.senior.token';
7723
- /** @private */
7724
- WebsocketService.TOKEN = JSON.parse(jsCookie.get(WebsocketService_1.TOKEN_COOKIE) || '{}');
7725
- /** @private */
7726
- WebsocketService.WEBSOCKET_URL = jsCookie.get(WebsocketService_1.BASE_URL_COOKIE) + '/websocket/';
7727
- WebsocketService.ɵprov = core.ɵɵdefineInjectable({ factory: function WebsocketService_Factory() { return new WebsocketService(); }, token: WebsocketService, providedIn: "root" });
7728
- WebsocketService = WebsocketService_1 = __decorate([
7921
+ WebsocketService.ctorParameters = function () { return [
7922
+ { type: UserInformationService }
7923
+ ]; };
7924
+ WebsocketService.ɵprov = core.ɵɵdefineInjectable({ factory: function WebsocketService_Factory() { return new WebsocketService(core.ɵɵinject(UserInformationService)); }, token: WebsocketService, providedIn: "root" });
7925
+ WebsocketService = __decorate([
7729
7926
  core.Injectable({
7730
7927
  providedIn: 'root'
7731
7928
  })
@@ -7996,6 +8193,7 @@
7996
8193
  exports.NotaFiscalEntradaLookup = NotaFiscalEntradaLookup;
7997
8194
  exports.NpsService = NpsService;
7998
8195
  exports.ParametersLookup = ParametersLookup;
8196
+ exports.PrimitiveManager = PrimitiveManager;
7999
8197
  exports.ProdutoServicoLookup = ProdutoServicoLookup;
8000
8198
  exports.QuantidadeDisponivelDemandaLookup = QuantidadeDisponivelDemandaLookup;
8001
8199
  exports.RequisicaoLookup = RequisicaoLookup;
@@ -8010,8 +8208,9 @@
8010
8208
  exports.ɵ0 = ɵ0;
8011
8209
  exports.ɵa = ErpLookupsService;
8012
8210
  exports.ɵd = StorageService;
8013
- exports.ɵe = VerifyModulePermissionService;
8014
- exports.ɵf = VerifyModulePermissionsService;
8211
+ exports.ɵe = UserInformationService;
8212
+ exports.ɵf = VerifyModulePermissionService;
8213
+ exports.ɵg = VerifyModulePermissionsService;
8015
8214
 
8016
8215
  Object.defineProperty(exports, '__esModule', { value: true });
8017
8216