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