active-connect-ng2 0.2.40 → 0.2.41

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 (53) hide show
  1. package/ng-package.json +7 -0
  2. package/package.json +13 -32
  3. package/src/lib/active-connect-ng2.module.ts +34 -0
  4. package/src/lib/websocket/client.ts +438 -0
  5. package/src/lib/websocket/decorators/function.ts +44 -0
  6. package/src/lib/websocket/decorators/websocket/handle.ts +12 -0
  7. package/src/lib/websocket/decorators/websocket/on-reconnect.ts +6 -0
  8. package/src/lib/websocket/decorators/websocket/on-success.ts +11 -0
  9. package/src/lib/websocket/decorators/websocket/outbound.ts +212 -0
  10. package/src/lib/websocket/decorators/websocket/route.ts +32 -0
  11. package/src/lib/websocket/decorators/websocket/shared.ts +11 -0
  12. package/{lib/websocket/decorators/websocket/websocket-route-service.d.ts → src/lib/websocket/decorators/websocket/websocket-route-service.ts} +3 -2
  13. package/src/lib/websocket/json/json-parser.ts +26 -0
  14. package/src/lib/websocket/lifecycle/loading-status.ts +32 -0
  15. package/src/lib/websocket/objects/outbound-object.ts +430 -0
  16. package/{public-api.d.ts → src/public-api.ts} +4 -0
  17. package/tsconfig.lib.json +14 -0
  18. package/tsconfig.lib.prod.json +10 -0
  19. package/tsconfig.spec.json +14 -0
  20. package/esm2020/active-connect-ng2.mjs +0 -5
  21. package/esm2020/lib/active-connect-ng2.module.mjs +0 -42
  22. package/esm2020/lib/websocket/client.mjs +0 -347
  23. package/esm2020/lib/websocket/decorators/function.mjs +0 -40
  24. package/esm2020/lib/websocket/decorators/websocket/handle.mjs +0 -9
  25. package/esm2020/lib/websocket/decorators/websocket/on-reconnect.mjs +0 -6
  26. package/esm2020/lib/websocket/decorators/websocket/on-success.mjs +0 -8
  27. package/esm2020/lib/websocket/decorators/websocket/outbound.mjs +0 -213
  28. package/esm2020/lib/websocket/decorators/websocket/route.mjs +0 -31
  29. package/esm2020/lib/websocket/decorators/websocket/shared.mjs +0 -10
  30. package/esm2020/lib/websocket/decorators/websocket/websocket-route-service.mjs +0 -2
  31. package/esm2020/lib/websocket/index.mjs +0 -11
  32. package/esm2020/lib/websocket/json/json-parser.mjs +0 -23
  33. package/esm2020/lib/websocket/lifecycle/loading-status.mjs +0 -31
  34. package/esm2020/lib/websocket/objects/outbound-object.mjs +0 -398
  35. package/esm2020/public-api.mjs +0 -7
  36. package/fesm2015/active-connect-ng2.mjs +0 -1178
  37. package/fesm2015/active-connect-ng2.mjs.map +0 -1
  38. package/fesm2020/active-connect-ng2.mjs +0 -1160
  39. package/fesm2020/active-connect-ng2.mjs.map +0 -1
  40. package/index.d.ts +0 -5
  41. package/lib/active-connect-ng2.module.d.ts +0 -7
  42. package/lib/websocket/client.d.ts +0 -59
  43. package/lib/websocket/decorators/function.d.ts +0 -30
  44. package/lib/websocket/decorators/websocket/handle.d.ts +0 -1
  45. package/lib/websocket/decorators/websocket/on-reconnect.d.ts +0 -1
  46. package/lib/websocket/decorators/websocket/on-success.d.ts +0 -1
  47. package/lib/websocket/decorators/websocket/outbound.d.ts +0 -1
  48. package/lib/websocket/decorators/websocket/route.d.ts +0 -1
  49. package/lib/websocket/decorators/websocket/shared.d.ts +0 -4
  50. package/lib/websocket/json/json-parser.d.ts +0 -5
  51. package/lib/websocket/lifecycle/loading-status.d.ts +0 -9
  52. package/lib/websocket/objects/outbound-object.d.ts +0 -48
  53. /package/{lib/websocket/index.d.ts → src/lib/websocket/index.ts} +0 -0
