@chat21/chat21-ionic 3.4.27-rc21 → 3.4.27-rc22

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.
@@ -0,0 +1,232 @@
1
+ /// websocket.worker.ts
2
+
3
+ interface WSMessage {
4
+ action?: string;
5
+ event?: { topic: string; method: string };
6
+ payload?: any;
7
+ }
8
+
9
+ interface Subscription {
10
+ topic: string;
11
+ label?: string;
12
+ onCreate?: (msg: any) => void;
13
+ onUpdate?: (msg: any) => void;
14
+ onData?: (msg: any) => void;
15
+ }
16
+
17
+ let ws: WebSocket | null = null;
18
+ let url = '';
19
+ let reconnectInterval = 5000;
20
+ let subscriptions: Subscription[] = [];
21
+ let pendingMessages: any[] = [];
22
+
23
+
24
+ let pingMsg = { action: "heartbeat", payload: { message: { text: "ping" } } }
25
+ let pongMsg = { action: "heartbeat", payload: { message: { text: "pong" } } }
26
+ const pongTimeout = 10000;
27
+ const pingTimeout = 15000;
28
+ let pingTimeoutId;
29
+ let pongTimeoutId;
30
+
31
+ let reconnectAttempts = 0;
32
+ const maxReconnectDelay = 30000;
33
+ let manuallyClosed = false;
34
+ let pageHidden = false;
35
+
36
+ onmessage = (e: MessageEvent) => {
37
+ const { action, data } = e.data;
38
+
39
+ switch (action) {
40
+ case 'init':
41
+ url = data.url;
42
+ connect();
43
+ break;
44
+ case 'subscribe':
45
+ const topic = data.topic || data.label;
46
+ subscriptions.push({ topic });
47
+ if (ws && ws.readyState === WebSocket.OPEN) {
48
+ ws.send(JSON.stringify({
49
+ action: 'subscribe',
50
+ payload: {
51
+ topic: topic,
52
+ message: undefined,
53
+ method: undefined
54
+ }
55
+ }));
56
+ }
57
+ break;
58
+ case 'unsubscribe':
59
+ subscriptions = subscriptions.filter(s => s.topic !== data.topic);
60
+ if (ws && ws.readyState === WebSocket.OPEN) {
61
+ // Unsubscribe
62
+ ws.send(JSON.stringify({
63
+ action: 'unsubscribe',
64
+ payload: {
65
+ topic: data.topic,
66
+ message: undefined,
67
+ method: undefined
68
+ }
69
+ }));
70
+ }
71
+ break;
72
+ case 'visibility': // ✅ Nuovo
73
+ pageHidden = data.hidden;
74
+ break;
75
+ case 'send':
76
+ sendMessage(data.message);
77
+ break;
78
+ case 'close': // ✅ Nuovo
79
+ closeConnection();
80
+ break;
81
+ }
82
+ };
83
+
84
+ function connect() {
85
+ ws = new WebSocket(url);
86
+ ws.onopen = () => {
87
+ console.log('[Worker] WebSocket connected',subscriptions);
88
+ // Risottiamo pending subscriptions
89
+ subscriptions.forEach(s => {
90
+ ws!.send(JSON.stringify({
91
+ action: 'subscribe',
92
+ payload: {
93
+ topic: s.topic,
94
+ message: undefined,
95
+ method: undefined
96
+ }
97
+ }));
98
+ }
99
+ );
100
+ // Invia messaggi in coda
101
+ pendingMessages.forEach(msg => ws!.send(JSON.stringify(msg)));
102
+ pendingMessages = [];
103
+
104
+ // Inizializza heartbeat
105
+ heartCheck();
106
+ reconnectAttempts = 0;
107
+ };
108
+
109
+ ws.onmessage = (event) => {
110
+ try {
111
+ const msg: WSMessage = JSON.parse(event.data);
112
+ handleMessage(msg);
113
+ } catch (err) {
114
+ console.error('[Worker] Invalid message', err);
115
+ }
116
+ };
117
+
118
+ ws.onclose = () => {
119
+ heartReset();
120
+ if(!manuallyClosed){
121
+ reconnectAttempts++;
122
+ const delay = Math.min(reconnectAttempts * 1000, maxReconnectDelay);
123
+ console.log('[Worker] WebSocket disconnected, retry in', delay, 'ms');
124
+ setTimeout(connect, delay);
125
+ }
126
+ };
127
+
128
+ ws.onerror = (err) => {
129
+ console.error('[Worker] WebSocket error', err);
130
+ ws?.close();
131
+ };
132
+ }
133
+
134
+ function handleMessage(msg: WSMessage) {
135
+ console.log('[Worker] Received message:', msg);
136
+ // --- GESTIONE PING/PONG ---
137
+ if (msg.action === 'heartbeat' && msg.payload?.message?.text === 'ping') {
138
+ console.log('[Worker] Received ping, sending pong');
139
+ if (ws && ws.readyState === WebSocket.OPEN) {
140
+ ws.send(JSON.stringify(pongMsg));
141
+ }
142
+ return; // Non processare ulteriormente il ping
143
+ }
144
+
145
+ // Solo formato "publish"
146
+ if (msg.action !== "publish") return;
147
+
148
+ const topic = msg.payload?.topic;
149
+ const method = msg.payload?.method;
150
+ const payload = msg.payload?.message;
151
+
152
+ if (!topic) return;
153
+
154
+ // Notifica solo le subscription che matchano
155
+ subscriptions.forEach(sub => {
156
+ if (sub.topic === topic) {
157
+ postMessage({ topic, method, payload }, undefined);
158
+ }
159
+ });
160
+ }
161
+
162
+ function sendMessage(message: any) {
163
+ if (ws && ws.readyState === WebSocket.OPEN) {
164
+ ws.send(JSON.stringify(message));
165
+ } else {
166
+ pendingMessages.push(message);
167
+ }
168
+ }
169
+
170
+
171
+ // -----------------------------------------------------------------------------------------------------
172
+ // @ HeartCheck
173
+ // -----------------------------------------------------------------------------------------------------
174
+ function heartCheck() {
175
+ heartReset();
176
+ heartStart();
177
+ }
178
+
179
+ // -----------------------------------------------------------------------------------------------------
180
+ // @ HeartStart
181
+ // -----------------------------------------------------------------------------------------------------
182
+ function heartStart() {
183
+ // this.getRemainingTime();
184
+
185
+ // usa intervallo adattivo se tab è in background (Chrome throtla i timer)
186
+ const adaptivePing = pageHidden ? pingTimeout * 3 : pingTimeout;
187
+
188
+ // // pianifica invio ping
189
+ pingTimeoutId = setTimeout(() => {
190
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
191
+ console.log("[WEBSOCKET-JS] - HEART-START - SENDING PING ");
192
+
193
+ // Qui viene inviato un battito cardiaco. Dopo averlo ricevuto, viene restituito un messaggio di battito cardiaco.
194
+ // onmessage Ottieni il battito cardiaco restituito per indicare che la connessione è normale
195
+ ws.send(JSON.stringify(pingMsg));
196
+
197
+ // Se non viene ripristinato dopo un determinato periodo di tempo, il backend viene attivamente disconnesso
198
+ pongTimeoutId = setTimeout(() => {
199
+ console.log("[WEBSOCKET-JS] - HEART-START - PONG-TIMEOUT-ID - CLOSE WS ");
200
+ // se onclose Si esibirà reconnect,Eseguiamo ws.close() Bene, se lo esegui direttamente reconnect Si innescherà onclose Causa riconnessione due volte
201
+ ws.close();
202
+ }, pongTimeout) as unknown as number;
203
+ }, adaptivePing);
204
+
205
+ }
206
+
207
+ // -----------------------------------------------------------------------------------------------------
208
+ // @ heartReset
209
+ // -----------------------------------------------------------------------------------------------------
210
+ function heartReset() {
211
+ if (pongTimeoutId !== undefined) {
212
+ clearTimeout(pongTimeoutId);
213
+ pongTimeoutId = undefined;
214
+ }
215
+
216
+ if (pingTimeoutId !== undefined) {
217
+ clearTimeout(pingTimeoutId);
218
+ pingTimeoutId = undefined;
219
+ }
220
+ }
221
+
222
+ function closeConnection() {
223
+ if (ws) {
224
+ ws.close();
225
+ ws = null;
226
+ }
227
+ heartReset();
228
+ pendingMessages = [];
229
+ subscriptions = [];
230
+ manuallyClosed = true;
231
+ console.log('[Worker] WebSocket closed manually');
232
+ }