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