@@ -1,1178 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { NgModule } from '@angular/core';
3
- import * as i1 from 'ngx-indexed-db';
4
- import { NgxIndexedDBModule } from 'ngx-indexed-db';
5
- export { NgxIndexedDBService } from 'ngx-indexed-db';
6
- import { __awaiter } from 'tslib';
7
- import { Observable } from 'rxjs';
8
-
9
- const dbConfig = {
10
- name: 'activeconnect_cache',
11
- version: 2,
12
- objectStoresMeta: [
13
- {
14
- store: 'outbound',
15
- storeConfig: { keyPath: 'method', autoIncrement: false },
16
- storeSchema: [
17
- { name: 'method', keypath: 'method', options: { unique: true } },
18
- { name: 'data', keypath: 'data', options: { unique: false } },
19
- {
20
- name: 'specificHash',
21
- keypath: 'specificHash',
22
- options: { unique: false },
23
- },
24
- {
25
- name: 'length',
26
- keypath: 'length',
27
- options: { unique: false },
28
- },
29
- ],
30
- },
31
- ],
32
- };
33
- class ActiveConnectNg2Module {
34
- }
35
- ActiveConnectNg2Module.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
36
- ActiveConnectNg2Module.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, imports: [i1.NgxIndexedDBModule], exports: [NgxIndexedDBModule] });
37
- ActiveConnectNg2Module.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, imports: [NgxIndexedDBModule.forRoot(dbConfig), NgxIndexedDBModule] });
38
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.9", ngImport: i0, type: ActiveConnectNg2Module, decorators: [{
39
- type: NgModule,
40
- args: [{
41
- declarations: [],
42
- imports: [NgxIndexedDBModule.forRoot(dbConfig)],
43
- exports: [NgxIndexedDBModule],
44
- }]
45
- }] });
46
-
47
- class JsonParser {
48
- static stringify(obj) {
49
- return JSON.stringify(obj);
50
- }
51
- static parsingFunction(key, value) {
52
- var a;
53
- if (typeof value === "string") {
54
- a =
55
- /^[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}\:[0-9]{2}\:[0-9]{2}\.[0-9]{3}Z$/.exec(value);
56
- if (a) {
57
- return new Date(a);
58
- }
59
- }
60
- return value;
61
- }
62
- static parse(str) {
63
- if (str && str != "undefined") {
64
- return JSON.parse(str, JsonParser.parsingFunction);
65
- }
66
- return str;
67
- }
68
- }
69
-
70
- class WebsocketClient {
71
- constructor(url, supportsCache, dbService) {
72
- this.url = url;
73
- this.supportsCache = supportsCache;
74
- this.dbService = dbService;
75
- this.requestStack = [];
76
- this.requestHistoryLogs = [];
77
- this._token = '';
78
- this.connectionEstablishedOnce = false;
79
- this.messageId = 0;
80
- this.rejectCallbacks = new Map();
81
- this.expectedMethods = new Map();
82
- this.closed = false;
83
- if (supportsCache)
84
- this.initCache();
85
- if (!url) {
86
- let protocol;
87
- let port;
88
- switch (document.location.protocol) {
89
- case 'https:': {
90
- protocol = 'wss:';
91
- port = ':443';
92
- break;
93
- }
94
- default: {
95
- protocol = 'ws:';
96
- port = ':80';
97
- break;
98
- }
99
- }
100
- this.url = protocol + '//' + document.location.hostname + port + '/wss';
101
- }
102
- this.connect(this.url);
103
- }
104
- connect(url) {
105
- if (!this.subject) {
106
- this.create(url);
107
- }
108
- return this.subject;
109
- }
110
- initTabSuspendedListener() {
111
- if (document) {
112
- document.addEventListener('visibilitychange', () => {
113
- if (document.visibilityState === 'hidden') {
114
- console.log('ActiveConnect: Closing WebSocket due to tab suspension...');
115
- this.disconnect(true);
116
- }
117
- else if (document.visibilityState === 'visible') {
118
- console.log('ActiveConnect: Reconnecting WebSocket...');
119
- this.connect(this.url);
120
- }
121
- });
122
- }
123
- }
124
- logEntry(method) {
125
- this.requestHistoryLogs.push({ timestamp: new Date(Date.now()), method });
126
- }
127
- get logs() {
128
- return this.requestHistoryLogs;
129
- }
130
- get Token() {
131
- if (!this._token) {
132
- if (window.localStorage)
133
- this._token = window.localStorage.getItem('token') || '';
134
- }
135
- return this._token;
136
- }
137
- set Token(val) {
138
- this._token = val;
139
- if (window.localStorage)
140
- window.localStorage.setItem('token', val);
141
- }
142
- set Connected(value) {
143
- if (value) {
144
- this.sendBrowserInfoToServer();
145
- this.auth(this.Token).then(() => {
146
- Promise.all(WebsocketClient.onReconnectCallback.map((c) => c.Func ? c.Func() : null)).then(() => {
147
- setTimeout(() => {
148
- this.resetRequestedState();
149
- this.requestStack.forEach((e) => {
150
- this.sendToSocket(e.method, e.data);
151
- this.requestStack = this.requestStack.filter((e1) => e1 != e);
152
- });
153
- }, 2000);
154
- });
155
- });
156
- }
157
- if (this.pool && this.pool.WssConnected)
158
- this.pool.WssConnected = value;
159
- }
160
- resetRequestedState() {
161
- if (this.connectionEstablishedOnce) {
162
- // reset requested state for outbounds
163
- WebsocketClient.resetRequestedStateCallbacks.forEach((reset) => {
164
- reset();
165
- });
166
- }
167
- else {
168
- this.connectionEstablishedOnce = true;
169
- }
170
- }
171
- static addResetRequestingStateCallback(callback) {
172
- WebsocketClient.resetRequestedStateCallbacks.push(callback);
173
- }
174
- create(url) {
175
- // create new connection
176
- this.logEntry('TCP/HTTP:CONNECT-SERVER');
177
- this.ws = new WebSocket(url + (this.supportsCache ? '?cache=true' : ''));
178
- this.ws.onerror = (err) => {
179
- this.ws.close();
180
- this.logEntry('TCP/HTTP:ERROR:' + err);
181
- console.log('ActiveConnect: ' + err);
182
- };
183
- this.ws.onopen = () => {
184
- this.logEntry('TCP/HTTP:CONNECTED');
185
- this.Connected = true;
186
- };
187
- this.ws.onmessage = (e) => {
188
- this.messageReceived(JsonParser.parse(e.data.toString()));
189
- };
190
- this.ws.onclose = () => {
191
- this.logEntry('TCP/HTTP:CLOSED');
192
- if (!this.closed) {
193
- if (this.pool && this.pool.WssConnected)
194
- this.pool.WssConnected = false;
195
- this.logEntry('TCP/HTTP:RESET-REQUESTED-OUTBOUND-STATE');
196
- this.resetRequestedState();
197
- setTimeout(() => {
198
- this.connect(url);
199
- }, 1000);
200
- }
201
- };
202
- }
203
- sendToSocket(method, data, dontEnsureTransmission) {
204
- const messageId = ++this.messageId;
205
- if (this.ws.readyState != this.ws.OPEN) {
206
- if (!dontEnsureTransmission)
207
- this.requestStack.push({ method, data, messageId });
208
- else
209
- return false;
210
- }
211
- else {
212
- this.ws.send(JsonParser.stringify({ method, value: data, messageId }));
213
- }
214
- return messageId;
215
- }
216
- auth(token) {
217
- return __awaiter(this, void 0, void 0, function* () {
218
- return this.sendToSocket('auth.token', token);
219
- });
220
- }
221
- send(method, data, dontEnsureTransmission) {
222
- this.logEntry('SEND:' + method);
223
- const messageId = this.sendToSocket(method, data, dontEnsureTransmission || false);
224
- if (messageId) {
225
- return this.expectMethod(`m.${method}`, messageId);
226
- }
227
- else {
228
- return new Promise((resolve) => {
229
- resolve(false);
230
- });
231
- }
232
- }
233
- expectMethod(method, messageId) {
234
- return new Promise((resolve, reject) => {
235
- if (messageId) {
236
- this.expectedMethods.set(messageId, [resolve]);
237
- this.rejectCallbacks.set(messageId, reject);
238
- }
239
- else {
240
- if (this.expectedMethods.has(method)) {
241
- let arr = this.expectedMethods.get(method);
242
- arr.push(resolve);
243
- }
244
- else {
245
- this.expectedMethods.set(method, [resolve]);
246
- }
247
- }
248
- });
249
- }
250
- messageReceived({ method, value, messageId, specificHash, inserted, updated, deleted, length, }) {
251
- this.logEntry('RECEIVED:' + method);
252
- if (method == '___cache') {
253
- this.handleOutboundCacheRequest(value);
254
- }
255
- if (messageId) {
256
- if (method == 'm.error') {
257
- const reject = this.rejectCallbacks.get(messageId);
258
- if (reject) {
259
- reject(value);
260
- }
261
- messageId = -1;
262
- }
263
- }
264
- if (messageId != null) {
265
- const callback = this.expectedMethods.get(messageId);
266
- if (callback) {
267
- const func = callback.shift();
268
- if (func)
269
- func(value);
270
- this.invokeSuccessHandlers(method);
271
- }
272
- else {
273
- const callback = this.expectedMethods.get(method);
274
- if (callback && callback.length > 0) {
275
- const func = callback.shift();
276
- if (func)
277
- func(value);
278
- }
279
- else {
280
- const out = WebsocketClient.outbounds.get(method);
281
- if (out) {
282
- out(value, specificHash, inserted, updated, deleted, length, this);
283
- }
284
- const handle = WebsocketClient.handles.get(method);
285
- if (handle) {
286
- handle.Func(value);
287
- }
288
- }
289
- }
290
- }
291
- else {
292
- throw Error('No MessageId was provided, the connection is not supported.');
293
- }
294
- }
295
- handleOutboundCacheRequest(method) {
296
- if (this.dbService) {
297
- try {
298
- this.dbService.getByKey('outbound', method).subscribe((item) => {
299
- if (item) {
300
- this.send('___cache', {
301
- method,
302
- specificHash: item.specificHash || null,
303
- });
304
- }
305
- else {
306
- this.send('___cache', {
307
- method,
308
- specificHash: null,
309
- });
310
- }
311
- });
312
- }
313
- catch (e) {
314
- this.send('___cache', {
315
- method,
316
- specificHash: null,
317
- });
318
- console.error('ActiveConnect: ' + e);
319
- }
320
- }
321
- else {
322
- this.send('___cache', {
323
- method,
324
- specificHash: null,
325
- });
326
- console.error('Active-Connect: Caching not possible as the indexedDB has not been initialized');
327
- }
328
- }
329
- static expectOutbound(method, callback) {
330
- WebsocketClient.outbounds.set(method, callback);
331
- }
332
- static registerHandle(method, callback) {
333
- WebsocketClient.handles.set(method, callback);
334
- }
335
- get isConnected() {
336
- if (this.ws)
337
- return this.ws.readyState == WebSocket.OPEN;
338
- return true;
339
- }
340
- sendBrowserInfoToServer() {
341
- // send browser / os information
342
- const browser = this.getBrowser();
343
- const os = this.getOS();
344
- this.send('___browser', {
345
- browser: `${browser.name} ${browser.version} ${os}`,
346
- });
347
- }
348
- getBrowser() {
349
- // https://www.gregoryvarghese.com/how-to-get-browser-name-and-version-via-javascript/
350
- var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
351
- if (/trident/i.test(M[1])) {
352
- tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
353
- return { name: 'IE ', version: tem[1] || '' };
354
- }
355
- if (M[1] === 'Chrome') {
356
- tem = ua.match(/\bOPR\/(\d+)/);
357
- if (tem != null) {
358
- return { name: 'Opera', version: tem[1] };
359
- }
360
- }
361
- M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
362
- if ((tem = ua.match(/version\/(\d+)/i)) != null) {
363
- M.splice(1, 1, tem[1]);
364
- }
365
- return {
366
- name: M[0],
367
- version: M[1],
368
- };
369
- }
370
- getOS() {
371
- var userAgent = window.navigator.userAgent, platform = window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad', 'iPod'], os = null;
372
- if (macosPlatforms.indexOf(platform) !== -1) {
373
- os = 'Mac OS';
374
- }
375
- else if (iosPlatforms.indexOf(platform) !== -1) {
376
- os = 'iOS';
377
- }
378
- else if (windowsPlatforms.indexOf(platform) !== -1) {
379
- os = 'Windows';
380
- }
381
- else if (/Android/.test(userAgent)) {
382
- os = 'Android';
383
- }
384
- else if (!os && /Linux/.test(platform)) {
385
- os = 'Linux';
386
- }
387
- return os || '';
388
- }
389
- static onSuccess(callback, regexp) {
390
- this.onSuccessHandlers.push({ callback, regexp });
391
- }
392
- static onReconnect(callback) {
393
- WebsocketClient.onReconnectCallback.push(callback);
394
- }
395
- invokeSuccessHandlers(method) {
396
- WebsocketClient.onSuccessHandlers
397
- .filter((e) => e.regexp.test(method))
398
- .forEach((e) => {
399
- var res = e.callback.Func();
400
- if (res && res.then) {
401
- res.then();
402
- }
403
- });
404
- }
405
- disconnect(restart) {
406
- if (!restart)
407
- this.closed = true;
408
- this.ws.close();
409
- }
410
- initCache() { }
411
- }
412
- WebsocketClient.resetRequestedStateCallbacks = [];
413
- WebsocketClient.outbounds = new Map();
414
- WebsocketClient.handles = new Map();
415
- WebsocketClient.onSuccessHandlers = [];
416
- WebsocketClient.onReconnectCallback = [];
417
-
418
- /**
419
- * Represents the reference to an object method used for websocket routes and outbounds.
420
- */
421
- class DecorableFunction {
422
- /**
423
- * Creates an instance of DecorableFunction.
424
- * @param objConfig - The configuration object for the object method.
425
- * @param objConfig.target - The target object.
426
- * @param objConfig.propertyKey - The property key of the target object.
427
- */
428
- constructor(objConfig) {
429
- this.objConfig = objConfig;
430
- // singelton service - fetch from angular
431
- const prototype = this.objConfig.target.prototype || this.objConfig.target;
432
- if (!prototype.___constructorOverridden) {
433
- prototype.___constructorOverridden = true;
434
- }
435
- }
436
- /**
437
- * Returns the decorated function.
438
- * @returns - The decorated function.
439
- */
440
- get Func() {
441
- var _a;
442
- if (((_a = this.objConfig) === null || _a === void 0 ? void 0 : _a.target) &&
443
- this.objConfig.target[this.objConfig.propertyKey]) {
444
- return this.objConfig.target[this.objConfig.propertyKey].bind(this.getBindObject());
445
- }
446
- return null;
447
- }
448
- /**
449
- * Returns the bind object.
450
- * @private
451
- * @returns - The bind object.
452
- */
453
- getBindObject() {
454
- const prototype = this.objConfig.target.prototype || this.objConfig.target;
455
- return prototype.___data._obj;
456
- }
457
- }
458
-
459
- function Handle(method) {
460
- return function _Handle(target, propertyKey) {
461
- // method annotation
462
- WebsocketClient.registerHandle(method, new DecorableFunction({ target, propertyKey }));
463
- };
464
- }
465
-
466
- function OnSuccess(regexp) {
467
- return function _Route(target, propertyKey) {
468
- WebsocketClient.onSuccess(new DecorableFunction({ target, propertyKey }), regexp);
469
- };
470
- }
471
-
472
- function OnReconnect(target, propertyKey) {
473
- WebsocketClient.onReconnect(new DecorableFunction({ target, propertyKey }));
474
- }
475
-
476
- function Outbound(method, requestingRequired, cached, sortBy) {
477
- return function _Outbound(target, propertyKey) {
478
- target.loading = new Map();
479
- // property annotation
480
- WebsocketClient.expectOutbound(method, function setOutbound(data, specificHash, inserted, updated, deleted, length, _this) {
481
- if (!target.___received)
482
- target.___received = {};
483
- if (!target.___data)
484
- target.___data = {};
485
- if (!target.___received)
486
- target.___received = {};
487
- if (!target.___requested)
488
- target.___requested = {};
489
- if (!cached) {
490
- if (_this.dbService) {
491
- try {
492
- _this.dbService
493
- .deleteByKey('outbound', method)
494
- .subscribe(() => { });
495
- }
496
- catch (e) {
497
- console.error('ActiveConnect: could not delete indexdb cache entry');
498
- }
499
- }
500
- }
501
- if (data == 'cache_restore') {
502
- if (_this.dbService) {
503
- try {
504
- _this.dbService
505
- .getByKey('outbound', method)
506
- .subscribe((result) => {
507
- target.___received[propertyKey] = true;
508
- target.___data[propertyKey] = result.data;
509
- target.loading.set(propertyKey, false);
510
- });
511
- }
512
- catch (e) {
513
- console.error('ActiveConnect: Unable to restore cached data.');
514
- console.error(e);
515
- }
516
- }
517
- else {
518
- console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
519
- }
520
- }
521
- else if (data == 'cache_delete') {
522
- if (_this.dbService) {
523
- try {
524
- _this.dbService
525
- .deleteByKey('outbound', method)
526
- .subscribe(() => { });
527
- }
528
- catch (e) {
529
- console.error('ActiveConnect: Unable to delete cached data');
530
- console.error(e);
531
- }
532
- }
533
- else {
534
- console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
535
- }
536
- target.___received[propertyKey] = false;
537
- target.___data[propertyKey] = undefined;
538
- target.loading.set(propertyKey, false);
539
- }
540
- else if (data == 'data_delete') {
541
- target.___data[propertyKey] = undefined;
542
- target.loading.set(propertyKey, false);
543
- target.___received[propertyKey] = false;
544
- target.___requested[propertyKey] = false;
545
- }
546
- else if (data == 'data_diff') {
547
- var data = target.___data[propertyKey] || [];
548
- inserted === null || inserted === void 0 ? void 0 : inserted.forEach((e) => {
549
- const matching = data.filter((d) => d.id == e.id);
550
- if (matching.length > 0) {
551
- data[data.indexOf(matching[0])] = e;
552
- }
553
- else {
554
- data.push(e);
555
- }
556
- });
557
- updated === null || updated === void 0 ? void 0 : updated.forEach((e) => {
558
- const matching = data.filter((d) => d.id == e.id);
559
- if (matching.length > 0) {
560
- data[data.indexOf(matching[0])] = e;
561
- }
562
- else {
563
- data.push(e);
564
- }
565
- });
566
- deleted === null || deleted === void 0 ? void 0 : deleted.forEach((e) => {
567
- data = data.filter((d) => d.id != e.id);
568
- });
569
- if (sortBy && data)
570
- data = data.sort(sortBy);
571
- target.___data[propertyKey] = data;
572
- target.loading.set(propertyKey, false);
573
- if (cached && specificHash) {
574
- if (_this.dbService) {
575
- if (data && (data === null || data === void 0 ? void 0 : data.length) > 0) {
576
- try {
577
- _this.dbService
578
- .update('outbound', {
579
- method,
580
- data,
581
- specificHash,
582
- })
583
- .subscribe(() => { });
584
- }
585
- catch (e) {
586
- console.error('ActiveConnect: Unable to update cached data');
587
- console.error(e);
588
- }
589
- }
590
- else {
591
- try {
592
- _this.dbService
593
- .deleteByKey('outbound', method)
594
- .subscribe(() => { });
595
- }
596
- catch (e) {
597
- console.error('ActiveConnect: Unable to delete cached data');
598
- console.error(e);
599
- }
600
- }
601
- }
602
- else {
603
- console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
604
- }
605
- }
606
- }
607
- else {
608
- if (sortBy && data)
609
- data = data.sort(sortBy);
610
- target.___received[propertyKey] = true;
611
- target.___data[propertyKey] = data;
612
- target.loading.set(propertyKey, false);
613
- if (cached && specificHash) {
614
- if (_this.dbService) {
615
- if (data && (data === null || data === void 0 ? void 0 : data.length) > 0) {
616
- try {
617
- _this.dbService
618
- .update('outbound', {
619
- method,
620
- data,
621
- specificHash,
622
- })
623
- .subscribe(() => { });
624
- }
625
- catch (e) {
626
- console.error('ActiveConnect: Unable to update cached data');
627
- console.error(e);
628
- }
629
- }
630
- else {
631
- try {
632
- _this.dbService
633
- .deleteByKey('outbound', method)
634
- .subscribe(() => { });
635
- }
636
- catch (e) {
637
- console.error('ActiveConnect: Unable to update cached data');
638
- console.error(e);
639
- }
640
- }
641
- }
642
- else {
643
- console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
644
- }
645
- }
646
- }
647
- });
648
- if (requestingRequired) {
649
- WebsocketClient.addResetRequestingStateCallback(function callback() {
650
- if (target.___requested) {
651
- target.___requested[propertyKey] = false;
652
- }
653
- });
654
- }
655
- const obj = {
656
- configurable: true,
657
- get() {
658
- if (!target.___requested)
659
- target.___requested = {};
660
- if (requestingRequired && !target.___requested[propertyKey]) {
661
- target.___requested[propertyKey] = true;
662
- this.send('request.' + method, null).then();
663
- }
664
- if (!target.___data)
665
- target.___data = {};
666
- if (!target.___data[propertyKey]) {
667
- target.loading.set(propertyKey, true);
668
- }
669
- else if (target.loading[propertyKey]) {
670
- target.loading.set(propertyKey, false);
671
- }
672
- return target.___data[propertyKey];
673
- },
674
- set(val) {
675
- if (!target.___data)
676
- target.___data = {};
677
- target.loading.set(propertyKey, false);
678
- if (sortBy && val)
679
- val = val.sort(sortBy);
680
- return (target.___data[propertyKey] = val);
681
- },
682
- };
683
- target[propertyKey] = obj;
684
- return obj;
685
- };
686
- }
687
-
688
- function Route(method, loadingKey, dontEnsureTransmission) {
689
- return function _Route(target, propertyKey) {
690
- // method annotation
691
- const original = target[propertyKey];
692
- target[propertyKey] = function execRoute(...data) {
693
- var _a;
694
- return __awaiter(this, void 0, void 0, function* () {
695
- if (loadingKey) {
696
- if (!this.loadingElements[loadingKey]) {
697
- this.loadingElements[loadingKey] = 0;
698
- }
699
- this.loadingElements[loadingKey]++;
700
- }
701
- const promise = original.bind(this)(...data);
702
- let res = null;
703
- if (this.client) {
704
- res = yield ((_a = this.client
705
- .send(method, data[0], dontEnsureTransmission)) === null || _a === void 0 ? void 0 : _a.catch((err) => {
706
- if (loadingKey)
707
- this.loadingElements[loadingKey]--;
708
- throw err;
709
- }));
710
- }
711
- yield promise;
712
- if (loadingKey)
713
- this.loadingElements[loadingKey]--;
714
- return res;
715
- });
716
- };
717
- return target;
718
- };
719
- }
720
-
721
- /**
722
- * @deprecated
723
- */
724
- function Shared(defaultValue) {
725
- if (defaultValue) {
726
- throw Error("Active-Connect/@Shared: defaultValue is no longer supported, please assign the value to the variable itself.");
727
- }
728
- return function _Shared(target, propertyKey) { };
729
- }
730
-
731
- class LoadingStatus extends WebsocketClient {
732
- get isLoading() {
733
- // return general loading
734
- let anyTrue = false;
735
- this.__proto__.loading.forEach((e) => {
736
- anyTrue || (anyTrue = e);
737
- });
738
- if (!anyTrue)
739
- this.__proto__.loading.clear();
740
- return this.__proto__.loading.size > 0;
741
- }
742
- getLoadingMap() {
743
- return this.__proto__.loading;
744
- }
745
- get getCurrent() {
746
- let count = 0;
747
- this.__proto__.loading.forEach((e) => {
748
- if (e)
749
- count++;
750
- });
751
- if (count == 0) {
752
- this.__proto__.loading.clear();
753
- }
754
- return count;
755
- }
756
- get getTotal() {
757
- return this.__proto__.loading.size;
758
- }
759
- }
760
-
761
- class OutboundObject {
762
- constructor(client, method, lazyLoaded, cached, initialLoadingCount, sortBy) {
763
- this.client = client;
764
- this.method = method;
765
- this.lazyLoaded = lazyLoaded;
766
- this.cached = cached;
767
- this.initialLoadingCount = initialLoadingCount;
768
- this.sortBy = sortBy;
769
- this.dataMap = new Map();
770
- this.data = undefined;
771
- this.requested = false;
772
- this._loading = false;
773
- this._length = undefined;
774
- this.requestedId = null;
775
- this.loadedObservable = null;
776
- this.loadedId = null;
777
- this.loadedIdData = null;
778
- this.loadedIdChanged = null;
779
- this.requestedGroupId = null;
780
- this.loadedGroupObservable = null;
781
- this.loadedGroupId = null;
782
- this.loadedGroupData = null;
783
- this.loadedGroupChanged = null;
784
- this.target.loading = new Map();
785
- if (this.client.dbService) {
786
- try {
787
- this.client.dbService
788
- .getByKey('outbound', method)
789
- .subscribe((result) => {
790
- var _a;
791
- if (result) {
792
- this.previouslyCachedCount = ((_a = result.data) === null || _a === void 0 ? void 0 : _a.length) || null;
793
- }
794
- });
795
- }
796
- catch (e) {
797
- console.error('ActiveConnect: Unable to read cached data');
798
- console.error(e);
799
- }
800
- }
801
- const _this = this;
802
- WebsocketClient.expectOutbound(method, function setOutbound(data, specificHash, insertedOrGroupData, updatedOrGroupId, deleted, length, _client) {
803
- var _a, _b, _c, _d;
804
- if (!cached) {
805
- if (_client.dbService) {
806
- try {
807
- _client.dbService
808
- .deleteByKey('outbound', method)
809
- .subscribe(() => { });
810
- }
811
- catch (e) {
812
- console.error('ActiveConnect: Unable to delete cached data');
813
- console.error(e);
814
- }
815
- }
816
- }
817
- if (data == 'cache_restore') {
818
- if (_client.dbService) {
819
- try {
820
- _client.dbService
821
- .getByKey('outbound', method)
822
- .subscribe((result) => {
823
- _this.setData(result.data);
824
- if (result.length)
825
- _this._length = result.length;
826
- _this.loading = false;
827
- });
828
- }
829
- catch (e) {
830
- console.error('ActiveConnect: Unable to restore cached data');
831
- console.error(e);
832
- }
833
- }
834
- else {
835
- console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
836
- }
837
- }
838
- else if (data == 'cache_delete') {
839
- if (_client.dbService) {
840
- try {
841
- _client.dbService
842
- .deleteByKey('outbound', method)
843
- .subscribe(() => { });
844
- }
845
- catch (e) {
846
- console.error('ActiveConnect: Unable to delete cached data');
847
- console.error(e);
848
- }
849
- }
850
- else {
851
- console.error('ActiveConnect: Caching / restore not possible as the indexedDB is not accessible');
852
- }
853
- _this.loading = false;
854
- _this.requested = false;
855
- }
856
- else if (data == 'data_delete') {
857
- _this.data = undefined;
858
- _this.dataMap = new Map();
859
- _this.requested = false;
860
- _this.loadedGroupData = null;
861
- _this.loadedGroupId = null;
862
- _this._length = undefined;
863
- _this.loading = false;
864
- }
865
- else if (data == 'data_group') {
866
- if (_this.requestedGroupId ==
867
- (updatedOrGroupId ? updatedOrGroupId[0] : 0)) {
868
- _this.loadedGroupData = insertedOrGroupData;
869
- _this.loadedGroupId = updatedOrGroupId ? updatedOrGroupId[0] : 0;
870
- (_a = _this.loadedGroupChanged) === null || _a === void 0 ? void 0 : _a.next(insertedOrGroupData);
871
- _this.loading = false;
872
- }
873
- }
874
- else if (data == 'data_id') {
875
- if (_this.requestedId == (updatedOrGroupId ? updatedOrGroupId[0] : 0)) {
876
- _this.loadedIdData =
877
- ((insertedOrGroupData === null || insertedOrGroupData === void 0 ? void 0 : insertedOrGroupData.length) || 0) > 0
878
- ? insertedOrGroupData[0]
879
- : null;
880
- _this.loadedId = updatedOrGroupId ? updatedOrGroupId[0] : 0;
881
- (_b = _this.loadedIdChanged) === null || _b === void 0 ? void 0 : _b.next(_this.loadedIdData);
882
- _this.loading = false;
883
- }
884
- }
885
- else if (data == 'data_diff') {
886
- insertedOrGroupData === null || insertedOrGroupData === void 0 ? void 0 : insertedOrGroupData.forEach((e) => {
887
- var _a;
888
- _this.dataMap.set(e.id, e);
889
- if (e.id == _this.loadedId) {
890
- (_a = _this.loadedIdChanged) === null || _a === void 0 ? void 0 : _a.next(e);
891
- }
892
- });
893
- updatedOrGroupId === null || updatedOrGroupId === void 0 ? void 0 : updatedOrGroupId.forEach((e) => {
894
- var _a;
895
- _this.dataMap.set(e.id, e);
896
- if (e.id == _this.loadedId) {
897
- (_a = _this.loadedIdChanged) === null || _a === void 0 ? void 0 : _a.next(e);
898
- }
899
- });
900
- deleted === null || deleted === void 0 ? void 0 : deleted.forEach((e) => {
901
- var _a;
902
- _this.dataMap.delete(e.id);
903
- if (e.id == _this.loadedId) {
904
- (_a = _this.loadedIdChanged) === null || _a === void 0 ? void 0 : _a.next(null);
905
- }
906
- });
907
- _this.data = Array.from(_this.dataMap.values());
908
- if (_this.data && _this.sortBy)
909
- _this.data = _this.data.sort(_this.sortBy);
910
- _this.loading = false;
911
- if (cached && specificHash) {
912
- if (_client.dbService) {
913
- try {
914
- if (_this.data && ((_c = _this.data) === null || _c === void 0 ? void 0 : _c.length) > 0) {
915
- _client.dbService
916
- .update('outbound', {
917
- method,
918
- data: _this.data,
919
- specificHash,
920
- length,
921
- })
922
- .subscribe(() => { });
923
- }
924
- else {
925
- _client.dbService
926
- .deleteByKey('outbound', method)
927
- .subscribe(() => { });
928
- }
929
- }
930
- catch (e) {
931
- console.error('ActiveConnect: Unable to update cached data.');
932
- console.error(e);
933
- }
934
- }
935
- else {
936
- console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
937
- }
938
- }
939
- }
940
- else {
941
- _this.setData(data);
942
- if (_this.loadedId) {
943
- const loadedValue = _this.dataMap.get(_this.loadedId);
944
- if (loadedValue) {
945
- _this.loadedIdData = loadedValue;
946
- (_d = _this.loadedIdChanged) === null || _d === void 0 ? void 0 : _d.next(_this.loadedIdData);
947
- }
948
- }
949
- _this.loading = false;
950
- if (cached && specificHash) {
951
- if (_client.dbService) {
952
- try {
953
- if (data && (data === null || data === void 0 ? void 0 : data.length) > 0) {
954
- _client.dbService
955
- .update('outbound', {
956
- method,
957
- data,
958
- specificHash,
959
- length,
960
- })
961
- .subscribe(() => { });
962
- }
963
- else {
964
- _client.dbService
965
- .deleteByKey('outbound', method)
966
- .subscribe(() => { });
967
- }
968
- }
969
- catch (e) {
970
- console.error('ActiveConnect: Unable to update cached data.');
971
- console.error(e);
972
- }
973
- }
974
- else {
975
- console.error('ActiveConnect: Caching not possible as the indexedDB has not been initialized');
976
- }
977
- }
978
- }
979
- if (length)
980
- _this._length = length;
981
- });
982
- WebsocketClient.addResetRequestingStateCallback(() => {
983
- this.afterServerReconnected();
984
- });
985
- }
986
- get target() {
987
- return this.client.__proto__;
988
- }
989
- get(id) {
990
- if (this.requestedId == id && this.loadedObservable && this.loadedIdData) {
991
- if (this.loadedIdData)
992
- setTimeout(() => {
993
- var _a;
994
- if (this.loadedIdData)
995
- (_a = this.loadedIdChanged) === null || _a === void 0 ? void 0 : _a.next(this.loadedIdData);
996
- }, 50);
997
- return this.loadedObservable;
998
- }
999
- let observablePromise;
1000
- if (this.requestedId != id || !this.loadedObservable) {
1001
- observablePromise = new Promise((resolve) => {
1002
- this.loadedObservable = new Observable((observer) => {
1003
- this.loadedIdChanged = observer;
1004
- resolve();
1005
- });
1006
- });
1007
- }
1008
- Promise.all([observablePromise]).then(() => {
1009
- new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1010
- var _a, _b;
1011
- if (!this.requested && this.lazyLoaded) {
1012
- this.load().then();
1013
- }
1014
- if (this.data) {
1015
- const res = this.dataMap.get(id);
1016
- if (res) {
1017
- (_a = this.loadedIdChanged) === null || _a === void 0 ? void 0 : _a.next(res);
1018
- resolve();
1019
- return;
1020
- }
1021
- }
1022
- if (this.loadedId == id) {
1023
- (_b = this.loadedIdChanged) === null || _b === void 0 ? void 0 : _b.next(this.loadedIdData);
1024
- }
1025
- else {
1026
- yield this.requestById(id);
1027
- }
1028
- resolve();
1029
- })).then();
1030
- });
1031
- return this.loadedObservable;
1032
- }
1033
- getForGroup(groupId) {
1034
- if (this.requestedGroupId == groupId &&
1035
- this.loadedGroupObservable &&
1036
- this.loadedGroupData) {
1037
- setTimeout(() => {
1038
- var _a;
1039
- if (this.loadedGroupData)
1040
- (_a = this.loadedGroupChanged) === null || _a === void 0 ? void 0 : _a.next(this.loadedGroupData);
1041
- }, 50);
1042
- return this.loadedGroupObservable;
1043
- }
1044
- let observablePromise;
1045
- if (this.requestedGroupId != groupId || !this.loadedGroupObservable) {
1046
- observablePromise = new Promise((resolve) => {
1047
- this.loadedGroupObservable = new Observable((observer) => {
1048
- this.loadedGroupChanged = observer;
1049
- resolve();
1050
- });
1051
- });
1052
- }
1053
- Promise.all([observablePromise]).then(() => {
1054
- new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
1055
- var _a;
1056
- if (!this.requested && this.lazyLoaded) {
1057
- this.load().then();
1058
- }
1059
- if (this.loadedGroupId == groupId && this.loadedGroupData) {
1060
- (_a = this.loadedGroupChanged) === null || _a === void 0 ? void 0 : _a.next(this.loadedGroupData);
1061
- }
1062
- else {
1063
- yield this.requestForGroup(groupId);
1064
- }
1065
- resolve();
1066
- })).then();
1067
- });
1068
- return this.loadedGroupObservable;
1069
- }
1070
- get all() {
1071
- if (!this.requested && this.lazyLoaded) {
1072
- this.load().then();
1073
- }
1074
- return this.data;
1075
- }
1076
- load(count) {
1077
- return __awaiter(this, void 0, void 0, function* () {
1078
- if (this.lazyLoaded) {
1079
- const hasBeenRequestedBefore = this.requested;
1080
- this._loading = true;
1081
- if (!this.requested) {
1082
- this.loading = true;
1083
- }
1084
- this.requested = true;
1085
- yield this.client.send('request.' + this.method, {
1086
- count: hasBeenRequestedBefore
1087
- ? this.data
1088
- ? count || this.initialLoadingCount
1089
- ? (count || this.initialLoadingCount) +
1090
- this.loadedLength
1091
- : undefined
1092
- : undefined
1093
- : this.previouslyCachedCount || this.initialLoadingCount,
1094
- loaded: this.loadedLength,
1095
- });
1096
- }
1097
- else {
1098
- throw Error('Active-Connect: Cannot run loading request as this outbound is not lazy-loaded.');
1099
- }
1100
- });
1101
- }
1102
- set loading(value) {
1103
- this._loading = value;
1104
- this.target.loading.set(this.method, value);
1105
- }
1106
- get loading() {
1107
- return this._loading;
1108
- }
1109
- get loadedLength() {
1110
- var _a;
1111
- return ((_a = this.data) === null || _a === void 0 ? void 0 : _a.length) || 0;
1112
- }
1113
- get length() {
1114
- return this._length;
1115
- }
1116
- requestById(id) {
1117
- this.loading = true;
1118
- this.requestedId = id;
1119
- return this.client.send('request.' + this.method, { id });
1120
- }
1121
- requestForGroup(groupId) {
1122
- this.loading = true;
1123
- this.requestedGroupId = groupId;
1124
- return this.client.send('request.' + this.method, { groupId });
1125
- }
1126
- setData(data) {
1127
- this.data = data;
1128
- if (this.data && this.sortBy)
1129
- this.data = this.data.sort(this.sortBy);
1130
- this._length = data.length;
1131
- this.dataMap = new Map();
1132
- this.data.forEach((d) => {
1133
- this.dataMap.set(d.id, d);
1134
- });
1135
- }
1136
- get isEmpty() {
1137
- return this.data == undefined;
1138
- }
1139
- /**
1140
- * The contained data can be modified within the callback method
1141
- */
1142
- update(callback) {
1143
- if (this.data) {
1144
- const updateLengthVariable = this.data.length == this._length;
1145
- const length = this.length;
1146
- callback(this.data);
1147
- this.setData(this.data);
1148
- if (!updateLengthVariable) {
1149
- this._length = length;
1150
- }
1151
- }
1152
- }
1153
- afterServerReconnected() {
1154
- if (this.requested && this.lazyLoaded) {
1155
- this.requested = false;
1156
- this.load(1).then();
1157
- }
1158
- if (this.loadedId) {
1159
- this.loadedIdData = null;
1160
- this.get(this.loadedId);
1161
- }
1162
- if (this.loadedGroupId) {
1163
- this.loadedGroupData = null;
1164
- this.getForGroup(this.loadedGroupId);
1165
- }
1166
- }
1167
- }
1168
-
1169
- /*
1170
- * Public API Surface of active-connect-ng2
1171
- */
1172
-
1173
- /**
1174
- * Generated bundle index. Do not edit.
1175
- */
1176
-
1177
- export { ActiveConnectNg2Module, Handle, LoadingStatus, OnReconnect, OnSuccess, Outbound, OutboundObject, Route, Shared, WebsocketClient };
1178
- //# sourceMappingURL=active-connect-ng2.mjs.map