@pocketping/widget 1.0.1 → 1.1.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.
- package/dist/index.cjs +116 -14
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +116 -14
- package/dist/pocketping.min.global.js +4 -4
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -697,6 +697,7 @@ var PocketPingClient = class {
|
|
|
697
697
|
constructor(config) {
|
|
698
698
|
this.session = null;
|
|
699
699
|
this.ws = null;
|
|
700
|
+
this.sse = null;
|
|
700
701
|
this.isOpen = false;
|
|
701
702
|
this.listeners = /* @__PURE__ */ new Map();
|
|
702
703
|
this.customEventHandlers = /* @__PURE__ */ new Map();
|
|
@@ -706,6 +707,10 @@ var PocketPingClient = class {
|
|
|
706
707
|
this.pollingTimeout = null;
|
|
707
708
|
this.pollingFailures = 0;
|
|
708
709
|
this.maxPollingFailures = 10;
|
|
710
|
+
this.wsConnectedAt = 0;
|
|
711
|
+
this.quickFailureThreshold = 2e3;
|
|
712
|
+
// If WS fails within 2s, assume serverless
|
|
713
|
+
this.connectionMode = "none";
|
|
709
714
|
this.trackedElementCleanups = [];
|
|
710
715
|
this.currentTrackedElements = [];
|
|
711
716
|
this.inspectorMode = false;
|
|
@@ -766,7 +771,7 @@ var PocketPingClient = class {
|
|
|
766
771
|
welcomeMessage: this.config.welcomeMessage
|
|
767
772
|
});
|
|
768
773
|
this.storeSessionId(response.sessionId);
|
|
769
|
-
this.
|
|
774
|
+
this.connectRealtime();
|
|
770
775
|
if (response.inspectorMode) {
|
|
771
776
|
this.enableInspectorMode();
|
|
772
777
|
} else if (response.trackedElements?.length) {
|
|
@@ -777,9 +782,20 @@ var PocketPingClient = class {
|
|
|
777
782
|
return this.session;
|
|
778
783
|
}
|
|
779
784
|
disconnect() {
|
|
780
|
-
this.ws
|
|
781
|
-
|
|
785
|
+
if (this.ws) {
|
|
786
|
+
this.ws.onclose = null;
|
|
787
|
+
this.ws.onmessage = null;
|
|
788
|
+
this.ws.onerror = null;
|
|
789
|
+
this.ws.onopen = null;
|
|
790
|
+
this.ws.close();
|
|
791
|
+
this.ws = null;
|
|
792
|
+
}
|
|
793
|
+
if (this.sse) {
|
|
794
|
+
this.sse.close();
|
|
795
|
+
this.sse = null;
|
|
796
|
+
}
|
|
782
797
|
this.session = null;
|
|
798
|
+
this.connectionMode = "none";
|
|
783
799
|
if (this.reconnectTimeout) {
|
|
784
800
|
clearTimeout(this.reconnectTimeout);
|
|
785
801
|
}
|
|
@@ -1383,37 +1399,122 @@ var PocketPingClient = class {
|
|
|
1383
1399
|
return this.inspectorMode;
|
|
1384
1400
|
}
|
|
1385
1401
|
// ─────────────────────────────────────────────────────────────────
|
|
1386
|
-
// WebSocket
|
|
1402
|
+
// Real-time Connection (WebSocket → SSE → Polling)
|
|
1387
1403
|
// ─────────────────────────────────────────────────────────────────
|
|
1404
|
+
connectRealtime() {
|
|
1405
|
+
if (!this.session) return;
|
|
1406
|
+
if (this.connectionMode === "polling") {
|
|
1407
|
+
this.startPolling();
|
|
1408
|
+
return;
|
|
1409
|
+
}
|
|
1410
|
+
if (this.connectionMode === "sse") {
|
|
1411
|
+
this.connectSSE();
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
this.connectWebSocket();
|
|
1415
|
+
}
|
|
1388
1416
|
connectWebSocket() {
|
|
1389
1417
|
if (!this.session) return;
|
|
1390
1418
|
const wsUrl = this.config.endpoint.replace(/^http/, "ws").replace(/\/$/, "") + `/stream?sessionId=${this.session.sessionId}`;
|
|
1391
1419
|
try {
|
|
1392
1420
|
this.ws = new WebSocket(wsUrl);
|
|
1421
|
+
this.wsConnectedAt = Date.now();
|
|
1422
|
+
const connectionTimeout = setTimeout(() => {
|
|
1423
|
+
console.warn("[PocketPing] \u23F1\uFE0F WebSocket timeout - trying SSE");
|
|
1424
|
+
if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
|
|
1425
|
+
this.ws.onclose = null;
|
|
1426
|
+
this.ws.onerror = null;
|
|
1427
|
+
this.ws.onopen = null;
|
|
1428
|
+
this.ws.close();
|
|
1429
|
+
this.ws = null;
|
|
1430
|
+
this.connectSSE();
|
|
1431
|
+
}
|
|
1432
|
+
}, 5e3);
|
|
1393
1433
|
this.ws.onopen = () => {
|
|
1434
|
+
clearTimeout(connectionTimeout);
|
|
1435
|
+
this.connectionMode = "ws";
|
|
1394
1436
|
this.reconnectAttempts = 0;
|
|
1437
|
+
this.wsConnectedAt = Date.now();
|
|
1395
1438
|
this.emit("wsConnected", null);
|
|
1396
1439
|
};
|
|
1397
1440
|
this.ws.onmessage = (event) => {
|
|
1398
1441
|
try {
|
|
1399
1442
|
const wsEvent = JSON.parse(event.data);
|
|
1400
|
-
this.
|
|
1443
|
+
this.handleRealtimeEvent(wsEvent);
|
|
1401
1444
|
} catch (err) {
|
|
1402
1445
|
console.error("[PocketPing] Failed to parse WS message:", err);
|
|
1403
1446
|
}
|
|
1404
1447
|
};
|
|
1405
1448
|
this.ws.onclose = () => {
|
|
1449
|
+
clearTimeout(connectionTimeout);
|
|
1406
1450
|
this.emit("wsDisconnected", null);
|
|
1407
|
-
this.
|
|
1451
|
+
this.handleWsFailure();
|
|
1408
1452
|
};
|
|
1409
|
-
this.ws.onerror = (
|
|
1410
|
-
|
|
1453
|
+
this.ws.onerror = () => {
|
|
1454
|
+
clearTimeout(connectionTimeout);
|
|
1411
1455
|
};
|
|
1412
|
-
} catch
|
|
1413
|
-
console.warn("[PocketPing] WebSocket unavailable
|
|
1456
|
+
} catch {
|
|
1457
|
+
console.warn("[PocketPing] WebSocket unavailable - trying SSE");
|
|
1458
|
+
this.connectSSE();
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
connectSSE() {
|
|
1462
|
+
if (!this.session) return;
|
|
1463
|
+
const sseUrl = this.config.endpoint.replace(/\/$/, "") + `/stream?sessionId=${this.session.sessionId}`;
|
|
1464
|
+
try {
|
|
1465
|
+
this.sse = new EventSource(sseUrl);
|
|
1466
|
+
const connectionTimeout = setTimeout(() => {
|
|
1467
|
+
console.warn("[PocketPing] \u23F1\uFE0F SSE timeout - falling back to polling");
|
|
1468
|
+
if (this.sse && this.sse.readyState !== EventSource.OPEN) {
|
|
1469
|
+
this.sse.close();
|
|
1470
|
+
this.sse = null;
|
|
1471
|
+
this.connectionMode = "polling";
|
|
1472
|
+
this.startPolling();
|
|
1473
|
+
}
|
|
1474
|
+
}, 5e3);
|
|
1475
|
+
this.sse.onopen = () => {
|
|
1476
|
+
clearTimeout(connectionTimeout);
|
|
1477
|
+
this.connectionMode = "sse";
|
|
1478
|
+
this.emit("sseConnected", null);
|
|
1479
|
+
};
|
|
1480
|
+
this.sse.addEventListener("message", (event) => {
|
|
1481
|
+
try {
|
|
1482
|
+
const data = JSON.parse(event.data);
|
|
1483
|
+
this.handleRealtimeEvent(data);
|
|
1484
|
+
} catch (err) {
|
|
1485
|
+
console.error("[PocketPing] Failed to parse SSE message:", err);
|
|
1486
|
+
}
|
|
1487
|
+
});
|
|
1488
|
+
this.sse.addEventListener("connected", () => {
|
|
1489
|
+
});
|
|
1490
|
+
this.sse.onerror = () => {
|
|
1491
|
+
clearTimeout(connectionTimeout);
|
|
1492
|
+
console.warn("[PocketPing] \u274C SSE error - falling back to polling");
|
|
1493
|
+
if (this.sse) {
|
|
1494
|
+
this.sse.close();
|
|
1495
|
+
this.sse = null;
|
|
1496
|
+
}
|
|
1497
|
+
this.connectionMode = "polling";
|
|
1498
|
+
this.startPolling();
|
|
1499
|
+
};
|
|
1500
|
+
} catch {
|
|
1501
|
+
console.warn("[PocketPing] SSE unavailable - falling back to polling");
|
|
1502
|
+
this.connectionMode = "polling";
|
|
1414
1503
|
this.startPolling();
|
|
1415
1504
|
}
|
|
1416
1505
|
}
|
|
1506
|
+
handleWsFailure() {
|
|
1507
|
+
const timeSinceConnect = Date.now() - this.wsConnectedAt;
|
|
1508
|
+
if (timeSinceConnect < this.quickFailureThreshold) {
|
|
1509
|
+
console.info("[PocketPing] WebSocket failed quickly - trying SSE");
|
|
1510
|
+
this.connectSSE();
|
|
1511
|
+
return;
|
|
1512
|
+
}
|
|
1513
|
+
this.scheduleReconnect();
|
|
1514
|
+
}
|
|
1515
|
+
handleRealtimeEvent(event) {
|
|
1516
|
+
this.handleWebSocketEvent(event);
|
|
1517
|
+
}
|
|
1417
1518
|
handleWebSocketEvent(event) {
|
|
1418
1519
|
switch (event.type) {
|
|
1419
1520
|
case "message":
|
|
@@ -1525,8 +1626,8 @@ var PocketPingClient = class {
|
|
|
1525
1626
|
}
|
|
1526
1627
|
scheduleReconnect() {
|
|
1527
1628
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
1528
|
-
console.warn("[PocketPing] Max reconnect attempts reached,
|
|
1529
|
-
this.
|
|
1629
|
+
console.warn("[PocketPing] Max reconnect attempts reached, trying SSE");
|
|
1630
|
+
this.connectSSE();
|
|
1530
1631
|
return;
|
|
1531
1632
|
}
|
|
1532
1633
|
const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
|
|
@@ -1551,6 +1652,7 @@ var PocketPingClient = class {
|
|
|
1551
1652
|
}
|
|
1552
1653
|
} catch (err) {
|
|
1553
1654
|
this.pollingFailures++;
|
|
1655
|
+
console.error(`[PocketPing] \u274C Polling error:`, err);
|
|
1554
1656
|
if (this.pollingFailures <= 3 || this.pollingFailures % 3 === 0) {
|
|
1555
1657
|
console.warn(`[PocketPing] Polling failed (${this.pollingFailures}/${this.maxPollingFailures})`);
|
|
1556
1658
|
}
|
|
@@ -1561,11 +1663,11 @@ var PocketPingClient = class {
|
|
|
1561
1663
|
}
|
|
1562
1664
|
}
|
|
1563
1665
|
if (this.session) {
|
|
1564
|
-
const delay = this.pollingFailures > 0 ? Math.min(
|
|
1666
|
+
const delay = this.pollingFailures > 0 ? Math.min(2e3 * Math.pow(2, this.pollingFailures - 1), 3e4) : 2e3;
|
|
1565
1667
|
this.pollingTimeout = setTimeout(poll, delay);
|
|
1566
1668
|
}
|
|
1567
1669
|
};
|
|
1568
|
-
poll
|
|
1670
|
+
this.pollingTimeout = setTimeout(poll, 500);
|
|
1569
1671
|
}
|
|
1570
1672
|
stopPolling() {
|
|
1571
1673
|
if (this.pollingTimeout) {
|
package/dist/index.d.cts
CHANGED
|
@@ -171,6 +171,7 @@ declare class PocketPingClient {
|
|
|
171
171
|
private config;
|
|
172
172
|
private session;
|
|
173
173
|
private ws;
|
|
174
|
+
private sse;
|
|
174
175
|
private isOpen;
|
|
175
176
|
private listeners;
|
|
176
177
|
private customEventHandlers;
|
|
@@ -180,6 +181,9 @@ declare class PocketPingClient {
|
|
|
180
181
|
private pollingTimeout;
|
|
181
182
|
private pollingFailures;
|
|
182
183
|
private maxPollingFailures;
|
|
184
|
+
private wsConnectedAt;
|
|
185
|
+
private quickFailureThreshold;
|
|
186
|
+
private connectionMode;
|
|
183
187
|
private trackedElementCleanups;
|
|
184
188
|
private currentTrackedElements;
|
|
185
189
|
private inspectorMode;
|
|
@@ -285,7 +289,11 @@ declare class PocketPingClient {
|
|
|
285
289
|
* Check if inspector mode is active
|
|
286
290
|
*/
|
|
287
291
|
isInspectorModeActive(): boolean;
|
|
292
|
+
private connectRealtime;
|
|
288
293
|
private connectWebSocket;
|
|
294
|
+
private connectSSE;
|
|
295
|
+
private handleWsFailure;
|
|
296
|
+
private handleRealtimeEvent;
|
|
289
297
|
private handleWebSocketEvent;
|
|
290
298
|
private handleVersionWarning;
|
|
291
299
|
private scheduleReconnect;
|
package/dist/index.d.ts
CHANGED
|
@@ -171,6 +171,7 @@ declare class PocketPingClient {
|
|
|
171
171
|
private config;
|
|
172
172
|
private session;
|
|
173
173
|
private ws;
|
|
174
|
+
private sse;
|
|
174
175
|
private isOpen;
|
|
175
176
|
private listeners;
|
|
176
177
|
private customEventHandlers;
|
|
@@ -180,6 +181,9 @@ declare class PocketPingClient {
|
|
|
180
181
|
private pollingTimeout;
|
|
181
182
|
private pollingFailures;
|
|
182
183
|
private maxPollingFailures;
|
|
184
|
+
private wsConnectedAt;
|
|
185
|
+
private quickFailureThreshold;
|
|
186
|
+
private connectionMode;
|
|
183
187
|
private trackedElementCleanups;
|
|
184
188
|
private currentTrackedElements;
|
|
185
189
|
private inspectorMode;
|
|
@@ -285,7 +289,11 @@ declare class PocketPingClient {
|
|
|
285
289
|
* Check if inspector mode is active
|
|
286
290
|
*/
|
|
287
291
|
isInspectorModeActive(): boolean;
|
|
292
|
+
private connectRealtime;
|
|
288
293
|
private connectWebSocket;
|
|
294
|
+
private connectSSE;
|
|
295
|
+
private handleWsFailure;
|
|
296
|
+
private handleRealtimeEvent;
|
|
289
297
|
private handleWebSocketEvent;
|
|
290
298
|
private handleVersionWarning;
|
|
291
299
|
private scheduleReconnect;
|
package/dist/index.js
CHANGED
|
@@ -658,6 +658,7 @@ var PocketPingClient = class {
|
|
|
658
658
|
constructor(config) {
|
|
659
659
|
this.session = null;
|
|
660
660
|
this.ws = null;
|
|
661
|
+
this.sse = null;
|
|
661
662
|
this.isOpen = false;
|
|
662
663
|
this.listeners = /* @__PURE__ */ new Map();
|
|
663
664
|
this.customEventHandlers = /* @__PURE__ */ new Map();
|
|
@@ -667,6 +668,10 @@ var PocketPingClient = class {
|
|
|
667
668
|
this.pollingTimeout = null;
|
|
668
669
|
this.pollingFailures = 0;
|
|
669
670
|
this.maxPollingFailures = 10;
|
|
671
|
+
this.wsConnectedAt = 0;
|
|
672
|
+
this.quickFailureThreshold = 2e3;
|
|
673
|
+
// If WS fails within 2s, assume serverless
|
|
674
|
+
this.connectionMode = "none";
|
|
670
675
|
this.trackedElementCleanups = [];
|
|
671
676
|
this.currentTrackedElements = [];
|
|
672
677
|
this.inspectorMode = false;
|
|
@@ -727,7 +732,7 @@ var PocketPingClient = class {
|
|
|
727
732
|
welcomeMessage: this.config.welcomeMessage
|
|
728
733
|
});
|
|
729
734
|
this.storeSessionId(response.sessionId);
|
|
730
|
-
this.
|
|
735
|
+
this.connectRealtime();
|
|
731
736
|
if (response.inspectorMode) {
|
|
732
737
|
this.enableInspectorMode();
|
|
733
738
|
} else if (response.trackedElements?.length) {
|
|
@@ -738,9 +743,20 @@ var PocketPingClient = class {
|
|
|
738
743
|
return this.session;
|
|
739
744
|
}
|
|
740
745
|
disconnect() {
|
|
741
|
-
this.ws
|
|
742
|
-
|
|
746
|
+
if (this.ws) {
|
|
747
|
+
this.ws.onclose = null;
|
|
748
|
+
this.ws.onmessage = null;
|
|
749
|
+
this.ws.onerror = null;
|
|
750
|
+
this.ws.onopen = null;
|
|
751
|
+
this.ws.close();
|
|
752
|
+
this.ws = null;
|
|
753
|
+
}
|
|
754
|
+
if (this.sse) {
|
|
755
|
+
this.sse.close();
|
|
756
|
+
this.sse = null;
|
|
757
|
+
}
|
|
743
758
|
this.session = null;
|
|
759
|
+
this.connectionMode = "none";
|
|
744
760
|
if (this.reconnectTimeout) {
|
|
745
761
|
clearTimeout(this.reconnectTimeout);
|
|
746
762
|
}
|
|
@@ -1344,37 +1360,122 @@ var PocketPingClient = class {
|
|
|
1344
1360
|
return this.inspectorMode;
|
|
1345
1361
|
}
|
|
1346
1362
|
// ─────────────────────────────────────────────────────────────────
|
|
1347
|
-
// WebSocket
|
|
1363
|
+
// Real-time Connection (WebSocket → SSE → Polling)
|
|
1348
1364
|
// ─────────────────────────────────────────────────────────────────
|
|
1365
|
+
connectRealtime() {
|
|
1366
|
+
if (!this.session) return;
|
|
1367
|
+
if (this.connectionMode === "polling") {
|
|
1368
|
+
this.startPolling();
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
if (this.connectionMode === "sse") {
|
|
1372
|
+
this.connectSSE();
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
this.connectWebSocket();
|
|
1376
|
+
}
|
|
1349
1377
|
connectWebSocket() {
|
|
1350
1378
|
if (!this.session) return;
|
|
1351
1379
|
const wsUrl = this.config.endpoint.replace(/^http/, "ws").replace(/\/$/, "") + `/stream?sessionId=${this.session.sessionId}`;
|
|
1352
1380
|
try {
|
|
1353
1381
|
this.ws = new WebSocket(wsUrl);
|
|
1382
|
+
this.wsConnectedAt = Date.now();
|
|
1383
|
+
const connectionTimeout = setTimeout(() => {
|
|
1384
|
+
console.warn("[PocketPing] \u23F1\uFE0F WebSocket timeout - trying SSE");
|
|
1385
|
+
if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
|
|
1386
|
+
this.ws.onclose = null;
|
|
1387
|
+
this.ws.onerror = null;
|
|
1388
|
+
this.ws.onopen = null;
|
|
1389
|
+
this.ws.close();
|
|
1390
|
+
this.ws = null;
|
|
1391
|
+
this.connectSSE();
|
|
1392
|
+
}
|
|
1393
|
+
}, 5e3);
|
|
1354
1394
|
this.ws.onopen = () => {
|
|
1395
|
+
clearTimeout(connectionTimeout);
|
|
1396
|
+
this.connectionMode = "ws";
|
|
1355
1397
|
this.reconnectAttempts = 0;
|
|
1398
|
+
this.wsConnectedAt = Date.now();
|
|
1356
1399
|
this.emit("wsConnected", null);
|
|
1357
1400
|
};
|
|
1358
1401
|
this.ws.onmessage = (event) => {
|
|
1359
1402
|
try {
|
|
1360
1403
|
const wsEvent = JSON.parse(event.data);
|
|
1361
|
-
this.
|
|
1404
|
+
this.handleRealtimeEvent(wsEvent);
|
|
1362
1405
|
} catch (err) {
|
|
1363
1406
|
console.error("[PocketPing] Failed to parse WS message:", err);
|
|
1364
1407
|
}
|
|
1365
1408
|
};
|
|
1366
1409
|
this.ws.onclose = () => {
|
|
1410
|
+
clearTimeout(connectionTimeout);
|
|
1367
1411
|
this.emit("wsDisconnected", null);
|
|
1368
|
-
this.
|
|
1412
|
+
this.handleWsFailure();
|
|
1369
1413
|
};
|
|
1370
|
-
this.ws.onerror = (
|
|
1371
|
-
|
|
1414
|
+
this.ws.onerror = () => {
|
|
1415
|
+
clearTimeout(connectionTimeout);
|
|
1372
1416
|
};
|
|
1373
|
-
} catch
|
|
1374
|
-
console.warn("[PocketPing] WebSocket unavailable
|
|
1417
|
+
} catch {
|
|
1418
|
+
console.warn("[PocketPing] WebSocket unavailable - trying SSE");
|
|
1419
|
+
this.connectSSE();
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
connectSSE() {
|
|
1423
|
+
if (!this.session) return;
|
|
1424
|
+
const sseUrl = this.config.endpoint.replace(/\/$/, "") + `/stream?sessionId=${this.session.sessionId}`;
|
|
1425
|
+
try {
|
|
1426
|
+
this.sse = new EventSource(sseUrl);
|
|
1427
|
+
const connectionTimeout = setTimeout(() => {
|
|
1428
|
+
console.warn("[PocketPing] \u23F1\uFE0F SSE timeout - falling back to polling");
|
|
1429
|
+
if (this.sse && this.sse.readyState !== EventSource.OPEN) {
|
|
1430
|
+
this.sse.close();
|
|
1431
|
+
this.sse = null;
|
|
1432
|
+
this.connectionMode = "polling";
|
|
1433
|
+
this.startPolling();
|
|
1434
|
+
}
|
|
1435
|
+
}, 5e3);
|
|
1436
|
+
this.sse.onopen = () => {
|
|
1437
|
+
clearTimeout(connectionTimeout);
|
|
1438
|
+
this.connectionMode = "sse";
|
|
1439
|
+
this.emit("sseConnected", null);
|
|
1440
|
+
};
|
|
1441
|
+
this.sse.addEventListener("message", (event) => {
|
|
1442
|
+
try {
|
|
1443
|
+
const data = JSON.parse(event.data);
|
|
1444
|
+
this.handleRealtimeEvent(data);
|
|
1445
|
+
} catch (err) {
|
|
1446
|
+
console.error("[PocketPing] Failed to parse SSE message:", err);
|
|
1447
|
+
}
|
|
1448
|
+
});
|
|
1449
|
+
this.sse.addEventListener("connected", () => {
|
|
1450
|
+
});
|
|
1451
|
+
this.sse.onerror = () => {
|
|
1452
|
+
clearTimeout(connectionTimeout);
|
|
1453
|
+
console.warn("[PocketPing] \u274C SSE error - falling back to polling");
|
|
1454
|
+
if (this.sse) {
|
|
1455
|
+
this.sse.close();
|
|
1456
|
+
this.sse = null;
|
|
1457
|
+
}
|
|
1458
|
+
this.connectionMode = "polling";
|
|
1459
|
+
this.startPolling();
|
|
1460
|
+
};
|
|
1461
|
+
} catch {
|
|
1462
|
+
console.warn("[PocketPing] SSE unavailable - falling back to polling");
|
|
1463
|
+
this.connectionMode = "polling";
|
|
1375
1464
|
this.startPolling();
|
|
1376
1465
|
}
|
|
1377
1466
|
}
|
|
1467
|
+
handleWsFailure() {
|
|
1468
|
+
const timeSinceConnect = Date.now() - this.wsConnectedAt;
|
|
1469
|
+
if (timeSinceConnect < this.quickFailureThreshold) {
|
|
1470
|
+
console.info("[PocketPing] WebSocket failed quickly - trying SSE");
|
|
1471
|
+
this.connectSSE();
|
|
1472
|
+
return;
|
|
1473
|
+
}
|
|
1474
|
+
this.scheduleReconnect();
|
|
1475
|
+
}
|
|
1476
|
+
handleRealtimeEvent(event) {
|
|
1477
|
+
this.handleWebSocketEvent(event);
|
|
1478
|
+
}
|
|
1378
1479
|
handleWebSocketEvent(event) {
|
|
1379
1480
|
switch (event.type) {
|
|
1380
1481
|
case "message":
|
|
@@ -1486,8 +1587,8 @@ var PocketPingClient = class {
|
|
|
1486
1587
|
}
|
|
1487
1588
|
scheduleReconnect() {
|
|
1488
1589
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
1489
|
-
console.warn("[PocketPing] Max reconnect attempts reached,
|
|
1490
|
-
this.
|
|
1590
|
+
console.warn("[PocketPing] Max reconnect attempts reached, trying SSE");
|
|
1591
|
+
this.connectSSE();
|
|
1491
1592
|
return;
|
|
1492
1593
|
}
|
|
1493
1594
|
const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
|
|
@@ -1512,6 +1613,7 @@ var PocketPingClient = class {
|
|
|
1512
1613
|
}
|
|
1513
1614
|
} catch (err) {
|
|
1514
1615
|
this.pollingFailures++;
|
|
1616
|
+
console.error(`[PocketPing] \u274C Polling error:`, err);
|
|
1515
1617
|
if (this.pollingFailures <= 3 || this.pollingFailures % 3 === 0) {
|
|
1516
1618
|
console.warn(`[PocketPing] Polling failed (${this.pollingFailures}/${this.maxPollingFailures})`);
|
|
1517
1619
|
}
|
|
@@ -1522,11 +1624,11 @@ var PocketPingClient = class {
|
|
|
1522
1624
|
}
|
|
1523
1625
|
}
|
|
1524
1626
|
if (this.session) {
|
|
1525
|
-
const delay = this.pollingFailures > 0 ? Math.min(
|
|
1627
|
+
const delay = this.pollingFailures > 0 ? Math.min(2e3 * Math.pow(2, this.pollingFailures - 1), 3e4) : 2e3;
|
|
1526
1628
|
this.pollingTimeout = setTimeout(poll, delay);
|
|
1527
1629
|
}
|
|
1528
1630
|
};
|
|
1529
|
-
poll
|
|
1631
|
+
this.pollingTimeout = setTimeout(poll, 500);
|
|
1530
1632
|
}
|
|
1531
1633
|
stopPolling() {
|
|
1532
1634
|
if (this.pollingTimeout) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var PocketPing=(()=>{var te=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var gt=(t,e)=>{for(var n in e)te(t,n,{get:e[n],enumerable:!0})},_t=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dt(e))!ut.call(t,o)&&o!==n&&te(t,o,{get:()=>e[o],enumerable:!(s=pt(e,o))||s.enumerable});return t};var ft=t=>_t(te({},"__esModule",{value:!0}),t);var Rt={};gt(Rt,{close:()=>Ge,default:()=>Ht,destroy:()=>Je,getIdentity:()=>it,getTrackedElements:()=>et,identify:()=>st,init:()=>fe,offEvent:()=>nt,on:()=>rt,onEvent:()=>tt,open:()=>Xe,reset:()=>ot,sendMessage:()=>Ze,setupTrackedElements:()=>Qe,toggle:()=>Ye,trigger:()=>Ke});var G,y,be,ht,N,he,xe,ke,we,ie,ne,se,mt,F={},Pe=[],vt=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Y=Array.isArray;function T(t,e){for(var n in e)t[n]=e[n];return t}function re(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ae(t,e,n){var s,o,i,a={};for(i in e)i=="key"?s=e[i]:i=="ref"?o=e[i]:a[i]=e[i];if(arguments.length>2&&(a.children=arguments.length>3?G.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(i in t.defaultProps)a[i]===void 0&&(a[i]=t.defaultProps[i]);return q(t,a,s,o,null)}function q(t,e,n,s,o){var i={type:t,props:e,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++be,__i:-1,__u:0};return o==null&&y.vnode!=null&&y.vnode(i),i}function I(t){return t.children}function J(t,e){this.props=t,this.context=e}function L(t,e){if(e==null)return t.__?L(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?L(t):null}function Ee(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Ee(t)}}function me(t){(!t.__d&&(t.__d=!0)&&N.push(t)&&!X.__r++||he!=y.debounceRendering)&&((he=y.debounceRendering)||xe)(X)}function X(){for(var t,e,n,s,o,i,a,l=1;N.length;)N.length>l&&N.sort(ke),t=N.shift(),l=N.length,t.__d&&(n=void 0,s=void 0,o=(s=(e=t).__v).__e,i=[],a=[],e.__P&&((n=T({},s)).__v=s.__v+1,y.vnode&&y.vnode(n),ce(e.__P,n,s,e.__n,e.__P.namespaceURI,32&s.__u?[o]:null,i,o??L(s),!!(32&s.__u),a),n.__v=s.__v,n.__.__k[n.__i]=n,Ie(i,n,a),s.__e=s.__=null,n.__e!=o&&Ee(n)));X.__r=0}function Se(t,e,n,s,o,i,a,l,p,c,g){var r,d,_,x,E,h,v,m=s&&s.__k||Pe,C=e.length;for(p=yt(n,e,m,p,C),r=0;r<C;r++)(_=n.__k[r])!=null&&(d=_.__i==-1?F:m[_.__i]||F,_.__i=r,h=ce(t,_,d,o,i,a,l,p,c,g),x=_.__e,_.ref&&d.ref!=_.ref&&(d.ref&&le(d.ref,null,_),g.push(_.ref,_.__c||x,_)),E==null&&x!=null&&(E=x),(v=!!(4&_.__u))||d.__k===_.__k?p=Ce(_,p,t,v):typeof _.type=="function"&&h!==void 0?p=h:x&&(p=x.nextSibling),_.__u&=-7);return n.__e=E,p}function yt(t,e,n,s,o){var i,a,l,p,c,g=n.length,r=g,d=0;for(t.__k=new Array(o),i=0;i<o;i++)(a=e[i])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=t.__k[i]=q(null,a,null,null,null):Y(a)?a=t.__k[i]=q(I,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=t.__k[i]=q(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):t.__k[i]=a,p=i+d,a.__=t,a.__b=t.__b+1,l=null,(c=a.__i=bt(a,n,p,r))!=-1&&(r--,(l=n[c])&&(l.__u|=2)),l==null||l.__v==null?(c==-1&&(o>g?d--:o<g&&d++),typeof a.type!="function"&&(a.__u|=4)):c!=p&&(c==p-1?d--:c==p+1?d++:(c>p?d--:d++,a.__u|=4))):t.__k[i]=null;if(r)for(i=0;i<g;i++)(l=n[i])!=null&&(2&l.__u)==0&&(l.__e==s&&(s=L(l)),Me(l,l));return s}function Ce(t,e,n,s){var o,i;if(typeof t.type=="function"){for(o=t.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=t,e=Ce(o[i],e,n,s));return e}t.__e!=e&&(s&&(e&&t.type&&!e.parentNode&&(e=L(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function bt(t,e,n,s){var o,i,a,l=t.key,p=t.type,c=e[n],g=c!=null&&(2&c.__u)==0;if(c===null&&l==null||g&&l==c.key&&p==c.type)return n;if(s>(g?1:0)){for(o=n-1,i=n+1;o>=0||i<e.length;)if((c=e[a=o>=0?o--:i++])!=null&&(2&c.__u)==0&&l==c.key&&p==c.type)return a}return-1}function ve(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||vt.test(e)?n:n+"px"}function B(t,e,n,s,o){var i,a;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof s=="string"&&(t.style.cssText=s=""),s)for(e in s)n&&e in n||ve(t.style,e,"");if(n)for(e in n)s&&n[e]==s[e]||ve(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")i=e!=(e=e.replace(we,"$1")),a=e.toLowerCase(),e=a in t||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+i]=n,n?s?n.u=s.u:(n.u=ie,t.addEventListener(e,i?se:ne,i)):t.removeEventListener(e,i?se:ne,i);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function ye(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ie++;else if(e.t<n.u)return;return n(y.event?y.event(e):e)}}}function ce(t,e,n,s,o,i,a,l,p,c){var g,r,d,_,x,E,h,v,m,C,S,W,H,j,R,$,V,f=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(p=!!(32&n.__u),i=[l=e.__e=n.__e]),(g=y.__b)&&g(e);e:if(typeof f=="function")try{if(v=e.props,m="prototype"in f&&f.prototype.render,C=(g=f.contextType)&&s[g.__c],S=g?C?C.props.value:g.__:s,n.__c?h=(r=e.__c=n.__c).__=r.__E:(m?e.__c=r=new f(v,S):(e.__c=r=new J(v,S),r.constructor=f,r.render=kt),C&&C.sub(r),r.state||(r.state={}),r.__n=s,d=r.__d=!0,r.__h=[],r._sb=[]),m&&r.__s==null&&(r.__s=r.state),m&&f.getDerivedStateFromProps!=null&&(r.__s==r.state&&(r.__s=T({},r.__s)),T(r.__s,f.getDerivedStateFromProps(v,r.__s))),_=r.props,x=r.state,r.__v=e,d)m&&f.getDerivedStateFromProps==null&&r.componentWillMount!=null&&r.componentWillMount(),m&&r.componentDidMount!=null&&r.__h.push(r.componentDidMount);else{if(m&&f.getDerivedStateFromProps==null&&v!==_&&r.componentWillReceiveProps!=null&&r.componentWillReceiveProps(v,S),e.__v==n.__v||!r.__e&&r.shouldComponentUpdate!=null&&r.shouldComponentUpdate(v,r.__s,S)===!1){for(e.__v!=n.__v&&(r.props=v,r.state=r.__s,r.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(w){w&&(w.__=e)}),W=0;W<r._sb.length;W++)r.__h.push(r._sb[W]);r._sb=[],r.__h.length&&a.push(r);break e}r.componentWillUpdate!=null&&r.componentWillUpdate(v,r.__s,S),m&&r.componentDidUpdate!=null&&r.__h.push(function(){r.componentDidUpdate(_,x,E)})}if(r.context=S,r.props=v,r.__P=t,r.__e=!1,H=y.__r,j=0,m){for(r.state=r.__s,r.__d=!1,H&&H(e),g=r.render(r.props,r.state,r.context),R=0;R<r._sb.length;R++)r.__h.push(r._sb[R]);r._sb=[]}else do r.__d=!1,H&&H(e),g=r.render(r.props,r.state,r.context),r.state=r.__s;while(r.__d&&++j<25);r.state=r.__s,r.getChildContext!=null&&(s=T(T({},s),r.getChildContext())),m&&!d&&r.getSnapshotBeforeUpdate!=null&&(E=r.getSnapshotBeforeUpdate(_,x)),$=g,g!=null&&g.type===I&&g.key==null&&($=Te(g.props.children)),l=Se(t,Y($)?$:[$],e,n,s,o,i,a,l,p,c),r.base=e.__e,e.__u&=-161,r.__h.length&&a.push(r),h&&(r.__E=r.__=null)}catch(w){if(e.__v=null,p||i!=null)if(w.then){for(e.__u|=p?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;i[i.indexOf(l)]=null,e.__e=l}else{for(V=i.length;V--;)re(i[V]);oe(e)}else e.__e=n.__e,e.__k=n.__k,w.then||oe(e);y.__e(w,e,n)}else i==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=xt(n.__e,e,n,s,o,i,a,p,c);return(g=y.diffed)&&g(e),128&e.__u?void 0:l}function oe(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(oe)}function Ie(t,e,n){for(var s=0;s<n.length;s++)le(n[s],n[++s],n[++s]);y.__c&&y.__c(e,t),t.some(function(o){try{t=o.__h,o.__h=[],t.some(function(i){i.call(o)})}catch(i){y.__e(i,o.__v)}})}function Te(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Y(t)?t.map(Te):T({},t)}function xt(t,e,n,s,o,i,a,l,p){var c,g,r,d,_,x,E,h=n.props||F,v=e.props,m=e.type;if(m=="svg"?o="http://www.w3.org/2000/svg":m=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(c=0;c<i.length;c++)if((_=i[c])&&"setAttribute"in _==!!m&&(m?_.localName==m:_.nodeType==3)){t=_,i[c]=null;break}}if(t==null){if(m==null)return document.createTextNode(v);t=document.createElementNS(o,m,v.is&&v),l&&(y.__m&&y.__m(e,i),l=!1),i=null}if(m==null)h===v||l&&t.data==v||(t.data=v);else{if(i=i&&G.call(t.childNodes),!l&&i!=null)for(h={},c=0;c<t.attributes.length;c++)h[(_=t.attributes[c]).name]=_.value;for(c in h)if(_=h[c],c!="children"){if(c=="dangerouslySetInnerHTML")r=_;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;B(t,c,null,_,o)}}for(c in v)_=v[c],c=="children"?d=_:c=="dangerouslySetInnerHTML"?g=_:c=="value"?x=_:c=="checked"?E=_:l&&typeof _!="function"||h[c]===_||B(t,c,_,h[c],o);if(g)l||r&&(g.__html==r.__html||g.__html==t.innerHTML)||(t.innerHTML=g.__html),e.__k=[];else if(r&&(t.innerHTML=""),Se(e.type=="template"?t.content:t,Y(d)?d:[d],e,n,s,m=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,a,i?i[0]:n.__k&&L(n,0),l,p),i!=null)for(c=i.length;c--;)re(i[c]);l||(c="value",m=="progress"&&x==null?t.removeAttribute("value"):x!=null&&(x!==t[c]||m=="progress"&&!x||m=="option"&&x!=h[c])&&B(t,c,x,h[c],o),c="checked",E!=null&&E!=t[c]&&B(t,c,E,h[c],o))}return t}function le(t,e,n){try{if(typeof t=="function"){var s=typeof t.__u=="function";s&&t.__u(),s&&e==null||(t.__u=t(e))}else t.current=e}catch(o){y.__e(o,n)}}function Me(t,e,n){var s,o;if(y.unmount&&y.unmount(t),(s=t.ref)&&(s.current&&s.current!=t.__e||le(s,null,e)),(s=t.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(i){y.__e(i,e)}s.base=s.__P=null}if(s=t.__k)for(o=0;o<s.length;o++)s[o]&&Me(s[o],e,n||typeof t.type!="function");n||re(t.__e),t.__c=t.__=t.__e=void 0}function kt(t,e,n){return this.constructor(t,n)}function pe(t,e,n){var s,o,i,a;e==document&&(e=document.documentElement),y.__&&y.__(t,e),o=(s=typeof n=="function")?null:n&&n.__k||e.__k,i=[],a=[],ce(e,t=(!s&&n||e).__k=ae(I,null,[t]),o||F,F,e.namespaceURI,!s&&n?[n]:o?null:e.firstChild?G.call(e.childNodes):null,i,!s&&n?n:o?o.__e:e.firstChild,s,a),Ie(i,t,a)}G=Pe.slice,y={__e:function(t,e,n,s){for(var o,i,a;e=e.__;)if((o=e.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(t)),a=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(t,s||{}),a=o.__d),a)return o.__E=o}catch(l){t=l}throw t}},be=0,ht=function(t){return t!=null&&t.constructor===void 0},J.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=T({},this.state),typeof t=="function"&&(t=t(T({},n),this.props)),t&&T(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),me(this))},J.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),me(this))},J.prototype.render=I,N=[],xe=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ke=function(t,e){return t.__v.__b-e.__v.__b},X.__r=0,we=/(PointerCapture)$|Capture$/i,ie=0,ne=ye(!1),se=ye(!0),mt=0;var D,k,de,$e,z=0,Ve=[],P=y,Oe=P.__b,Ae=P.__r,He=P.diffed,Re=P.__c,Ne=P.unmount,Le=P.__;function ge(t,e){P.__h&&P.__h(k,t,z||e),z=0;var n=k.__H||(k.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function M(t){return z=1,wt(ze,t)}function wt(t,e,n){var s=ge(D++,2);if(s.t=t,!s.__c&&(s.__=[n?n(e):ze(void 0,e),function(l){var p=s.__N?s.__N[0]:s.__[0],c=s.t(p,l);p!==c&&(s.__N=[c,s.__[1]],s.__c.setState({}))}],s.__c=k,!k.__f)){var o=function(l,p,c){if(!s.__c.__H)return!0;var g=s.__c.__H.__.filter(function(d){return!!d.__c});if(g.every(function(d){return!d.__N}))return!i||i.call(this,l,p,c);var r=s.__c.props!==l;return g.forEach(function(d){if(d.__N){var _=d.__[0];d.__=d.__N,d.__N=void 0,_!==d.__[0]&&(r=!0)}}),i&&i.call(this,l,p,c)||r};k.__f=!0;var i=k.shouldComponentUpdate,a=k.componentWillUpdate;k.componentWillUpdate=function(l,p,c){if(this.__e){var g=i;i=void 0,o(l,p,c),i=g}a&&a.call(this,l,p,c)},k.shouldComponentUpdate=o}return s.__N||s.__}function O(t,e){var n=ge(D++,3);!P.__s&&De(n.__H,e)&&(n.__=t,n.u=e,k.__H.__h.push(n))}function _e(t){return z=5,Ue(function(){return{current:t}},[])}function Ue(t,e){var n=ge(D++,7);return De(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Fe(t,e){return z=8,Ue(function(){return t},e)}function Pt(){for(var t;t=Ve.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Z),t.__H.__h.forEach(ue),t.__H.__h=[]}catch(e){t.__H.__h=[],P.__e(e,t.__v)}}P.__b=function(t){k=null,Oe&&Oe(t)},P.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Le&&Le(t,e)},P.__r=function(t){Ae&&Ae(t),D=0;var e=(k=t.__c).__H;e&&(de===k?(e.__h=[],k.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Z),e.__h.forEach(ue),e.__h=[],D=0)),de=k},P.diffed=function(t){He&&He(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Ve.push(e)!==1&&$e===P.requestAnimationFrame||(($e=P.requestAnimationFrame)||Et)(Pt)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),de=k=null},P.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Z),n.__h=n.__h.filter(function(s){return!s.__||ue(s)})}catch(s){e.some(function(o){o.__h&&(o.__h=[])}),e=[],P.__e(s,n.__v)}}),Re&&Re(t,e)},P.unmount=function(t){Ne&&Ne(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(s){try{Z(s)}catch(o){e=o}}),n.__H=void 0,e&&P.__e(e,n.__v))};var We=typeof requestAnimationFrame=="function";function Et(t){var e,n=function(){clearTimeout(s),We&&cancelAnimationFrame(e),setTimeout(t)},s=setTimeout(n,35);We&&(e=requestAnimationFrame(n))}function Z(t){var e=k,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),k=e}function ue(t){var e=k;t.__c=t.__(),k=e}function De(t,e){return!t||t.length!==e.length||e.some(function(n,s){return n!==t[s]})}function ze(t,e){return typeof e=="function"?e(t):e}function je(t,e){let n=e==="dark",s={bg:n?"#1f2937":"#ffffff",bgSecondary:n?"#374151":"#f3f4f6",text:n?"#f9fafb":"#111827",textSecondary:n?"#9ca3af":"#6b7280",border:n?"#4b5563":"#e5e7eb",messageBg:n?"#374151":"#f3f4f6"};return`
|
|
1
|
+
"use strict";var PocketPing=(()=>{var te=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var gt=(t,e)=>{for(var n in e)te(t,n,{get:e[n],enumerable:!0})},ht=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dt(e))!ut.call(t,o)&&o!==n&&te(t,o,{get:()=>e[o],enumerable:!(s=pt(e,o))||s.enumerable});return t};var _t=t=>ht(te({},"__esModule",{value:!0}),t);var Rt={};gt(Rt,{close:()=>Ge,default:()=>Ht,destroy:()=>Je,getIdentity:()=>it,getTrackedElements:()=>et,identify:()=>st,init:()=>_e,offEvent:()=>nt,on:()=>rt,onEvent:()=>tt,open:()=>Xe,reset:()=>ot,sendMessage:()=>Ze,setupTrackedElements:()=>Qe,toggle:()=>Ye,trigger:()=>Ke});var G,y,be,ft,N,fe,ke,xe,we,ie,ne,se,mt,U={},Se=[],vt=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Y=Array.isArray;function T(t,e){for(var n in e)t[n]=e[n];return t}function re(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ae(t,e,n){var s,o,i,a={};for(i in e)i=="key"?s=e[i]:i=="ref"?o=e[i]:a[i]=e[i];if(arguments.length>2&&(a.children=arguments.length>3?G.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(i in t.defaultProps)a[i]===void 0&&(a[i]=t.defaultProps[i]);return q(t,a,s,o,null)}function q(t,e,n,s,o){var i={type:t,props:e,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++be,__i:-1,__u:0};return o==null&&y.vnode!=null&&y.vnode(i),i}function I(t){return t.children}function J(t,e){this.props=t,this.context=e}function L(t,e){if(e==null)return t.__?L(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?L(t):null}function Pe(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Pe(t)}}function me(t){(!t.__d&&(t.__d=!0)&&N.push(t)&&!X.__r++||fe!=y.debounceRendering)&&((fe=y.debounceRendering)||ke)(X)}function X(){for(var t,e,n,s,o,i,a,l=1;N.length;)N.length>l&&N.sort(xe),t=N.shift(),l=N.length,t.__d&&(n=void 0,s=void 0,o=(s=(e=t).__v).__e,i=[],a=[],e.__P&&((n=T({},s)).__v=s.__v+1,y.vnode&&y.vnode(n),ce(e.__P,n,s,e.__n,e.__P.namespaceURI,32&s.__u?[o]:null,i,o??L(s),!!(32&s.__u),a),n.__v=s.__v,n.__.__k[n.__i]=n,Ie(i,n,a),s.__e=s.__=null,n.__e!=o&&Pe(n)));X.__r=0}function Ee(t,e,n,s,o,i,a,l,p,c,g){var r,d,h,k,P,f,v,m=s&&s.__k||Se,C=e.length;for(p=yt(n,e,m,p,C),r=0;r<C;r++)(h=n.__k[r])!=null&&(d=h.__i==-1?U:m[h.__i]||U,h.__i=r,f=ce(t,h,d,o,i,a,l,p,c,g),k=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&le(d.ref,null,h),g.push(h.ref,h.__c||k,h)),P==null&&k!=null&&(P=k),(v=!!(4&h.__u))||d.__k===h.__k?p=Ce(h,p,t,v):typeof h.type=="function"&&f!==void 0?p=f:k&&(p=k.nextSibling),h.__u&=-7);return n.__e=P,p}function yt(t,e,n,s,o){var i,a,l,p,c,g=n.length,r=g,d=0;for(t.__k=new Array(o),i=0;i<o;i++)(a=e[i])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=t.__k[i]=q(null,a,null,null,null):Y(a)?a=t.__k[i]=q(I,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=t.__k[i]=q(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):t.__k[i]=a,p=i+d,a.__=t,a.__b=t.__b+1,l=null,(c=a.__i=bt(a,n,p,r))!=-1&&(r--,(l=n[c])&&(l.__u|=2)),l==null||l.__v==null?(c==-1&&(o>g?d--:o<g&&d++),typeof a.type!="function"&&(a.__u|=4)):c!=p&&(c==p-1?d--:c==p+1?d++:(c>p?d--:d++,a.__u|=4))):t.__k[i]=null;if(r)for(i=0;i<g;i++)(l=n[i])!=null&&(2&l.__u)==0&&(l.__e==s&&(s=L(l)),Me(l,l));return s}function Ce(t,e,n,s){var o,i;if(typeof t.type=="function"){for(o=t.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=t,e=Ce(o[i],e,n,s));return e}t.__e!=e&&(s&&(e&&t.type&&!e.parentNode&&(e=L(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function bt(t,e,n,s){var o,i,a,l=t.key,p=t.type,c=e[n],g=c!=null&&(2&c.__u)==0;if(c===null&&l==null||g&&l==c.key&&p==c.type)return n;if(s>(g?1:0)){for(o=n-1,i=n+1;o>=0||i<e.length;)if((c=e[a=o>=0?o--:i++])!=null&&(2&c.__u)==0&&l==c.key&&p==c.type)return a}return-1}function ve(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||vt.test(e)?n:n+"px"}function B(t,e,n,s,o){var i,a;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof s=="string"&&(t.style.cssText=s=""),s)for(e in s)n&&e in n||ve(t.style,e,"");if(n)for(e in n)s&&n[e]==s[e]||ve(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")i=e!=(e=e.replace(we,"$1")),a=e.toLowerCase(),e=a in t||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+i]=n,n?s?n.u=s.u:(n.u=ie,t.addEventListener(e,i?se:ne,i)):t.removeEventListener(e,i?se:ne,i);else{if(o=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function ye(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ie++;else if(e.t<n.u)return;return n(y.event?y.event(e):e)}}}function ce(t,e,n,s,o,i,a,l,p,c){var g,r,d,h,k,P,f,v,m,C,E,W,H,j,R,$,F,_=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(p=!!(32&n.__u),i=[l=e.__e=n.__e]),(g=y.__b)&&g(e);e:if(typeof _=="function")try{if(v=e.props,m="prototype"in _&&_.prototype.render,C=(g=_.contextType)&&s[g.__c],E=g?C?C.props.value:g.__:s,n.__c?f=(r=e.__c=n.__c).__=r.__E:(m?e.__c=r=new _(v,E):(e.__c=r=new J(v,E),r.constructor=_,r.render=xt),C&&C.sub(r),r.state||(r.state={}),r.__n=s,d=r.__d=!0,r.__h=[],r._sb=[]),m&&r.__s==null&&(r.__s=r.state),m&&_.getDerivedStateFromProps!=null&&(r.__s==r.state&&(r.__s=T({},r.__s)),T(r.__s,_.getDerivedStateFromProps(v,r.__s))),h=r.props,k=r.state,r.__v=e,d)m&&_.getDerivedStateFromProps==null&&r.componentWillMount!=null&&r.componentWillMount(),m&&r.componentDidMount!=null&&r.__h.push(r.componentDidMount);else{if(m&&_.getDerivedStateFromProps==null&&v!==h&&r.componentWillReceiveProps!=null&&r.componentWillReceiveProps(v,E),e.__v==n.__v||!r.__e&&r.shouldComponentUpdate!=null&&r.shouldComponentUpdate(v,r.__s,E)===!1){for(e.__v!=n.__v&&(r.props=v,r.state=r.__s,r.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(w){w&&(w.__=e)}),W=0;W<r._sb.length;W++)r.__h.push(r._sb[W]);r._sb=[],r.__h.length&&a.push(r);break e}r.componentWillUpdate!=null&&r.componentWillUpdate(v,r.__s,E),m&&r.componentDidUpdate!=null&&r.__h.push(function(){r.componentDidUpdate(h,k,P)})}if(r.context=E,r.props=v,r.__P=t,r.__e=!1,H=y.__r,j=0,m){for(r.state=r.__s,r.__d=!1,H&&H(e),g=r.render(r.props,r.state,r.context),R=0;R<r._sb.length;R++)r.__h.push(r._sb[R]);r._sb=[]}else do r.__d=!1,H&&H(e),g=r.render(r.props,r.state,r.context),r.state=r.__s;while(r.__d&&++j<25);r.state=r.__s,r.getChildContext!=null&&(s=T(T({},s),r.getChildContext())),m&&!d&&r.getSnapshotBeforeUpdate!=null&&(P=r.getSnapshotBeforeUpdate(h,k)),$=g,g!=null&&g.type===I&&g.key==null&&($=Te(g.props.children)),l=Ee(t,Y($)?$:[$],e,n,s,o,i,a,l,p,c),r.base=e.__e,e.__u&=-161,r.__h.length&&a.push(r),f&&(r.__E=r.__=null)}catch(w){if(e.__v=null,p||i!=null)if(w.then){for(e.__u|=p?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;i[i.indexOf(l)]=null,e.__e=l}else{for(F=i.length;F--;)re(i[F]);oe(e)}else e.__e=n.__e,e.__k=n.__k,w.then||oe(e);y.__e(w,e,n)}else i==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=kt(n.__e,e,n,s,o,i,a,p,c);return(g=y.diffed)&&g(e),128&e.__u?void 0:l}function oe(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(oe)}function Ie(t,e,n){for(var s=0;s<n.length;s++)le(n[s],n[++s],n[++s]);y.__c&&y.__c(e,t),t.some(function(o){try{t=o.__h,o.__h=[],t.some(function(i){i.call(o)})}catch(i){y.__e(i,o.__v)}})}function Te(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Y(t)?t.map(Te):T({},t)}function kt(t,e,n,s,o,i,a,l,p){var c,g,r,d,h,k,P,f=n.props||U,v=e.props,m=e.type;if(m=="svg"?o="http://www.w3.org/2000/svg":m=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(c=0;c<i.length;c++)if((h=i[c])&&"setAttribute"in h==!!m&&(m?h.localName==m:h.nodeType==3)){t=h,i[c]=null;break}}if(t==null){if(m==null)return document.createTextNode(v);t=document.createElementNS(o,m,v.is&&v),l&&(y.__m&&y.__m(e,i),l=!1),i=null}if(m==null)f===v||l&&t.data==v||(t.data=v);else{if(i=i&&G.call(t.childNodes),!l&&i!=null)for(f={},c=0;c<t.attributes.length;c++)f[(h=t.attributes[c]).name]=h.value;for(c in f)if(h=f[c],c!="children"){if(c=="dangerouslySetInnerHTML")r=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;B(t,c,null,h,o)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?g=h:c=="value"?k=h:c=="checked"?P=h:l&&typeof h!="function"||f[c]===h||B(t,c,h,f[c],o);if(g)l||r&&(g.__html==r.__html||g.__html==t.innerHTML)||(t.innerHTML=g.__html),e.__k=[];else if(r&&(t.innerHTML=""),Ee(e.type=="template"?t.content:t,Y(d)?d:[d],e,n,s,m=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,a,i?i[0]:n.__k&&L(n,0),l,p),i!=null)for(c=i.length;c--;)re(i[c]);l||(c="value",m=="progress"&&k==null?t.removeAttribute("value"):k!=null&&(k!==t[c]||m=="progress"&&!k||m=="option"&&k!=f[c])&&B(t,c,k,f[c],o),c="checked",P!=null&&P!=t[c]&&B(t,c,P,f[c],o))}return t}function le(t,e,n){try{if(typeof t=="function"){var s=typeof t.__u=="function";s&&t.__u(),s&&e==null||(t.__u=t(e))}else t.current=e}catch(o){y.__e(o,n)}}function Me(t,e,n){var s,o;if(y.unmount&&y.unmount(t),(s=t.ref)&&(s.current&&s.current!=t.__e||le(s,null,e)),(s=t.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(i){y.__e(i,e)}s.base=s.__P=null}if(s=t.__k)for(o=0;o<s.length;o++)s[o]&&Me(s[o],e,n||typeof t.type!="function");n||re(t.__e),t.__c=t.__=t.__e=void 0}function xt(t,e,n){return this.constructor(t,n)}function pe(t,e,n){var s,o,i,a;e==document&&(e=document.documentElement),y.__&&y.__(t,e),o=(s=typeof n=="function")?null:n&&n.__k||e.__k,i=[],a=[],ce(e,t=(!s&&n||e).__k=ae(I,null,[t]),o||U,U,e.namespaceURI,!s&&n?[n]:o?null:e.firstChild?G.call(e.childNodes):null,i,!s&&n?n:o?o.__e:e.firstChild,s,a),Ie(i,t,a)}G=Se.slice,y={__e:function(t,e,n,s){for(var o,i,a;e=e.__;)if((o=e.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(t)),a=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(t,s||{}),a=o.__d),a)return o.__E=o}catch(l){t=l}throw t}},be=0,ft=function(t){return t!=null&&t.constructor===void 0},J.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=T({},this.state),typeof t=="function"&&(t=t(T({},n),this.props)),t&&T(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),me(this))},J.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),me(this))},J.prototype.render=I,N=[],ke=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,xe=function(t,e){return t.__v.__b-e.__v.__b},X.__r=0,we=/(PointerCapture)$|Capture$/i,ie=0,ne=ye(!1),se=ye(!0),mt=0;var D,x,de,$e,z=0,Fe=[],S=y,Oe=S.__b,Ae=S.__r,He=S.diffed,Re=S.__c,Ne=S.unmount,Le=S.__;function ge(t,e){S.__h&&S.__h(x,t,z||e),z=0;var n=x.__H||(x.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function M(t){return z=1,wt(ze,t)}function wt(t,e,n){var s=ge(D++,2);if(s.t=t,!s.__c&&(s.__=[n?n(e):ze(void 0,e),function(l){var p=s.__N?s.__N[0]:s.__[0],c=s.t(p,l);p!==c&&(s.__N=[c,s.__[1]],s.__c.setState({}))}],s.__c=x,!x.__f)){var o=function(l,p,c){if(!s.__c.__H)return!0;var g=s.__c.__H.__.filter(function(d){return!!d.__c});if(g.every(function(d){return!d.__N}))return!i||i.call(this,l,p,c);var r=s.__c.props!==l;return g.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(r=!0)}}),i&&i.call(this,l,p,c)||r};x.__f=!0;var i=x.shouldComponentUpdate,a=x.componentWillUpdate;x.componentWillUpdate=function(l,p,c){if(this.__e){var g=i;i=void 0,o(l,p,c),i=g}a&&a.call(this,l,p,c)},x.shouldComponentUpdate=o}return s.__N||s.__}function O(t,e){var n=ge(D++,3);!S.__s&&De(n.__H,e)&&(n.__=t,n.u=e,x.__H.__h.push(n))}function he(t){return z=5,Ve(function(){return{current:t}},[])}function Ve(t,e){var n=ge(D++,7);return De(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ue(t,e){return z=8,Ve(function(){return t},e)}function St(){for(var t;t=Fe.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Z),t.__H.__h.forEach(ue),t.__H.__h=[]}catch(e){t.__H.__h=[],S.__e(e,t.__v)}}S.__b=function(t){x=null,Oe&&Oe(t)},S.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Le&&Le(t,e)},S.__r=function(t){Ae&&Ae(t),D=0;var e=(x=t.__c).__H;e&&(de===x?(e.__h=[],x.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Z),e.__h.forEach(ue),e.__h=[],D=0)),de=x},S.diffed=function(t){He&&He(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Fe.push(e)!==1&&$e===S.requestAnimationFrame||(($e=S.requestAnimationFrame)||Pt)(St)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),de=x=null},S.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Z),n.__h=n.__h.filter(function(s){return!s.__||ue(s)})}catch(s){e.some(function(o){o.__h&&(o.__h=[])}),e=[],S.__e(s,n.__v)}}),Re&&Re(t,e)},S.unmount=function(t){Ne&&Ne(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(s){try{Z(s)}catch(o){e=o}}),n.__H=void 0,e&&S.__e(e,n.__v))};var We=typeof requestAnimationFrame=="function";function Pt(t){var e,n=function(){clearTimeout(s),We&&cancelAnimationFrame(e),setTimeout(t)},s=setTimeout(n,35);We&&(e=requestAnimationFrame(n))}function Z(t){var e=x,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),x=e}function ue(t){var e=x;t.__c=t.__(),x=e}function De(t,e){return!t||t.length!==e.length||e.some(function(n,s){return n!==t[s]})}function ze(t,e){return typeof e=="function"?e(t):e}function je(t,e){let n=e==="dark",s={bg:n?"#1f2937":"#ffffff",bgSecondary:n?"#374151":"#f3f4f6",text:n?"#f9fafb":"#111827",textSecondary:n?"#9ca3af":"#6b7280",border:n?"#4b5563":"#e5e7eb",messageBg:n?"#374151":"#f3f4f6"};return`
|
|
2
2
|
#pocketping-container {
|
|
3
3
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
|
4
4
|
font-size: 14px;
|
|
@@ -354,7 +354,7 @@
|
|
|
354
354
|
.pp-footer a:hover {
|
|
355
355
|
text-decoration: underline;
|
|
356
356
|
}
|
|
357
|
-
`}var St=0;function u(t,e,n,s,o,i){e||(e={});var a,l,p=e;if("ref"in p)for(l in p={},e)l=="ref"?a=e[l]:p[l]=e[l];var c={type:t,props:p,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--St,__i:-1,__u:0,__source:o,__self:i};if(typeof t=="function"&&(a=t.defaultProps))for(l in a)p[l]===void 0&&(p[l]=a[l]);return y.vnode&&y.vnode(c),c}function qe({client:t,config:e}){let[n,s]=M(!1),[o,i]=M([]),[a,l]=M(""),[p,c]=M(!1),[g,r]=M(!1),[d,_]=M(!1),[x,E]=M(0),[h,v]=M(e),m=_e(null),C=_e(null);O(()=>{let f=t.on("openChange",s),w=t.on("message",()=>{i([...t.getMessages()])}),U=t.on("typing",ee=>{c(ee.isTyping)}),at=t.on("presence",ee=>{r(ee.online)}),ct=t.on("connect",()=>{_(!0),i(t.getMessages()),r(t.getSession()?.operatorOnline??!1),v(t.getConfig())}),lt=t.on("configUpdate",()=>{v(t.getConfig())});return t.isConnected()&&(_(!0),i(t.getMessages()),r(t.getSession()?.operatorOnline??!1),v(t.getConfig())),()=>{f(),w(),U(),at(),ct(),lt()}},[t]),O(()=>{n&&m.current?.scrollIntoView({behavior:"smooth"})},[o,n]),O(()=>{n&&(setTimeout(()=>{m.current?.scrollIntoView({behavior:"auto"})},50),C.current?.focus(),E(0))},[n]),O(()=>{if(!n&&o.length>0){let f=o.filter(w=>w.sender!=="visitor"&&w.status!=="read").length;E(f)}},[o,n]);let S=Fe(()=>{if(!n||!d)return;let f=o.filter(w=>w.sender!=="visitor"&&w.status!=="read");if(f.length>0){let w=f.map(U=>U.id);t.sendReadStatus(w,"read")}},[n,d,o,t]);if(O(()=>{if(!n||!d)return;let f=setTimeout(()=>{S()},1e3);return()=>clearTimeout(f)},[n,d,o,S]),O(()=>{let f=()=>{document.visibilityState==="visible"&&n&&S()};return document.addEventListener("visibilitychange",f),()=>document.removeEventListener("visibilitychange",f)},[n,S]),O(()=>{let f=t.on("read",()=>{i([...t.getMessages()])});return()=>f()},[t]),!Ct(h))return null;let H=async f=>{if(f.preventDefault(),!a.trim())return;let w=a;l("");try{await t.sendMessage(w)}catch(U){console.error("[PocketPing] Failed to send message:",U)}},j=f=>{let w=f.target;l(w.value),t.sendTyping(!0)},R=h.position??"bottom-right",$=It(h.theme??"auto"),V=h.primaryColor??"#6366f1";return u(I,{children:[u("style",{children:je(V,$)}),u("button",{class:`pp-toggle pp-${R}`,onClick:()=>t.toggleOpen(),"aria-label":n?"Close chat":"Open chat",children:[n?u(Be,{}):u(Mt,{}),!n&&x>0&&u("span",{class:"pp-unread-badge",children:x>9?"9+":x}),!n&&x===0&&g&&u("span",{class:"pp-online-dot"})]}),n&&u("div",{class:`pp-window pp-${R} pp-theme-${$}`,children:[u("div",{class:"pp-header",children:[u("div",{class:"pp-header-info",children:[h.operatorAvatar&&u("img",{src:h.operatorAvatar,alt:"",class:"pp-avatar"}),u("div",{children:[u("div",{class:"pp-header-title",children:h.operatorName??"Support"}),u("div",{class:"pp-header-status",children:g?u(I,{children:[u("span",{class:"pp-status-dot pp-online"})," Online"]}):u(I,{children:[u("span",{class:"pp-status-dot"})," Away"]})})]})]}),u("button",{class:"pp-close-btn",onClick:()=>t.setOpen(!1),"aria-label":"Close chat",children:u(Be,{})})]}),u("div",{class:"pp-messages",children:[h.welcomeMessage&&o.length===0&&u("div",{class:"pp-welcome",children:h.welcomeMessage}),o.map(f=>u("div",{class:`pp-message pp-message-${f.sender}`,children:[u("div",{class:"pp-message-content",children:f.content}),u("div",{class:"pp-message-time",children:[Tt(f.timestamp),f.sender==="ai"&&u("span",{class:"pp-ai-badge",children:"AI"}),f.sender==="visitor"&&u("span",{class:`pp-status pp-status-${f.status??"sent"}`,children:u(Ot,{status:f.status})})]})]},f.id)),p&&u("div",{class:"pp-message pp-message-operator pp-typing",children:[u("span",{}),u("span",{}),u("span",{})]}),u("div",{ref:m})]}),u("form",{class:"pp-input-form",onSubmit:H,children:[u("input",{ref:C,type:"text",class:"pp-input",placeholder:h.placeholder??"Type a message...",value:a,onInput:j,disabled:!d}),u("button",{type:"submit",class:"pp-send-btn",disabled:!a.trim()||!d,"aria-label":"Send message",children:u($t,{})})]}),u("div",{class:"pp-footer",children:["Powered by ",u("a",{href:"https://pocketping.io",target:"_blank",rel:"noopener",children:"PocketPing"})]})]})]})}function Ct(t){let e=window.location.pathname;return t.hideOnPages?.some(n=>new RegExp(n).test(e))?!1:t.showOnPages?.length?t.showOnPages.some(n=>new RegExp(n).test(e)):!0}function It(t){return t==="auto"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":t}function Tt(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Mt(){return u("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:u("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Be(){return u("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[u("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function $t(){return u("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[u("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),u("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Ot({status:t}){return!t||t==="sending"||t==="sent"?u("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check",children:u("polyline",{points:"3 8 7 12 13 4"})}):t==="delivered"?u("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double",children:[u("polyline",{points:"1 8 5 12 11 4"}),u("polyline",{points:"7 8 11 12 17 4"})]}):t==="read"?u("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double pp-check-read",children:[u("polyline",{points:"1 8 5 12 11 4"}),u("polyline",{points:"7 8 11 12 17 4"})]}):null}var K="0.3.6";var Q=class{constructor(e){this.session=null;this.ws=null;this.isOpen=!1;this.listeners=new Map;this.customEventHandlers=new Map;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.reconnectTimeout=null;this.pollingTimeout=null;this.pollingFailures=0;this.maxPollingFailures=10;this.trackedElementCleanups=[];this.currentTrackedElements=[];this.inspectorMode=!1;this.inspectorCleanup=null;this.config=e}async connect(){let e=this.getOrCreateVisitorId(),n=this.getStoredSessionId(),s=this.getStoredIdentity(),i=new URLSearchParams(window.location.search).get("pp_inspector"),a=await this.fetch("/connect",{method:"POST",body:JSON.stringify({visitorId:e,sessionId:n,inspectorToken:i||void 0,metadata:{url:window.location.href,referrer:document.referrer||void 0,pageTitle:document.title||void 0,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,screenResolution:`${window.screen.width}x${window.screen.height}`},identity:s||void 0})});return this.session={sessionId:a.sessionId,visitorId:a.visitorId,operatorOnline:a.operatorOnline??!1,messages:a.messages??[],identity:a.identity||s||void 0},a.operatorName&&(this.config.operatorName=a.operatorName),a.operatorAvatar&&(this.config.operatorAvatar=a.operatorAvatar),a.primaryColor&&(this.config.primaryColor=a.primaryColor),a.welcomeMessage&&(this.config.welcomeMessage=a.welcomeMessage),this.emit("configUpdate",{operatorName:this.config.operatorName,operatorAvatar:this.config.operatorAvatar,primaryColor:this.config.primaryColor,welcomeMessage:this.config.welcomeMessage}),this.storeSessionId(a.sessionId),this.connectWebSocket(),a.inspectorMode?this.enableInspectorMode():a.trackedElements?.length&&this.setupTrackedElements(a.trackedElements),this.emit("connect",this.session),this.config.onConnect?.(a.sessionId),this.session}disconnect(){this.ws?.close(),this.ws=null,this.session=null,this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.stopPolling(),this.cleanupTrackedElements(),this.disableInspectorMode()}async sendMessage(e){if(!this.session)throw new Error("Not connected");let n=`temp-${this.generateId()}`,s={id:n,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:new Date().toISOString(),status:"sending"};this.session.messages.push(s),this.emit("message",s);try{let o=await this.fetch("/message",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,content:e,sender:"visitor"})}),i=this.session.messages.findIndex(l=>l.id===n);i>=0&&(this.session.messages[i].id=o.messageId,this.session.messages[i].timestamp=o.timestamp,this.session.messages[i].status="sent",this.emit("message",this.session.messages[i]));let a=this.session.messages[i]||{id:o.messageId,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:o.timestamp,status:"sent"};return this.config.onMessage?.(a),a}catch(o){let i=this.session.messages.findIndex(a=>a.id===n);throw i>=0&&(this.session.messages.splice(i,1),this.emit("message",s)),o}}async fetchMessages(e){if(!this.session)throw new Error("Not connected");let n=new URLSearchParams({sessionId:this.session.sessionId});return e&&n.set("after",e),(await this.fetch(`/messages?${n}`,{method:"GET"})).messages}async sendTyping(e=!0){this.session&&await this.fetch("/typing",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,sender:"visitor",isTyping:e})})}async sendReadStatus(e,n){if(!(!this.session||e.length===0))try{await this.fetch("/read",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,messageIds:e,status:n})});for(let s of this.session.messages)e.includes(s.id)&&(s.status=n,n==="delivered"?s.deliveredAt=new Date().toISOString():n==="read"&&(s.readAt=new Date().toISOString()));this.emit("readStatusSent",{messageIds:e,status:n})}catch(s){console.error("[PocketPing] Failed to send read status:",s)}}async getPresence(){return this.fetch("/presence",{method:"GET"})}async identify(e){if(!e?.id)throw new Error("[PocketPing] identity.id is required");if(this.storeIdentity(e),this.session)try{await this.fetch("/identify",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,identity:e})}),this.session.identity=e,this.emit("identify",e)}catch(n){throw console.error("[PocketPing] Failed to identify:",n),n}}async reset(e){this.clearIdentity(),this.session&&(this.session.identity=void 0),e?.newSession&&(localStorage.removeItem("pocketping_session_id"),localStorage.removeItem("pocketping_visitor_id"),this.disconnect(),await this.connect()),this.emit("reset",null)}getIdentity(){return this.session?.identity||this.getStoredIdentity()}getSession(){return this.session}getMessages(){return this.session?.messages??[]}isConnected(){return this.session!==null}isWidgetOpen(){return this.isOpen}getConfig(){return this.config}setOpen(e){this.isOpen=e,this.emit("openChange",e),e?this.config.onOpen?.():this.config.onClose?.()}toggleOpen(){this.setOpen(!this.isOpen)}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>{this.listeners.get(e)?.delete(n)}}emit(e,n){this.listeners.get(e)?.forEach(s=>s(n))}trigger(e,n,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[PocketPing] Cannot trigger event: WebSocket not connected");return}let o={name:e,data:n,timestamp:new Date().toISOString()};this.ws.send(JSON.stringify({type:"event",data:o})),this.emit(`event:${e}`,o),s?.widgetMessage&&(this.setOpen(!0),this.emit("triggerMessage",{message:s.widgetMessage,eventName:e}))}onEvent(e,n){return this.customEventHandlers.has(e)||this.customEventHandlers.set(e,new Set),this.customEventHandlers.get(e).add(n),()=>{this.customEventHandlers.get(e)?.delete(n)}}offEvent(e,n){this.customEventHandlers.get(e)?.delete(n)}emitCustomEvent(e){let n=this.customEventHandlers.get(e.name);n&&n.forEach(s=>s(e.data,e)),this.emit("event",e),this.emit(`event:${e.name}`,e)}setupTrackedElements(e){this.cleanupTrackedElements(),this.currentTrackedElements=e;for(let n of e){let s=n.event||"click",o=a=>{let l={...n.data,selector:n.selector,elementText:a.target?.textContent?.trim().slice(0,100),url:window.location.href};this.trigger(n.name,l,{widgetMessage:n.widgetMessage})},i=a=>{a.target?.closest(n.selector)&&o(a)};document.addEventListener(s,i,!0),this.trackedElementCleanups.push(()=>{document.removeEventListener(s,i,!0)})}e.length>0&&console.info(`[PocketPing] Tracking ${e.length} element(s)`)}cleanupTrackedElements(){for(let e of this.trackedElementCleanups)e();this.trackedElementCleanups=[],this.currentTrackedElements=[]}getTrackedElements(){return[...this.currentTrackedElements]}enableInspectorMode(){if(this.inspectorMode)return;this.inspectorMode=!0,console.info("[PocketPing] \u{1F50D} Inspector mode active - click on any element to select it");let e=document.createElement("div");e.id="pp-inspector-overlay",e.innerHTML=`
|
|
357
|
+
`}var Et=0;function u(t,e,n,s,o,i){e||(e={});var a,l,p=e;if("ref"in p)for(l in p={},e)l=="ref"?a=e[l]:p[l]=e[l];var c={type:t,props:p,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Et,__i:-1,__u:0,__source:o,__self:i};if(typeof t=="function"&&(a=t.defaultProps))for(l in a)p[l]===void 0&&(p[l]=a[l]);return y.vnode&&y.vnode(c),c}function qe({client:t,config:e}){let[n,s]=M(!1),[o,i]=M([]),[a,l]=M(""),[p,c]=M(!1),[g,r]=M(!1),[d,h]=M(!1),[k,P]=M(0),[f,v]=M(e),m=he(null),C=he(null);O(()=>{let _=t.on("openChange",s),w=t.on("message",()=>{i([...t.getMessages()])}),V=t.on("typing",ee=>{c(ee.isTyping)}),at=t.on("presence",ee=>{r(ee.online)}),ct=t.on("connect",()=>{h(!0),i(t.getMessages()),r(t.getSession()?.operatorOnline??!1),v(t.getConfig())}),lt=t.on("configUpdate",()=>{v(t.getConfig())});return t.isConnected()&&(h(!0),i(t.getMessages()),r(t.getSession()?.operatorOnline??!1),v(t.getConfig())),()=>{_(),w(),V(),at(),ct(),lt()}},[t]),O(()=>{n&&m.current?.scrollIntoView({behavior:"smooth"})},[o,n]),O(()=>{n&&(setTimeout(()=>{m.current?.scrollIntoView({behavior:"auto"})},50),C.current?.focus(),P(0))},[n]),O(()=>{if(!n&&o.length>0){let _=o.filter(w=>w.sender!=="visitor"&&w.status!=="read").length;P(_)}},[o,n]);let E=Ue(()=>{if(!n||!d)return;let _=o.filter(w=>w.sender!=="visitor"&&w.status!=="read");if(_.length>0){let w=_.map(V=>V.id);t.sendReadStatus(w,"read")}},[n,d,o,t]);if(O(()=>{if(!n||!d)return;let _=setTimeout(()=>{E()},1e3);return()=>clearTimeout(_)},[n,d,o,E]),O(()=>{let _=()=>{document.visibilityState==="visible"&&n&&E()};return document.addEventListener("visibilitychange",_),()=>document.removeEventListener("visibilitychange",_)},[n,E]),O(()=>{let _=t.on("read",()=>{i([...t.getMessages()])});return()=>_()},[t]),!Ct(f))return null;let H=async _=>{if(_.preventDefault(),!a.trim())return;let w=a;l("");try{await t.sendMessage(w)}catch(V){console.error("[PocketPing] Failed to send message:",V)}},j=_=>{let w=_.target;l(w.value),t.sendTyping(!0)},R=f.position??"bottom-right",$=It(f.theme??"auto"),F=f.primaryColor??"#6366f1";return u(I,{children:[u("style",{children:je(F,$)}),u("button",{class:`pp-toggle pp-${R}`,onClick:()=>t.toggleOpen(),"aria-label":n?"Close chat":"Open chat",children:[n?u(Be,{}):u(Mt,{}),!n&&k>0&&u("span",{class:"pp-unread-badge",children:k>9?"9+":k}),!n&&k===0&&g&&u("span",{class:"pp-online-dot"})]}),n&&u("div",{class:`pp-window pp-${R} pp-theme-${$}`,children:[u("div",{class:"pp-header",children:[u("div",{class:"pp-header-info",children:[f.operatorAvatar&&u("img",{src:f.operatorAvatar,alt:"",class:"pp-avatar"}),u("div",{children:[u("div",{class:"pp-header-title",children:f.operatorName??"Support"}),u("div",{class:"pp-header-status",children:g?u(I,{children:[u("span",{class:"pp-status-dot pp-online"})," Online"]}):u(I,{children:[u("span",{class:"pp-status-dot"})," Away"]})})]})]}),u("button",{class:"pp-close-btn",onClick:()=>t.setOpen(!1),"aria-label":"Close chat",children:u(Be,{})})]}),u("div",{class:"pp-messages",children:[f.welcomeMessage&&o.length===0&&u("div",{class:"pp-welcome",children:f.welcomeMessage}),o.map(_=>u("div",{class:`pp-message pp-message-${_.sender}`,children:[u("div",{class:"pp-message-content",children:_.content}),u("div",{class:"pp-message-time",children:[Tt(_.timestamp),_.sender==="ai"&&u("span",{class:"pp-ai-badge",children:"AI"}),_.sender==="visitor"&&u("span",{class:`pp-status pp-status-${_.status??"sent"}`,children:u(Ot,{status:_.status})})]})]},_.id)),p&&u("div",{class:"pp-message pp-message-operator pp-typing",children:[u("span",{}),u("span",{}),u("span",{})]}),u("div",{ref:m})]}),u("form",{class:"pp-input-form",onSubmit:H,children:[u("input",{ref:C,type:"text",class:"pp-input",placeholder:f.placeholder??"Type a message...",value:a,onInput:j,disabled:!d}),u("button",{type:"submit",class:"pp-send-btn",disabled:!a.trim()||!d,"aria-label":"Send message",children:u($t,{})})]}),u("div",{class:"pp-footer",children:["Powered by ",u("a",{href:"https://pocketping.io",target:"_blank",rel:"noopener",children:"PocketPing"})]})]})]})}function Ct(t){let e=window.location.pathname;return t.hideOnPages?.some(n=>new RegExp(n).test(e))?!1:t.showOnPages?.length?t.showOnPages.some(n=>new RegExp(n).test(e)):!0}function It(t){return t==="auto"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":t}function Tt(t){return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function Mt(){return u("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:u("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Be(){return u("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[u("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function $t(){return u("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2",children:[u("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),u("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Ot({status:t}){return!t||t==="sending"||t==="sent"?u("svg",{viewBox:"0 0 16 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check",children:u("polyline",{points:"3 8 7 12 13 4"})}):t==="delivered"?u("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double",children:[u("polyline",{points:"1 8 5 12 11 4"}),u("polyline",{points:"7 8 11 12 17 4"})]}):t==="read"?u("svg",{viewBox:"0 0 20 16",fill:"none",stroke:"currentColor","stroke-width":"2",class:"pp-check-double pp-check-read",children:[u("polyline",{points:"1 8 5 12 11 4"}),u("polyline",{points:"7 8 11 12 17 4"})]}):null}var K="0.3.6";var Q=class{constructor(e){this.session=null;this.ws=null;this.sse=null;this.isOpen=!1;this.listeners=new Map;this.customEventHandlers=new Map;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.reconnectTimeout=null;this.pollingTimeout=null;this.pollingFailures=0;this.maxPollingFailures=10;this.wsConnectedAt=0;this.quickFailureThreshold=2e3;this.connectionMode="none";this.trackedElementCleanups=[];this.currentTrackedElements=[];this.inspectorMode=!1;this.inspectorCleanup=null;this.config=e}async connect(){let e=this.getOrCreateVisitorId(),n=this.getStoredSessionId(),s=this.getStoredIdentity(),i=new URLSearchParams(window.location.search).get("pp_inspector"),a=await this.fetch("/connect",{method:"POST",body:JSON.stringify({visitorId:e,sessionId:n,inspectorToken:i||void 0,metadata:{url:window.location.href,referrer:document.referrer||void 0,pageTitle:document.title||void 0,userAgent:navigator.userAgent,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,screenResolution:`${window.screen.width}x${window.screen.height}`},identity:s||void 0})});return this.session={sessionId:a.sessionId,visitorId:a.visitorId,operatorOnline:a.operatorOnline??!1,messages:a.messages??[],identity:a.identity||s||void 0},a.operatorName&&(this.config.operatorName=a.operatorName),a.operatorAvatar&&(this.config.operatorAvatar=a.operatorAvatar),a.primaryColor&&(this.config.primaryColor=a.primaryColor),a.welcomeMessage&&(this.config.welcomeMessage=a.welcomeMessage),this.emit("configUpdate",{operatorName:this.config.operatorName,operatorAvatar:this.config.operatorAvatar,primaryColor:this.config.primaryColor,welcomeMessage:this.config.welcomeMessage}),this.storeSessionId(a.sessionId),this.connectRealtime(),a.inspectorMode?this.enableInspectorMode():a.trackedElements?.length&&this.setupTrackedElements(a.trackedElements),this.emit("connect",this.session),this.config.onConnect?.(a.sessionId),this.session}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.onmessage=null,this.ws.onerror=null,this.ws.onopen=null,this.ws.close(),this.ws=null),this.sse&&(this.sse.close(),this.sse=null),this.session=null,this.connectionMode="none",this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.stopPolling(),this.cleanupTrackedElements(),this.disableInspectorMode()}async sendMessage(e){if(!this.session)throw new Error("Not connected");let n=`temp-${this.generateId()}`,s={id:n,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:new Date().toISOString(),status:"sending"};this.session.messages.push(s),this.emit("message",s);try{let o=await this.fetch("/message",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,content:e,sender:"visitor"})}),i=this.session.messages.findIndex(l=>l.id===n);i>=0&&(this.session.messages[i].id=o.messageId,this.session.messages[i].timestamp=o.timestamp,this.session.messages[i].status="sent",this.emit("message",this.session.messages[i]));let a=this.session.messages[i]||{id:o.messageId,sessionId:this.session.sessionId,content:e,sender:"visitor",timestamp:o.timestamp,status:"sent"};return this.config.onMessage?.(a),a}catch(o){let i=this.session.messages.findIndex(a=>a.id===n);throw i>=0&&(this.session.messages.splice(i,1),this.emit("message",s)),o}}async fetchMessages(e){if(!this.session)throw new Error("Not connected");let n=new URLSearchParams({sessionId:this.session.sessionId});return e&&n.set("after",e),(await this.fetch(`/messages?${n}`,{method:"GET"})).messages}async sendTyping(e=!0){this.session&&await this.fetch("/typing",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,sender:"visitor",isTyping:e})})}async sendReadStatus(e,n){if(!(!this.session||e.length===0))try{await this.fetch("/read",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,messageIds:e,status:n})});for(let s of this.session.messages)e.includes(s.id)&&(s.status=n,n==="delivered"?s.deliveredAt=new Date().toISOString():n==="read"&&(s.readAt=new Date().toISOString()));this.emit("readStatusSent",{messageIds:e,status:n})}catch(s){console.error("[PocketPing] Failed to send read status:",s)}}async getPresence(){return this.fetch("/presence",{method:"GET"})}async identify(e){if(!e?.id)throw new Error("[PocketPing] identity.id is required");if(this.storeIdentity(e),this.session)try{await this.fetch("/identify",{method:"POST",body:JSON.stringify({sessionId:this.session.sessionId,identity:e})}),this.session.identity=e,this.emit("identify",e)}catch(n){throw console.error("[PocketPing] Failed to identify:",n),n}}async reset(e){this.clearIdentity(),this.session&&(this.session.identity=void 0),e?.newSession&&(localStorage.removeItem("pocketping_session_id"),localStorage.removeItem("pocketping_visitor_id"),this.disconnect(),await this.connect()),this.emit("reset",null)}getIdentity(){return this.session?.identity||this.getStoredIdentity()}getSession(){return this.session}getMessages(){return this.session?.messages??[]}isConnected(){return this.session!==null}isWidgetOpen(){return this.isOpen}getConfig(){return this.config}setOpen(e){this.isOpen=e,this.emit("openChange",e),e?this.config.onOpen?.():this.config.onClose?.()}toggleOpen(){this.setOpen(!this.isOpen)}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),()=>{this.listeners.get(e)?.delete(n)}}emit(e,n){this.listeners.get(e)?.forEach(s=>s(n))}trigger(e,n,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){console.warn("[PocketPing] Cannot trigger event: WebSocket not connected");return}let o={name:e,data:n,timestamp:new Date().toISOString()};this.ws.send(JSON.stringify({type:"event",data:o})),this.emit(`event:${e}`,o),s?.widgetMessage&&(this.setOpen(!0),this.emit("triggerMessage",{message:s.widgetMessage,eventName:e}))}onEvent(e,n){return this.customEventHandlers.has(e)||this.customEventHandlers.set(e,new Set),this.customEventHandlers.get(e).add(n),()=>{this.customEventHandlers.get(e)?.delete(n)}}offEvent(e,n){this.customEventHandlers.get(e)?.delete(n)}emitCustomEvent(e){let n=this.customEventHandlers.get(e.name);n&&n.forEach(s=>s(e.data,e)),this.emit("event",e),this.emit(`event:${e.name}`,e)}setupTrackedElements(e){this.cleanupTrackedElements(),this.currentTrackedElements=e;for(let n of e){let s=n.event||"click",o=a=>{let l={...n.data,selector:n.selector,elementText:a.target?.textContent?.trim().slice(0,100),url:window.location.href};this.trigger(n.name,l,{widgetMessage:n.widgetMessage})},i=a=>{a.target?.closest(n.selector)&&o(a)};document.addEventListener(s,i,!0),this.trackedElementCleanups.push(()=>{document.removeEventListener(s,i,!0)})}e.length>0&&console.info(`[PocketPing] Tracking ${e.length} element(s)`)}cleanupTrackedElements(){for(let e of this.trackedElementCleanups)e();this.trackedElementCleanups=[],this.currentTrackedElements=[]}getTrackedElements(){return[...this.currentTrackedElements]}enableInspectorMode(){if(this.inspectorMode)return;this.inspectorMode=!0,console.info("[PocketPing] \u{1F50D} Inspector mode active - click on any element to select it");let e=document.createElement("div");e.id="pp-inspector-overlay",e.innerHTML=`
|
|
358
358
|
<style>
|
|
359
359
|
#pp-inspector-overlay {
|
|
360
360
|
position: fixed;
|
|
@@ -437,9 +437,9 @@
|
|
|
437
437
|
<button id="pp-inspector-exit">Exit</button>
|
|
438
438
|
</div>
|
|
439
439
|
<div id="pp-inspector-tooltip"></div>
|
|
440
|
-
`,document.body.appendChild(e);let n=document.getElementById("pp-inspector-tooltip"),s=null,o=p=>{if(p.id&&!p.id.startsWith("pp-"))return`#${CSS.escape(p.id)}`;let c=Array.from(p.classList).filter(d=>!d.startsWith("pp-"));if(c.length>0){let d="."+c.map(
|
|
440
|
+
`,document.body.appendChild(e);let n=document.getElementById("pp-inspector-tooltip"),s=null,o=p=>{if(p.id&&!p.id.startsWith("pp-"))return`#${CSS.escape(p.id)}`;let c=Array.from(p.classList).filter(d=>!d.startsWith("pp-"));if(c.length>0){let d="."+c.map(h=>CSS.escape(h)).join(".");if(document.querySelectorAll(d).length===1)return d}for(let d of Array.from(p.attributes))if(d.name.startsWith("data-")&&d.value){let h=`[${d.name}="${CSS.escape(d.value)}"]`;if(document.querySelectorAll(h).length===1)return h}let g=[],r=p;for(;r&&r!==document.body;){let d=r.tagName.toLowerCase();if(r.id&&!r.id.startsWith("pp-")){d=`#${CSS.escape(r.id)}`,g.unshift(d);break}let h=r.parentElement;if(h){let k=r.tagName,P=Array.from(h.children).filter(f=>f.tagName===k);if(P.length>1){let f=P.indexOf(r)+1;d+=`:nth-of-type(${f})`}}g.unshift(d),r=h}return g.join(" > ")},i=p=>{let c=p.target;if(c.closest("#pp-inspector-overlay")||c.closest("#pocketping-widget"))return;s&&s.classList.remove("pp-inspector-highlight"),c.classList.add("pp-inspector-highlight"),s=c;let g=o(c);n.textContent=g,n.style.display="block",n.style.left=`${p.clientX+15}px`,n.style.top=`${p.clientY+15}px`;let r=n.getBoundingClientRect();r.right>window.innerWidth&&(n.style.left=`${p.clientX-r.width-15}px`),r.bottom>window.innerHeight&&(n.style.top=`${p.clientY-r.height-15}px`)},a=p=>{let c=p.target;c.closest("#pp-inspector-overlay")||(c.classList.remove("pp-inspector-highlight"),n.style.display="none")},l=p=>{let c=p.target;if(c.id==="pp-inspector-exit"){this.disableInspectorMode();return}if(c.closest("#pp-inspector-overlay")||c.closest("#pocketping-widget"))return;p.preventDefault(),p.stopPropagation();let g=o(c);this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"inspector_select",data:{selector:g,tagName:c.tagName.toLowerCase(),text:c.textContent?.trim().slice(0,50)||"",url:window.location.href}})),this.emit("inspectorSelect",{selector:g,element:c}),c.classList.remove("pp-inspector-highlight"),c.classList.add("pp-inspector-highlight"),setTimeout(()=>{c.classList.remove("pp-inspector-highlight")},500);let r=document.getElementById("pp-inspector-banner");if(r){let d=r.innerHTML;r.innerHTML=`
|
|
441
441
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
442
442
|
<polyline points="20 6 9 17 4 12"/>
|
|
443
443
|
</svg>
|
|
444
444
|
<span>Selector captured: <code style="background:rgba(255,255,255,0.2);padding:2px 6px;border-radius:4px;font-family:monospace;">${g}</code></span>
|
|
445
|
-
`,setTimeout(()=>{r&&this.inspectorMode&&(r.innerHTML=d,document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()}))},2e3)}console.info(`[PocketPing] \u{1F4CC} Selector captured: ${g}`)};document.addEventListener("mouseover",i,!0),document.addEventListener("mouseout",a,!0),document.addEventListener("click",l,!0),this.inspectorCleanup=()=>{document.removeEventListener("mouseover",i,!0),document.removeEventListener("mouseout",a,!0),document.removeEventListener("click",l,!0),e.remove(),s&&s.classList.remove("pp-inspector-highlight")},document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()})}disableInspectorMode(){this.inspectorMode&&(this.inspectorMode=!1,this.inspectorCleanup&&(this.inspectorCleanup(),this.inspectorCleanup=null),console.info("[PocketPing] Inspector mode disabled"),this.emit("inspectorDisabled",null))}isInspectorModeActive(){return this.inspectorMode}connectWebSocket(){if(!this.session)return;let e=this.config.endpoint.replace(/^http/,"ws").replace(/\/$/,"")+`/stream?sessionId=${this.session.sessionId}`;try{this.ws=new WebSocket(e),this.ws.onopen=()=>{this.reconnectAttempts=0,this.emit("wsConnected",null)},this.ws.onmessage=n=>{try{let s=JSON.parse(n.data);this.handleWebSocketEvent(s)}catch(s){console.error("[PocketPing] Failed to parse WS message:",s)}},this.ws.onclose=()=>{this.emit("wsDisconnected",null),this.scheduleReconnect()},this.ws.onerror=n=>{console.error("[PocketPing] WebSocket error:",n)}}catch{console.warn("[PocketPing] WebSocket unavailable, using polling"),this.startPolling()}}handleWebSocketEvent(e){switch(e.type){case"message":let n=e.data;if(this.session){let p=this.session.messages.findIndex(c=>c.id===n.id);if(p<0&&n.sender==="visitor"&&(p=this.session.messages.findIndex(c=>c.id.startsWith("temp-")&&c.content===n.content&&c.sender==="visitor"),p>=0&&(this.session.messages[p].id=n.id)),p<0&&n.sender!=="visitor"){let c=new Date(n.timestamp).getTime();p=this.session.messages.findIndex(g=>g.sender===n.sender&&g.content===n.content&&Math.abs(new Date(g.timestamp).getTime()-c)<2e3)}if(p>=0){let c=this.session.messages[p];n.status&&n.status!==c.status&&(c.status=n.status,n.deliveredAt&&(c.deliveredAt=n.deliveredAt),n.readAt&&(c.readAt=n.readAt),this.emit("read",{messageIds:[n.id],status:n.status}))}else this.session.messages.push(n),this.emit("message",n),this.config.onMessage?.(n)}n.sender!=="visitor"&&this.emit("typing",{isTyping:!1});break;case"typing":let s=e.data;s.sender!=="visitor"&&this.emit("typing",{isTyping:s.isTyping});break;case"presence":this.session&&(this.session.operatorOnline=e.data.online),this.emit("presence",e.data);break;case"ai_takeover":this.emit("aiTakeover",e.data);break;case"read":let o=e.data;if(this.session)for(let p of this.session.messages)o.messageIds.includes(p.id)&&(p.status=o.status,o.deliveredAt&&(p.deliveredAt=o.deliveredAt),o.readAt&&(p.readAt=o.readAt));this.emit("read",o);break;case"event":let i=e.data;this.emitCustomEvent(i);break;case"version_warning":let a=e.data;this.handleVersionWarning(a);break;case"config_update":let l=e.data;l.trackedElements&&(this.setupTrackedElements(l.trackedElements),this.emit("configUpdate",l));break}}handleVersionWarning(e){let n="[PocketPing]",s=e.upgradeUrl?` Upgrade: ${e.upgradeUrl}`:" Update your widget to the latest version.";switch(e.severity){case"error":console.error(`${n} \u{1F6A8} VERSION ERROR: ${e.message}${s}`),console.error(`${n} Current: ${e.currentVersion}, Required: ${e.minVersion||"unknown"}`);break;case"warning":console.warn(`${n} \u26A0\uFE0F VERSION WARNING: ${e.message}${s}`),console.warn(`${n} Current: ${e.currentVersion}, Latest: ${e.latestVersion||"unknown"}`);break;case"info":console.info(`${n} \u2139\uFE0F ${e.message}`);break}this.emit("versionWarning",e),this.config.onVersionWarning?.(e),e.canContinue||(console.error(`${n} Widget is incompatible with backend. Please update immediately.`),this.disconnect())}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.warn("[PocketPing] Max reconnect attempts reached, switching to polling"),this.startPolling();return}let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.connectWebSocket()},e)}startPolling(){let e=async()=>{if(this.session){try{let n=this.session.messages[this.session.messages.length-1]?.id,s=await this.fetchMessages(n);this.pollingFailures=0;for(let o of s)this.session.messages.find(i=>i.id===o.id)||(this.session.messages.push(o),this.emit("message",o),this.config.onMessage?.(o))}catch{if(this.pollingFailures++,(this.pollingFailures<=3||this.pollingFailures%3===0)&&console.warn(`[PocketPing] Polling failed (${this.pollingFailures}/${this.maxPollingFailures})`),this.pollingFailures>=this.maxPollingFailures){console.error("[PocketPing] Polling disabled after too many failures. Real-time updates unavailable."),this.emit("pollingDisabled",{failures:this.pollingFailures});return}}if(this.session){let n=this.pollingFailures>0?Math.min(3e3*Math.pow(2,this.pollingFailures-1),3e4):3e3;this.pollingTimeout=setTimeout(e,n)}}};e()}stopPolling(){this.pollingTimeout&&(clearTimeout(this.pollingTimeout),this.pollingTimeout=null),this.pollingFailures=0}async fetch(e,n){let s=this.config.endpoint.replace(/\/$/,"")+e,o=await fetch(s,{...n,headers:{"Content-Type":"application/json","X-PocketPing-Version":K,...n.headers}});if(this.checkVersionHeaders(o),!o.ok){let i=await o.text();throw new Error(`PocketPing API error: ${o.status} ${i}`)}return o.json()}checkVersionHeaders(e){let n=e.headers.get("X-PocketPing-Version-Status"),s=e.headers.get("X-PocketPing-Min-Version"),o=e.headers.get("X-PocketPing-Latest-Version"),i=e.headers.get("X-PocketPing-Version-Message");if(!n||n==="ok")return;let a="info",l=!0;n==="deprecated"?a="warning":n==="unsupported"?(a="error",l=!1):n==="outdated"&&(a="info");let p={severity:a,message:i||`Widget version ${K} is ${n}`,currentVersion:K,minVersion:s||void 0,latestVersion:o||void 0,canContinue:l,upgradeUrl:"https://docs.pocketping.io/widget/installation"};this.handleVersionWarning(p)}getOrCreateVisitorId(){let e="pocketping_visitor_id",n=localStorage.getItem(e);return n||(n=this.generateId(),localStorage.setItem(e,n)),n}getStoredSessionId(){return localStorage.getItem("pocketping_session_id")}storeSessionId(e){localStorage.setItem("pocketping_session_id",e)}getStoredIdentity(){try{let e=localStorage.getItem("pocketping_user_identity");return e?JSON.parse(e):null}catch{return null}}storeIdentity(e){localStorage.setItem("pocketping_user_identity",JSON.stringify(e))}clearIdentity(){localStorage.removeItem("pocketping_user_identity")}generateId(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}};var b=null,A=null,At="https://app.pocketping.io/api/widget";function fe(t){if(b)return console.warn("[PocketPing] Already initialized"),b;let e=t.endpoint;if(!e&&t.projectId&&(e=`${At}/${t.projectId}`),!e)throw new Error("[PocketPing] endpoint or projectId is required");let n={...t,endpoint:e};return b=new Q(n),A=document.createElement("div"),A.id="pocketping-container",document.body.appendChild(A),pe(ae(qe,{client:b,config:t}),A),b.connect().catch(s=>{console.error("[PocketPing] Failed to connect:",s)}),b}function Je(){A&&(pe(null,A),A.remove(),A=null),b&&(b.disconnect(),b=null)}function Xe(){b?.setOpen(!0)}function Ge(){b?.setOpen(!1)}function Ye(){b?.toggleOpen()}function Ze(t){if(!b)throw new Error("[PocketPing] Not initialized");return b.sendMessage(t)}function Ke(t,e,n){if(!b){console.warn("[PocketPing] Not initialized, cannot trigger event");return}b.trigger(t,e,n)}function Qe(t){if(!b){console.warn("[PocketPing] Not initialized, cannot setup tracked elements");return}b.setupTrackedElements(t)}function et(){return b?.getTrackedElements()||[]}function tt(t,e){return b?b.onEvent(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}function nt(t,e){b?.offEvent(t,e)}async function st(t){if(!b)throw new Error("[PocketPing] Not initialized");return b.identify(t)}async function ot(t){if(!b){console.warn("[PocketPing] Not initialized");return}return b.reset(t)}function it(){return b?.getIdentity()||null}function rt(t,e){return b?b.on(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}if(typeof document<"u"){let t=document.currentScript;if(t){let e=t.dataset.projectId,n=t.dataset.endpoint;(e||n)&&fe({projectId:e,endpoint:n,theme:t.dataset.theme||"auto",position:t.dataset.position||"bottom-right"})}}var Ht={init:fe,destroy:Je,open:Xe,close:Ge,toggle:Ye,sendMessage:Ze,trigger:Ke,onEvent:tt,offEvent:nt,on:rt,identify:st,reset:ot,getIdentity:it,setupTrackedElements:Qe,getTrackedElements:et};return ft(Rt);})();
|
|
445
|
+
`,setTimeout(()=>{r&&this.inspectorMode&&(r.innerHTML=d,document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()}))},2e3)}console.info(`[PocketPing] \u{1F4CC} Selector captured: ${g}`)};document.addEventListener("mouseover",i,!0),document.addEventListener("mouseout",a,!0),document.addEventListener("click",l,!0),this.inspectorCleanup=()=>{document.removeEventListener("mouseover",i,!0),document.removeEventListener("mouseout",a,!0),document.removeEventListener("click",l,!0),e.remove(),s&&s.classList.remove("pp-inspector-highlight")},document.getElementById("pp-inspector-exit")?.addEventListener("click",()=>{this.disableInspectorMode()})}disableInspectorMode(){this.inspectorMode&&(this.inspectorMode=!1,this.inspectorCleanup&&(this.inspectorCleanup(),this.inspectorCleanup=null),console.info("[PocketPing] Inspector mode disabled"),this.emit("inspectorDisabled",null))}isInspectorModeActive(){return this.inspectorMode}connectRealtime(){if(this.session){if(this.connectionMode==="polling"){this.startPolling();return}if(this.connectionMode==="sse"){this.connectSSE();return}this.connectWebSocket()}}connectWebSocket(){if(!this.session)return;let e=this.config.endpoint.replace(/^http/,"ws").replace(/\/$/,"")+`/stream?sessionId=${this.session.sessionId}`;try{this.ws=new WebSocket(e),this.wsConnectedAt=Date.now();let n=setTimeout(()=>{console.warn("[PocketPing] \u23F1\uFE0F WebSocket timeout - trying SSE"),this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onopen=null,this.ws.close(),this.ws=null,this.connectSSE())},5e3);this.ws.onopen=()=>{clearTimeout(n),this.connectionMode="ws",this.reconnectAttempts=0,this.wsConnectedAt=Date.now(),this.emit("wsConnected",null)},this.ws.onmessage=s=>{try{let o=JSON.parse(s.data);this.handleRealtimeEvent(o)}catch(o){console.error("[PocketPing] Failed to parse WS message:",o)}},this.ws.onclose=()=>{clearTimeout(n),this.emit("wsDisconnected",null),this.handleWsFailure()},this.ws.onerror=()=>{clearTimeout(n)}}catch{console.warn("[PocketPing] WebSocket unavailable - trying SSE"),this.connectSSE()}}connectSSE(){if(!this.session)return;let e=this.config.endpoint.replace(/\/$/,"")+`/stream?sessionId=${this.session.sessionId}`;try{this.sse=new EventSource(e);let n=setTimeout(()=>{console.warn("[PocketPing] \u23F1\uFE0F SSE timeout - falling back to polling"),this.sse&&this.sse.readyState!==EventSource.OPEN&&(this.sse.close(),this.sse=null,this.connectionMode="polling",this.startPolling())},5e3);this.sse.onopen=()=>{clearTimeout(n),this.connectionMode="sse",this.emit("sseConnected",null)},this.sse.addEventListener("message",s=>{try{let o=JSON.parse(s.data);this.handleRealtimeEvent(o)}catch(o){console.error("[PocketPing] Failed to parse SSE message:",o)}}),this.sse.addEventListener("connected",()=>{}),this.sse.onerror=()=>{clearTimeout(n),console.warn("[PocketPing] \u274C SSE error - falling back to polling"),this.sse&&(this.sse.close(),this.sse=null),this.connectionMode="polling",this.startPolling()}}catch{console.warn("[PocketPing] SSE unavailable - falling back to polling"),this.connectionMode="polling",this.startPolling()}}handleWsFailure(){if(Date.now()-this.wsConnectedAt<this.quickFailureThreshold){console.info("[PocketPing] WebSocket failed quickly - trying SSE"),this.connectSSE();return}this.scheduleReconnect()}handleRealtimeEvent(e){this.handleWebSocketEvent(e)}handleWebSocketEvent(e){switch(e.type){case"message":let n=e.data;if(this.session){let p=this.session.messages.findIndex(c=>c.id===n.id);if(p<0&&n.sender==="visitor"&&(p=this.session.messages.findIndex(c=>c.id.startsWith("temp-")&&c.content===n.content&&c.sender==="visitor"),p>=0&&(this.session.messages[p].id=n.id)),p<0&&n.sender!=="visitor"){let c=new Date(n.timestamp).getTime();p=this.session.messages.findIndex(g=>g.sender===n.sender&&g.content===n.content&&Math.abs(new Date(g.timestamp).getTime()-c)<2e3)}if(p>=0){let c=this.session.messages[p];n.status&&n.status!==c.status&&(c.status=n.status,n.deliveredAt&&(c.deliveredAt=n.deliveredAt),n.readAt&&(c.readAt=n.readAt),this.emit("read",{messageIds:[n.id],status:n.status}))}else this.session.messages.push(n),this.emit("message",n),this.config.onMessage?.(n)}n.sender!=="visitor"&&this.emit("typing",{isTyping:!1});break;case"typing":let s=e.data;s.sender!=="visitor"&&this.emit("typing",{isTyping:s.isTyping});break;case"presence":this.session&&(this.session.operatorOnline=e.data.online),this.emit("presence",e.data);break;case"ai_takeover":this.emit("aiTakeover",e.data);break;case"read":let o=e.data;if(this.session)for(let p of this.session.messages)o.messageIds.includes(p.id)&&(p.status=o.status,o.deliveredAt&&(p.deliveredAt=o.deliveredAt),o.readAt&&(p.readAt=o.readAt));this.emit("read",o);break;case"event":let i=e.data;this.emitCustomEvent(i);break;case"version_warning":let a=e.data;this.handleVersionWarning(a);break;case"config_update":let l=e.data;l.trackedElements&&(this.setupTrackedElements(l.trackedElements),this.emit("configUpdate",l));break}}handleVersionWarning(e){let n="[PocketPing]",s=e.upgradeUrl?` Upgrade: ${e.upgradeUrl}`:" Update your widget to the latest version.";switch(e.severity){case"error":console.error(`${n} \u{1F6A8} VERSION ERROR: ${e.message}${s}`),console.error(`${n} Current: ${e.currentVersion}, Required: ${e.minVersion||"unknown"}`);break;case"warning":console.warn(`${n} \u26A0\uFE0F VERSION WARNING: ${e.message}${s}`),console.warn(`${n} Current: ${e.currentVersion}, Latest: ${e.latestVersion||"unknown"}`);break;case"info":console.info(`${n} \u2139\uFE0F ${e.message}`);break}this.emit("versionWarning",e),this.config.onVersionWarning?.(e),e.canContinue||(console.error(`${n} Widget is incompatible with backend. Please update immediately.`),this.disconnect())}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.warn("[PocketPing] Max reconnect attempts reached, trying SSE"),this.connectSSE();return}let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.reconnectAttempts++,this.reconnectTimeout=setTimeout(()=>{this.connectWebSocket()},e)}startPolling(){let e=async()=>{if(this.session){try{let n=this.session.messages[this.session.messages.length-1]?.id,s=await this.fetchMessages(n);this.pollingFailures=0;for(let o of s)this.session.messages.find(i=>i.id===o.id)||(this.session.messages.push(o),this.emit("message",o),this.config.onMessage?.(o))}catch(n){if(this.pollingFailures++,console.error("[PocketPing] \u274C Polling error:",n),(this.pollingFailures<=3||this.pollingFailures%3===0)&&console.warn(`[PocketPing] Polling failed (${this.pollingFailures}/${this.maxPollingFailures})`),this.pollingFailures>=this.maxPollingFailures){console.error("[PocketPing] Polling disabled after too many failures. Real-time updates unavailable."),this.emit("pollingDisabled",{failures:this.pollingFailures});return}}if(this.session){let n=this.pollingFailures>0?Math.min(2e3*Math.pow(2,this.pollingFailures-1),3e4):2e3;this.pollingTimeout=setTimeout(e,n)}}};this.pollingTimeout=setTimeout(e,500)}stopPolling(){this.pollingTimeout&&(clearTimeout(this.pollingTimeout),this.pollingTimeout=null),this.pollingFailures=0}async fetch(e,n){let s=this.config.endpoint.replace(/\/$/,"")+e,o=await fetch(s,{...n,headers:{"Content-Type":"application/json","X-PocketPing-Version":K,...n.headers}});if(this.checkVersionHeaders(o),!o.ok){let i=await o.text();throw new Error(`PocketPing API error: ${o.status} ${i}`)}return o.json()}checkVersionHeaders(e){let n=e.headers.get("X-PocketPing-Version-Status"),s=e.headers.get("X-PocketPing-Min-Version"),o=e.headers.get("X-PocketPing-Latest-Version"),i=e.headers.get("X-PocketPing-Version-Message");if(!n||n==="ok")return;let a="info",l=!0;n==="deprecated"?a="warning":n==="unsupported"?(a="error",l=!1):n==="outdated"&&(a="info");let p={severity:a,message:i||`Widget version ${K} is ${n}`,currentVersion:K,minVersion:s||void 0,latestVersion:o||void 0,canContinue:l,upgradeUrl:"https://docs.pocketping.io/widget/installation"};this.handleVersionWarning(p)}getOrCreateVisitorId(){let e="pocketping_visitor_id",n=localStorage.getItem(e);return n||(n=this.generateId(),localStorage.setItem(e,n)),n}getStoredSessionId(){return localStorage.getItem("pocketping_session_id")}storeSessionId(e){localStorage.setItem("pocketping_session_id",e)}getStoredIdentity(){try{let e=localStorage.getItem("pocketping_user_identity");return e?JSON.parse(e):null}catch{return null}}storeIdentity(e){localStorage.setItem("pocketping_user_identity",JSON.stringify(e))}clearIdentity(){localStorage.removeItem("pocketping_user_identity")}generateId(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,11)}`}};var b=null,A=null,At="https://app.pocketping.io/api/widget";function _e(t){if(b)return console.warn("[PocketPing] Already initialized"),b;let e=t.endpoint;if(!e&&t.projectId&&(e=`${At}/${t.projectId}`),!e)throw new Error("[PocketPing] endpoint or projectId is required");let n={...t,endpoint:e};return b=new Q(n),A=document.createElement("div"),A.id="pocketping-container",document.body.appendChild(A),pe(ae(qe,{client:b,config:t}),A),b.connect().catch(s=>{console.error("[PocketPing] Failed to connect:",s)}),b}function Je(){A&&(pe(null,A),A.remove(),A=null),b&&(b.disconnect(),b=null)}function Xe(){b?.setOpen(!0)}function Ge(){b?.setOpen(!1)}function Ye(){b?.toggleOpen()}function Ze(t){if(!b)throw new Error("[PocketPing] Not initialized");return b.sendMessage(t)}function Ke(t,e,n){if(!b){console.warn("[PocketPing] Not initialized, cannot trigger event");return}b.trigger(t,e,n)}function Qe(t){if(!b){console.warn("[PocketPing] Not initialized, cannot setup tracked elements");return}b.setupTrackedElements(t)}function et(){return b?.getTrackedElements()||[]}function tt(t,e){return b?b.onEvent(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}function nt(t,e){b?.offEvent(t,e)}async function st(t){if(!b)throw new Error("[PocketPing] Not initialized");return b.identify(t)}async function ot(t){if(!b){console.warn("[PocketPing] Not initialized");return}return b.reset(t)}function it(){return b?.getIdentity()||null}function rt(t,e){return b?b.on(t,e):(console.warn("[PocketPing] Not initialized, cannot subscribe to event"),()=>{})}if(typeof document<"u"){let t=document.currentScript;if(t){let e=t.dataset.projectId,n=t.dataset.endpoint;(e||n)&&_e({projectId:e,endpoint:n,theme:t.dataset.theme||"auto",position:t.dataset.position||"bottom-right"})}}var Ht={init:_e,destroy:Je,open:Xe,close:Ge,toggle:Ye,sendMessage:Ze,trigger:Ke,onEvent:tt,offEvent:nt,on:rt,identify:st,reset:ot,getIdentity:it,setupTrackedElements:Qe,getTrackedElements:et};return _t(Rt);})();
|