@vuu-ui/vuu-data-remote 0.13.105 → 0.13.107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/cjs/ConnectionManager.js +23 -24
  2. package/cjs/ConnectionManager.js.map +1 -1
  3. package/cjs/DedicatedWorker.js +1 -6
  4. package/cjs/DedicatedWorker.js.map +1 -1
  5. package/cjs/LostConnectionHandler.js +80 -0
  6. package/cjs/LostConnectionHandler.js.map +1 -0
  7. package/cjs/VuuAuthProvider.js +87 -0
  8. package/cjs/VuuAuthProvider.js.map +1 -0
  9. package/cjs/VuuAuthenticator.js +50 -0
  10. package/cjs/VuuAuthenticator.js.map +1 -0
  11. package/cjs/WebSocketConnection.js +11 -17
  12. package/cjs/WebSocketConnection.js.map +1 -1
  13. package/cjs/authenticate.js +15 -0
  14. package/cjs/authenticate.js.map +1 -1
  15. package/cjs/index.js +9 -0
  16. package/cjs/index.js.map +1 -1
  17. package/cjs/inlined-worker.js +259 -343
  18. package/cjs/inlined-worker.js.map +1 -1
  19. package/esm/ConnectionManager.js +25 -26
  20. package/esm/ConnectionManager.js.map +1 -1
  21. package/esm/DedicatedWorker.js +1 -6
  22. package/esm/DedicatedWorker.js.map +1 -1
  23. package/esm/LostConnectionHandler.js +76 -0
  24. package/esm/LostConnectionHandler.js.map +1 -0
  25. package/esm/VuuAuthProvider.js +85 -0
  26. package/esm/VuuAuthProvider.js.map +1 -0
  27. package/esm/VuuAuthenticator.js +47 -0
  28. package/esm/VuuAuthenticator.js.map +1 -0
  29. package/esm/WebSocketConnection.js +11 -17
  30. package/esm/WebSocketConnection.js.map +1 -1
  31. package/esm/authenticate.js +15 -1
  32. package/esm/authenticate.js.map +1 -1
  33. package/esm/index.js +4 -1
  34. package/esm/index.js.map +1 -1
  35. package/esm/inlined-worker.js +259 -343
  36. package/esm/inlined-worker.js.map +1 -1
  37. package/package.json +7 -7
  38. package/types/ConnectionManager.d.ts +5 -6
  39. package/types/DedicatedWorker.d.ts +1 -2
  40. package/types/LostConnectionHandler.d.ts +28 -0
  41. package/types/VuuAuthProvider.d.ts +38 -0
  42. package/types/VuuAuthenticator.d.ts +21 -0
  43. package/types/WebSocketConnection.d.ts +19 -38
  44. package/types/authenticate.d.ts +4 -0
  45. package/types/index.d.ts +5 -2
  46. package/types/inlined-worker.d.ts +1 -1
  47. package/types/server-proxy/server-proxy.d.ts +2 -2
@@ -407,7 +407,18 @@ var MENU_RPC_TYPES = [
407
407
  "VIEW_PORT_MENU_ROW_RPC",
408
408
  "VIEW_PORT_MENU_CELL_RPC"
409
409
  ];
410
- var isSelectRequest = (message) => "type" in message && (message.type === "SELECT_ROW" || message.type === "DESELECT_ROW" || message.type === "SELECT_ROW_RANGE" || message.type === "SELECT_ALL" || message.type === "DESELECT_ALL");
410
+ var INVALID_SESSION = "Invalid session";
411
+ var SESSION_LIMIT_EXCEEDED = "User session limit exceeded";
412
+ var INVALID_TOKEN = "Invalid token";
413
+ var TOKEN_EXPIRED = "Token has expired";
414
+ var InvalidLoginMessages = [
415
+ INVALID_SESSION,
416
+ SESSION_LIMIT_EXCEEDED,
417
+ INVALID_TOKEN,
418
+ TOKEN_EXPIRED
419
+ ];
420
+ var isLoginErrorMessage = (message) => typeof message === "string" && InvalidLoginMessages.includes(message);
421
+ var isSelectRequest = (message) => message && typeof message === "object" && "type" in message && (message.type === "SELECT_ROW" || message.type === "DESELECT_ROW" || message.type === "SELECT_ROW_RANGE" || message.type === "SELECT_ALL" || message.type === "DESELECT_ALL");
411
422
  var isRpcServiceRequest = (message) => message.type === "RPC_REQUEST";
412
423
  var hasViewPortContext = (message) => message.context.type === "VIEWPORT_CONTEXT";
413
424
  var isVuuMenuRpcRequest = (message) => MENU_RPC_TYPES.includes(message["type"]);
@@ -1439,9 +1450,195 @@ var toClientRowTree = ({ rowIndex, rowKey, sel: isSelected, data, ts }, keys) =>
1439
1450
  ].concat(rest);
1440
1451
  };
1441
1452
 
1453
+ // src/WebSocketConnection.ts
1454
+ var { debug: debug3, debugEnabled: debugEnabled3, info: info2 } = logger("WebSocketConnection");
1455
+ var isLoginRejectedMessage = (message) => message !== null && "type" in message && message.type === "LOGIN_REJECTED";
1456
+ var DEFAULT_CONNECTION_TIMEOUT = 1e4;
1457
+ var parseWebSocketMessage = (message) => {
1458
+ try {
1459
+ return JSON.parse(message);
1460
+ } catch (e) {
1461
+ throw Error(\`Error parsing JSON response from server \${message}\`);
1462
+ }
1463
+ };
1464
+ var _callback, _confirmedOpen, _connectionPhase, _connectionStatus, _connectionTimeout, _deferredOpen, _protocols, _url, _ws;
1465
+ var WebSocketConnection = class extends EventEmitter {
1466
+ constructor({
1467
+ callback,
1468
+ connectionTimeout = DEFAULT_CONNECTION_TIMEOUT,
1469
+ protocols,
1470
+ url
1471
+ }) {
1472
+ super();
1473
+ __privateAdd(this, _callback);
1474
+ /**
1475
+ We are not confirmedOpen until we receive the first message from the
1476
+ server. If we get an unexpected close event before that, we consider
1477
+ the reconnect attempts as still within the connection phase, not true
1478
+ reconnection. This can happen e.g. when connecting to remote host via
1479
+ a proxy.
1480
+ */
1481
+ __privateAdd(this, _confirmedOpen, false);
1482
+ __privateAdd(this, _connectionPhase, "initial-connection");
1483
+ __privateAdd(this, _connectionStatus, "closed");
1484
+ __privateAdd(this, _connectionTimeout);
1485
+ __privateAdd(this, _deferredOpen);
1486
+ __privateAdd(this, _protocols);
1487
+ __privateAdd(this, _url);
1488
+ __privateAdd(this, _ws);
1489
+ __publicField(this, "receive", (evt) => {
1490
+ if (isLoginErrorMessage(evt.data)) {
1491
+ console.log(\`[WebSocketConnection] closed because of login issue\`);
1492
+ if (__privateGet(this, _deferredOpen)) {
1493
+ console.log(\`... and qwe have a deferred connection\`);
1494
+ }
1495
+ __privateGet(this, _callback).call(this, {
1496
+ type: "LOGIN_REJECTED",
1497
+ reason: evt.data
1498
+ });
1499
+ this.close(evt.data);
1500
+ } else {
1501
+ const vuuMessageFromServer = parseWebSocketMessage(evt.data);
1502
+ if (debugEnabled3) {
1503
+ if (vuuMessageFromServer.body.type !== "HB") {
1504
+ debug3(\`\${vuuMessageFromServer.body.type}\`);
1505
+ if (vuuMessageFromServer.body.type === "CHANGE_VP_SUCCESS") {
1506
+ debug3(JSON.stringify(vuuMessageFromServer.body));
1507
+ }
1508
+ }
1509
+ }
1510
+ __privateGet(this, _callback).call(this, vuuMessageFromServer);
1511
+ if (!this.confirmedOpen) {
1512
+ if (vuuMessageFromServer.body.type === "LOGIN_SUCCESS") {
1513
+ this.connectionStatus = __privateGet(this, _connectionPhase) === "initial-connection" ? "connected" : "reconnected";
1514
+ this.confirmedOpen = true;
1515
+ }
1516
+ }
1517
+ }
1518
+ });
1519
+ __publicField(this, "send", (msg) => {
1520
+ var _a;
1521
+ if (msg.body.type === "CHANGE_VP_RANGE") {
1522
+ info2 == null ? void 0 : info2(
1523
+ \`CHANGE_VP_RANGE<#\${msg.requestId}> \${msg.body.from}-\${msg.body.to}\`
1524
+ );
1525
+ }
1526
+ (_a = __privateGet(this, _ws)) == null ? void 0 : _a.send(JSON.stringify(msg));
1527
+ });
1528
+ __privateSet(this, _callback, callback);
1529
+ __privateSet(this, _connectionTimeout, connectionTimeout);
1530
+ __privateSet(this, _url, url);
1531
+ __privateSet(this, _protocols, protocols);
1532
+ }
1533
+ get connectionTimeout() {
1534
+ return __privateGet(this, _connectionTimeout);
1535
+ }
1536
+ get protocols() {
1537
+ return __privateGet(this, _protocols);
1538
+ }
1539
+ get isClosed() {
1540
+ return __privateGet(this, _connectionStatus) === "closed";
1541
+ }
1542
+ get isDisconnected() {
1543
+ return __privateGet(this, _connectionStatus) === "disconnected";
1544
+ }
1545
+ get connectionPhase() {
1546
+ return __privateGet(this, _connectionPhase);
1547
+ }
1548
+ get connectionStatus() {
1549
+ return __privateGet(this, _connectionStatus);
1550
+ }
1551
+ set connectionStatus(connectionStatus) {
1552
+ if (connectionStatus !== "connecting" && connectionStatus !== "reconnecting") {
1553
+ __privateSet(this, _connectionStatus, connectionStatus);
1554
+ this.emit("connection-status", __privateGet(this, _connectionStatus));
1555
+ }
1556
+ }
1557
+ get confirmedOpen() {
1558
+ return __privateGet(this, _confirmedOpen);
1559
+ }
1560
+ /**
1561
+ * We are 'confirmedOpen' when we see the first message transmitted
1562
+ * from the server. This ensures that even if we have one or more
1563
+ * proxies in our route to the endPoint, all connections have been
1564
+ * opened successfully.
1565
+ * First time in here (on our initial successful connection) we switch
1566
+ * from 'connect' phase to 'reconnect' phase. We may have different
1567
+ * retry configurations for these two phases.
1568
+ */
1569
+ set confirmedOpen(confirmedOpen) {
1570
+ __privateSet(this, _confirmedOpen, confirmedOpen);
1571
+ if (confirmedOpen && __privateGet(this, _connectionPhase) === "initial-connection") {
1572
+ __privateSet(this, _connectionPhase, "post-disconnect-reconnection");
1573
+ }
1574
+ }
1575
+ get url() {
1576
+ return __privateGet(this, _url);
1577
+ }
1578
+ async openWebSocket() {
1579
+ var _a;
1580
+ const initialConnect = __privateGet(this, _connectionPhase) === "initial-connection";
1581
+ if (__privateGet(this, _deferredOpen) === void 0) {
1582
+ __privateSet(this, _deferredOpen, new DeferredPromise());
1583
+ }
1584
+ const { connectionTimeout, protocols, url } = this;
1585
+ __privateSet(this, _connectionStatus, initialConnect ? "connecting" : "reconnecting");
1586
+ const timer = setTimeout(() => {
1587
+ throw Error(
1588
+ \`Failed to open WebSocket connection to \${url}, timed out after \${connectionTimeout}ms\`
1589
+ );
1590
+ }, connectionTimeout);
1591
+ const ws = __privateSet(this, _ws, new WebSocket(url, protocols));
1592
+ ws.onopen = () => {
1593
+ this.connectionStatus = "websocket-open";
1594
+ clearTimeout(timer);
1595
+ if (__privateGet(this, _deferredOpen)) {
1596
+ __privateGet(this, _deferredOpen).resolve(void 0);
1597
+ __privateSet(this, _deferredOpen, void 0);
1598
+ }
1599
+ };
1600
+ ws.onerror = () => {
1601
+ clearTimeout(timer);
1602
+ };
1603
+ ws.onclose = () => {
1604
+ if (!this.isClosed) {
1605
+ this.confirmedOpen = false;
1606
+ this.connectionStatus = "disconnected";
1607
+ this.close("failure");
1608
+ }
1609
+ };
1610
+ ws.onmessage = (evt) => {
1611
+ this.receive(evt);
1612
+ };
1613
+ return (_a = __privateGet(this, _deferredOpen)) == null ? void 0 : _a.promise;
1614
+ }
1615
+ close(reason = "shutdown") {
1616
+ var _a;
1617
+ this.connectionStatus = "closed";
1618
+ if (reason === "failure") {
1619
+ if (__privateGet(this, _deferredOpen)) {
1620
+ __privateGet(this, _deferredOpen).reject(Error("connection failed"));
1621
+ __privateSet(this, _deferredOpen, void 0);
1622
+ }
1623
+ } else {
1624
+ (_a = __privateGet(this, _ws)) == null ? void 0 : _a.close();
1625
+ }
1626
+ __privateSet(this, _ws, void 0);
1627
+ }
1628
+ };
1629
+ _callback = new WeakMap();
1630
+ _confirmedOpen = new WeakMap();
1631
+ _connectionPhase = new WeakMap();
1632
+ _connectionStatus = new WeakMap();
1633
+ _connectionTimeout = new WeakMap();
1634
+ _deferredOpen = new WeakMap();
1635
+ _protocols = new WeakMap();
1636
+ _url = new WeakMap();
1637
+ _ws = new WeakMap();
1638
+
1442
1639
  // src/server-proxy/server-proxy.ts
1443
1640
  var _requestId = 1;
1444
- var { debug: debug3, debugEnabled: debugEnabled3, error: error2, info: info2, infoEnabled: infoEnabled2, warn: warn2 } = logger("ServerProxy");
1641
+ var { debug: debug4, debugEnabled: debugEnabled4, error: error2, info: info3, infoEnabled: infoEnabled2, warn: warn2 } = logger("ServerProxy");
1445
1642
  var nextRequestId = () => \`\${_requestId++}\`;
1446
1643
  var DEFAULT_OPTIONS = {};
1447
1644
  var isActiveViewport = (viewPort) => viewPort.disabled !== true && viewPort.suspended !== true;
@@ -1478,13 +1675,15 @@ var ServerProxy = class {
1478
1675
  __publicField(this, "cachedTableMetaRequests", /* @__PURE__ */ new Map());
1479
1676
  __publicField(this, "cachedTableSchemas", /* @__PURE__ */ new Map());
1480
1677
  __publicField(this, "tableList");
1481
- __publicField(this, "connectionStatusChanged", (message) => {
1482
- if (message.connectionStatus === "disconnected") {
1678
+ __publicField(this, "connectionStatusChanged", (status) => {
1679
+ if (status === "disconnected") {
1680
+ this.sessionId = void 0;
1483
1681
  this.clearAllViewports();
1682
+ } else if (status === "reconnected") {
1683
+ this.reconnect();
1484
1684
  }
1485
1685
  });
1486
1686
  __publicField(this, "reconnect", async () => {
1487
- await this.login(this.authToken);
1488
1687
  const [activeViewports, inactiveViewports] = partition(
1489
1688
  Array.from(this.viewports.values()),
1490
1689
  isActiveViewport
@@ -1520,7 +1719,6 @@ var ServerProxy = class {
1520
1719
  this.postMessageToClient = callback;
1521
1720
  this.viewports = /* @__PURE__ */ new Map();
1522
1721
  this.mapClientToServerViewport = /* @__PURE__ */ new Map();
1523
- connection.on("reconnected", this.reconnect);
1524
1722
  connection.on("connection-status", this.connectionStatusChanged);
1525
1723
  }
1526
1724
  async login(authToken) {
@@ -1576,8 +1774,8 @@ var ServerProxy = class {
1576
1774
  );
1577
1775
  if (clientResponse) {
1578
1776
  this.postMessageToClient(clientResponse);
1579
- if (debugEnabled3) {
1580
- debug3(
1777
+ if (debugEnabled4) {
1778
+ debug4(
1581
1779
  \`post DataSourceSubscribedMessage to client: \${JSON.stringify(
1582
1780
  clientResponse
1583
1781
  )}\`
@@ -1651,7 +1849,7 @@ var ServerProxy = class {
1651
1849
  unsubscribe(clientViewportId) {
1652
1850
  const serverViewportId = this.mapClientToServerViewport.get(clientViewportId);
1653
1851
  if (serverViewportId) {
1654
- info2 == null ? void 0 : info2(
1852
+ info3 == null ? void 0 : info3(
1655
1853
  \`Unsubscribe Message (Client to Server):
1656
1854
  \${serverViewportId}\`
1657
1855
  );
@@ -1693,26 +1891,26 @@ var ServerProxy = class {
1693
1891
  /**********************************************************************/
1694
1892
  setViewRange(viewport, message) {
1695
1893
  const requestId = nextRequestId();
1696
- infoEnabled2 && info2(\`setViewRange (\${message.range.from}:\${message.range.to})\`);
1894
+ infoEnabled2 && info3(\`setViewRange (\${message.range.from}:\${message.range.to})\`);
1697
1895
  const [serverRequest, rows, debounceRequest] = viewport.rangeRequest(
1698
1896
  requestId,
1699
1897
  message.range
1700
1898
  );
1701
1899
  if (viewport.status === "subscribed") {
1702
- info2 == null ? void 0 : info2(\`setViewRange \${message.range.from} - \${message.range.to}\`);
1900
+ info3 == null ? void 0 : info3(\`setViewRange \${message.range.from} - \${message.range.to}\`);
1703
1901
  if (serverRequest) {
1704
1902
  if (true) {
1705
- info2 == null ? void 0 : info2(
1903
+ info3 == null ? void 0 : info3(
1706
1904
  \`CHANGE_VP_RANGE (\${message.range.from}-\${message.range.to}) => (\${serverRequest.from}-\${serverRequest.to})\`
1707
1905
  );
1708
1906
  }
1709
- infoEnabled2 && info2(
1907
+ infoEnabled2 && info3(
1710
1908
  \`setViewRange send CHANGE_VP_RANGE<#\${requestId}> (\${serverRequest.from}-\${serverRequest.to})\`
1711
1909
  );
1712
1910
  this.sendMessageToServer(serverRequest, requestId);
1713
1911
  }
1714
1912
  if (rows) {
1715
- info2 == null ? void 0 : info2(\`setViewRange \${rows.length} rows returned from cache\`);
1913
+ info3 == null ? void 0 : info3(\`setViewRange \${rows.length} rows returned from cache\`);
1716
1914
  this.postMessageToClient({
1717
1915
  mode: "update",
1718
1916
  type: "viewport-update",
@@ -1776,19 +1974,19 @@ var ServerProxy = class {
1776
1974
  viewport.suspend();
1777
1975
  if (escalateToDisable) {
1778
1976
  viewport.suspendTimer = setTimeout(() => {
1779
- info2 == null ? void 0 : info2("suspendTimer expired, escalate suspend to disable");
1977
+ info3 == null ? void 0 : info3("suspendTimer expired, escalate suspend to disable");
1780
1978
  this.disableViewport(viewport);
1781
1979
  }, escalateDelay);
1782
1980
  }
1783
1981
  }
1784
1982
  resumeViewport(viewport) {
1785
1983
  if (viewport.suspendTimer) {
1786
- debug3 == null ? void 0 : debug3("clear suspend timer");
1984
+ debug4 == null ? void 0 : debug4("clear suspend timer");
1787
1985
  clearTimeout(viewport.suspendTimer);
1788
1986
  viewport.suspendTimer = null;
1789
1987
  }
1790
1988
  const [size, rows] = viewport.resume();
1791
- debug3 == null ? void 0 : debug3(\`resumeViewport size \${size}, \${rows.length} rows sent to client\`);
1989
+ debug4 == null ? void 0 : debug4(\`resumeViewport size \${size}, \${rows.length} rows sent to client\`);
1792
1990
  this.postMessageToClient({
1793
1991
  clientViewportId: viewport.clientViewportId,
1794
1992
  mode: "update",
@@ -2038,6 +2236,14 @@ var ServerProxy = class {
2038
2236
  }
2039
2237
  handleMessageFromServer(message) {
2040
2238
  var _a, _b;
2239
+ if (isLoginRejectedMessage(message)) {
2240
+ if (this.pendingLogin) {
2241
+ this.pendingLogin.reject(message.reason);
2242
+ this.pendingLogin = void 0;
2243
+ this.authToken = "";
2244
+ }
2245
+ return;
2246
+ }
2041
2247
  const { body, requestId, sessionId } = message;
2042
2248
  const pendingRequest = this.pendingRequests.get(requestId);
2043
2249
  if (pendingRequest) {
@@ -2067,9 +2273,6 @@ var ServerProxy = class {
2067
2273
  throw Error("LOGIN_SUCCESS did not provide sessionId");
2068
2274
  }
2069
2275
  break;
2070
- case "LOGIN_FAIL":
2071
- this.postMessageToClient(body);
2072
- break;
2073
2276
  case "REMOVE_VP_SUCCESS":
2074
2277
  {
2075
2278
  const viewport = viewports.get(body.viewPortId);
@@ -2116,8 +2319,8 @@ var ServerProxy = class {
2116
2319
  const response = viewport.completeOperation(requestId);
2117
2320
  if (response !== void 0) {
2118
2321
  this.postMessageToClient(response);
2119
- if (debugEnabled3) {
2120
- debug3(\`postMessageToClient \${JSON.stringify(response)}\`);
2322
+ if (debugEnabled4) {
2323
+ debug4(\`postMessageToClient \${JSON.stringify(response)}\`);
2121
2324
  }
2122
2325
  }
2123
2326
  }
@@ -2167,28 +2370,28 @@ var ServerProxy = class {
2167
2370
  case "TABLE_ROW":
2168
2371
  {
2169
2372
  const viewportRowMap = groupRowsByViewport(body.rows);
2170
- if (debugEnabled3) {
2373
+ if (debugEnabled4) {
2171
2374
  const [firstRow] = body.rows;
2172
2375
  if (body.rows.length === 0) {
2173
- infoEnabled2 && info2("handleMessageFromServer TABLE_ROW 0 rows");
2376
+ infoEnabled2 && info3("handleMessageFromServer TABLE_ROW 0 rows");
2174
2377
  } else if ((firstRow == null ? void 0 : firstRow.rowIndex) === -1) {
2175
2378
  if (body.rows.length === 1) {
2176
2379
  if (firstRow.updateType === "SIZE") {
2177
- infoEnabled2 && info2(
2380
+ infoEnabled2 && info3(
2178
2381
  \`handleMessageFromServer [\${firstRow.viewPortId}] TABLE_ROW SIZE ONLY \${firstRow.vpSize}\`
2179
2382
  );
2180
2383
  } else {
2181
- infoEnabled2 && info2(
2384
+ infoEnabled2 && info3(
2182
2385
  \`handleMessageFromServer [\${firstRow.viewPortId}] TABLE_ROW SIZE \${firstRow.vpSize} rowIdx \${firstRow.rowIndex}\`
2183
2386
  );
2184
2387
  }
2185
2388
  } else {
2186
- infoEnabled2 && info2(
2389
+ infoEnabled2 && info3(
2187
2390
  \`handleMessageFromServer TABLE_ROW \${body.rows.length} rows, SIZE \${firstRow.vpSize}, [\${body.rows.map((r) => r.rowIndex).join(",")}]\`
2188
2391
  );
2189
2392
  }
2190
2393
  } else {
2191
- infoEnabled2 && info2(
2394
+ infoEnabled2 && info3(
2192
2395
  \`handleMessageFromServer TABLE_ROW \${body.rows.length} rows [\${body.rows.map((r) => r.rowIndex).join(",")}]\`
2193
2396
  );
2194
2397
  }
@@ -2211,7 +2414,7 @@ var ServerProxy = class {
2211
2414
  const viewport = this.viewports.get(body.viewPortId);
2212
2415
  if (viewport) {
2213
2416
  const { from, to } = body;
2214
- infoEnabled2 && info2(\`CHANGE_VP_RANGE_SUCCESS<#\${requestId}> \${from} - \${to}\`);
2417
+ infoEnabled2 && info3(\`CHANGE_VP_RANGE_SUCCESS<#\${requestId}> \${from} - \${to}\`);
2215
2418
  viewport.completeOperation(requestId, from, to);
2216
2419
  }
2217
2420
  }
@@ -2356,7 +2559,7 @@ var ServerProxy = class {
2356
2559
  error2(body.msg);
2357
2560
  break;
2358
2561
  default:
2359
- infoEnabled2 && info2(\`handleMessageFromServer \${body["type"]}.\`);
2562
+ infoEnabled2 && info3(\`handleMessageFromServer \${body["type"]}.\`);
2360
2563
  }
2361
2564
  }
2362
2565
  cacheTableMeta(messageBody) {
@@ -2395,7 +2598,7 @@ var ServerProxy = class {
2395
2598
  const [rows, mode] = result;
2396
2599
  const size = viewport.getNewRowCount();
2397
2600
  if (size !== void 0 || rows && rows.length > 0) {
2398
- debugEnabled3 && debug3(
2601
+ debugEnabled4 && debug4(
2399
2602
  \`postMessageToClient #\${viewport.clientViewportId} viewport-update \${mode}, \${(_a = rows == null ? void 0 : rows.length) != null ? _a : "no"} rows, size \${size}\`
2400
2603
  );
2401
2604
  if (mode) {
@@ -2414,316 +2617,31 @@ var ServerProxy = class {
2414
2617
  }
2415
2618
  };
2416
2619
 
2417
- // src/WebSocketConnection.ts
2418
- var { debug: debug4, debugEnabled: debugEnabled4, info: info3 } = logger("WebSocketConnection");
2419
- var isNotConnecting = (connectionState) => connectionState.connectionStatus !== "connecting" && connectionState.connectionStatus !== "reconnecting";
2420
- var isWebSocketConnectionMessage = (msg) => {
2421
- if ("connectionStatus" in msg) {
2422
- return [
2423
- "connecting",
2424
- "connected",
2425
- "connection-open-awaiting-session",
2426
- "reconnecting",
2427
- "reconnected",
2428
- "disconnected",
2429
- "closed",
2430
- "failed"
2431
- ].includes(msg.connectionStatus);
2432
- } else {
2433
- return false;
2434
- }
2435
- };
2436
- var DEFAULT_RETRY_LIMITS = {
2437
- connect: 5,
2438
- reconnect: 8
2439
- };
2440
- var DEFAULT_CONNECTION_TIMEOUT = 1e4;
2441
- var ConnectingEndState = {
2442
- connecting: "connected",
2443
- reconnecting: "reconnected"
2444
- };
2445
- var parseWebSocketMessage = (message) => {
2446
- try {
2447
- return JSON.parse(message);
2448
- } catch (e) {
2449
- throw Error(\`Error parsing JSON response from server \${message}\`);
2450
- }
2451
- };
2452
- var _callback, _confirmedOpen, _connectionState, _connectionTimeout, _deferredConnection, _protocols, _reconnectAttempts, _requiresLogin, _url, _ws;
2453
- var WebSocketConnection = class extends EventEmitter {
2454
- constructor({
2455
- callback,
2456
- connectionTimeout = DEFAULT_CONNECTION_TIMEOUT,
2457
- protocols,
2458
- retryLimits = DEFAULT_RETRY_LIMITS,
2459
- url
2460
- }) {
2461
- super();
2462
- __privateAdd(this, _callback);
2463
- /**
2464
- We are not confirmedOpen until we receive the first message from the
2465
- server. If we get an unexpected close event before that, we consider
2466
- the reconnect attempts as still within the connection phase, not true
2467
- reconnection. This can happen e.g. when connecting to remote host via
2468
- a proxy.
2469
- */
2470
- __privateAdd(this, _confirmedOpen, false);
2471
- __privateAdd(this, _connectionState);
2472
- __privateAdd(this, _connectionTimeout);
2473
- __privateAdd(this, _deferredConnection);
2474
- __privateAdd(this, _protocols);
2475
- __privateAdd(this, _reconnectAttempts);
2476
- __privateAdd(this, _requiresLogin, true);
2477
- __privateAdd(this, _url);
2478
- __privateAdd(this, _ws);
2479
- __publicField(this, "receive", (evt) => {
2480
- if (evt.data === "Invalid token" || evt.data === "Token has expired") {
2481
- const closeReason = evt.data === "Invalid token" ? "invalid-token" : "token-expired";
2482
- this.close(closeReason);
2483
- } else {
2484
- const vuuMessageFromServer = parseWebSocketMessage(evt.data);
2485
- if (vuuMessageFromServer.body.type === "CHANGE_VP_RANGE_SUCCESS") {
2486
- info3 == null ? void 0 : info3(\`CHANGE_VP_RANGE_SUCCESS<#\${vuuMessageFromServer.requestId}>\`);
2487
- }
2488
- if (debugEnabled4) {
2489
- if (vuuMessageFromServer.body.type !== "HB") {
2490
- debug4(\`\${vuuMessageFromServer.body.type}\`);
2491
- if (vuuMessageFromServer.body.type === "CHANGE_VP_SUCCESS") {
2492
- debug4(JSON.stringify(vuuMessageFromServer.body));
2493
- }
2494
- }
2495
- }
2496
- __privateGet(this, _callback).call(this, vuuMessageFromServer);
2497
- }
2498
- });
2499
- __publicField(this, "send", (msg) => {
2500
- var _a;
2501
- if (msg.body.type === "CHANGE_VP_RANGE") {
2502
- info3 == null ? void 0 : info3(
2503
- \`CHANGE_VP_RANGE<#\${msg.requestId}> \${msg.body.from}-\${msg.body.to}\`
2504
- );
2505
- }
2506
- (_a = __privateGet(this, _ws)) == null ? void 0 : _a.send(JSON.stringify(msg));
2507
- });
2508
- __privateSet(this, _callback, callback);
2509
- __privateSet(this, _connectionTimeout, connectionTimeout);
2510
- __privateSet(this, _url, url);
2511
- __privateSet(this, _protocols, protocols);
2512
- __privateSet(this, _reconnectAttempts, {
2513
- retryAttemptsTotal: retryLimits.reconnect,
2514
- retryAttemptsRemaining: retryLimits.reconnect,
2515
- secondsToNextRetry: 1
2516
- });
2517
- __privateSet(this, _connectionState, {
2518
- connectionPhase: "connecting",
2519
- connectionStatus: "closed",
2520
- retryAttemptsTotal: retryLimits.connect,
2521
- retryAttemptsRemaining: retryLimits.connect,
2522
- secondsToNextRetry: 1
2523
- });
2524
- }
2525
- get connectionTimeout() {
2526
- return __privateGet(this, _connectionTimeout);
2527
- }
2528
- get protocols() {
2529
- return __privateGet(this, _protocols);
2530
- }
2531
- get requiresLogin() {
2532
- return __privateGet(this, _requiresLogin);
2533
- }
2534
- get isClosed() {
2535
- return this.status === "closed";
2536
- }
2537
- get isDisconnected() {
2538
- return this.status === "disconnected";
2539
- }
2540
- get isConnecting() {
2541
- return __privateGet(this, _connectionState).connectionPhase === "connecting";
2542
- }
2543
- get status() {
2544
- return __privateGet(this, _connectionState).connectionStatus;
2545
- }
2546
- set status(connectionStatus) {
2547
- __privateSet(this, _connectionState, {
2548
- ...__privateGet(this, _connectionState),
2549
- connectionStatus
2550
- });
2551
- if (isNotConnecting(__privateGet(this, _connectionState))) {
2552
- this.emit("connection-status", __privateGet(this, _connectionState));
2553
- }
2554
- }
2555
- get connectionState() {
2556
- return __privateGet(this, _connectionState);
2557
- }
2558
- get hasConnectionAttemptsRemaining() {
2559
- return __privateGet(this, _connectionState).retryAttemptsRemaining > 0;
2560
- }
2561
- get confirmedOpen() {
2562
- return __privateGet(this, _confirmedOpen);
2563
- }
2564
- /**
2565
- * We are 'confirmedOpen' when we see the first message transmitted
2566
- * from the server. This ensures that even if we have one or more
2567
- * proxies in our route to the endPoint, all connections have been
2568
- * opened successfully.
2569
- * First time in here (on our initial successful connection) we switch
2570
- * from 'connect' phase to 'reconnect' phase. We may have different
2571
- * retry configurations for these two phases.
2572
- */
2573
- set confirmedOpen(confirmedOpen) {
2574
- __privateSet(this, _confirmedOpen, confirmedOpen);
2575
- if (confirmedOpen && this.isConnecting) {
2576
- __privateSet(this, _connectionState, {
2577
- ...__privateGet(this, _connectionState),
2578
- connectionPhase: "reconnecting",
2579
- ...__privateGet(this, _reconnectAttempts)
2580
- });
2581
- } else if (confirmedOpen) {
2582
- __privateSet(this, _connectionState, {
2583
- ...__privateGet(this, _connectionState),
2584
- ...__privateGet(this, _reconnectAttempts)
2585
- });
2586
- }
2587
- }
2588
- get url() {
2589
- return __privateGet(this, _url);
2590
- }
2591
- async connect(clientCall = true) {
2592
- var _a;
2593
- const state = __privateGet(this, _connectionState);
2594
- if (this.isConnecting && __privateGet(this, _deferredConnection) === void 0) {
2595
- __privateSet(this, _deferredConnection, new DeferredPromise());
2596
- }
2597
- const { connectionTimeout, protocols, url } = this;
2598
- this.status = state.connectionPhase;
2599
- const timer = setTimeout(() => {
2600
- throw Error(
2601
- \`Failed to open WebSocket connection to \${url}, timed out after \${connectionTimeout}ms\`
2602
- );
2603
- }, connectionTimeout);
2604
- const ws2 = __privateSet(this, _ws, new WebSocket(url, protocols));
2605
- ws2.onopen = () => {
2606
- const connectedStatus = ConnectingEndState[state.connectionPhase];
2607
- this.status = connectedStatus;
2608
- clearTimeout(timer);
2609
- if (__privateGet(this, _deferredConnection)) {
2610
- __privateGet(this, _deferredConnection).resolve(void 0);
2611
- __privateSet(this, _deferredConnection, void 0);
2612
- }
2613
- if (this.isConnecting) {
2614
- this.emit("connected");
2615
- } else {
2616
- this.emit("reconnected");
2617
- }
2618
- };
2619
- ws2.onerror = () => {
2620
- clearTimeout(timer);
2621
- };
2622
- ws2.onclose = () => {
2623
- if (!this.isClosed) {
2624
- this.confirmedOpen = false;
2625
- this.status = "disconnected";
2626
- if (this.hasConnectionAttemptsRemaining) {
2627
- this.reconnect();
2628
- } else {
2629
- this.close("failure");
2630
- }
2631
- }
2632
- };
2633
- ws2.onmessage = (evt) => {
2634
- if (!this.confirmedOpen) {
2635
- this.confirmedOpen = true;
2636
- }
2637
- this.receive(evt);
2638
- };
2639
- if (clientCall) {
2640
- return (_a = __privateGet(this, _deferredConnection)) == null ? void 0 : _a.promise;
2641
- }
2642
- }
2643
- reconnect() {
2644
- const { retryAttemptsRemaining, secondsToNextRetry } = __privateGet(this, _connectionState);
2645
- setTimeout(() => {
2646
- __privateSet(this, _connectionState, {
2647
- ...__privateGet(this, _connectionState),
2648
- retryAttemptsRemaining: retryAttemptsRemaining - 1,
2649
- secondsToNextRetry: secondsToNextRetry * 2
2650
- });
2651
- this.connect(false);
2652
- }, secondsToNextRetry * 1e3);
2653
- }
2654
- close(reason = "shutdown") {
2655
- var _a;
2656
- this.status = "closed";
2657
- if (reason === "failure") {
2658
- if (__privateGet(this, _deferredConnection)) {
2659
- __privateGet(this, _deferredConnection).reject(Error("connection failed"));
2660
- __privateSet(this, _deferredConnection, void 0);
2661
- }
2662
- } else {
2663
- (_a = __privateGet(this, _ws)) == null ? void 0 : _a.close();
2664
- }
2665
- this.emit("closed", { type: "websocket-closed", reason });
2666
- __privateSet(this, _ws, void 0);
2667
- }
2668
- };
2669
- _callback = new WeakMap();
2670
- _confirmedOpen = new WeakMap();
2671
- _connectionState = new WeakMap();
2672
- _connectionTimeout = new WeakMap();
2673
- _deferredConnection = new WeakMap();
2674
- _protocols = new WeakMap();
2675
- _reconnectAttempts = new WeakMap();
2676
- _requiresLogin = new WeakMap();
2677
- _url = new WeakMap();
2678
- _ws = new WeakMap();
2679
-
2680
2620
  // src/worker.ts
2681
- var server;
2621
+ var serverProxy;
2622
+ var webSocketConnection;
2682
2623
  var { info: info4, infoEnabled: infoEnabled3 } = logger("worker");
2683
- var getRetryLimits = (retryLimitDisconnect, retryLimitStartup) => {
2684
- if (retryLimitDisconnect !== void 0 && retryLimitStartup !== void 0) {
2685
- return {
2686
- connect: retryLimitStartup,
2687
- reconnect: retryLimitDisconnect
2688
- };
2689
- } else if (retryLimitDisconnect !== void 0) {
2690
- return {
2691
- connect: retryLimitDisconnect,
2692
- reconnect: retryLimitDisconnect
2693
- };
2694
- } else if (retryLimitStartup !== void 0) {
2695
- return {
2696
- connect: retryLimitStartup,
2697
- reconnect: retryLimitStartup
2698
- };
2699
- }
2700
- };
2701
- var ws;
2702
2624
  var sendMessageToClient = (message) => {
2703
2625
  postMessage(message);
2704
2626
  };
2705
- async function connectToServer(url, protocols, token, retryLimitDisconnect, retryLimitStartup) {
2706
- const websocketConnection = ws = new WebSocketConnection({
2707
- callback: (msg) => {
2708
- if (isConnectionQualityMetrics(msg)) {
2709
- postMessage({ type: "connection-metrics", messages: msg });
2710
- } else if (isWebSocketConnectionMessage(msg)) {
2711
- postMessage(msg);
2712
- } else {
2713
- server.handleMessageFromServer(msg);
2714
- }
2715
- },
2716
- protocols,
2717
- retryLimits: getRetryLimits(retryLimitStartup, retryLimitDisconnect),
2718
- url
2719
- });
2720
- websocketConnection.on("connection-status", postMessage);
2721
- websocketConnection.on("closed", postMessage);
2722
- await websocketConnection.connect();
2723
- server = new ServerProxy(websocketConnection, sendMessageToClient);
2724
- if (websocketConnection.requiresLogin) {
2725
- return await server.login(token);
2627
+ async function connectToServer(url, protocols, token) {
2628
+ if (webSocketConnection === void 0 && serverProxy === void 0) {
2629
+ webSocketConnection = new WebSocketConnection({
2630
+ callback: (msg) => {
2631
+ if (isConnectionQualityMetrics(msg)) {
2632
+ postMessage({ type: "connection-metrics", messages: msg });
2633
+ } else {
2634
+ serverProxy.handleMessageFromServer(msg);
2635
+ }
2636
+ },
2637
+ protocols,
2638
+ url
2639
+ });
2640
+ webSocketConnection.on("connection-status", postMessage);
2641
+ serverProxy = new ServerProxy(webSocketConnection, sendMessageToClient);
2726
2642
  }
2643
+ await webSocketConnection.openWebSocket();
2644
+ return serverProxy.login(token);
2727
2645
  }
2728
2646
  var handleMessageFromClient = async ({
2729
2647
  data: message
@@ -2734,9 +2652,7 @@ var handleMessageFromClient = async ({
2734
2652
  const sessionId = await connectToServer(
2735
2653
  message.url,
2736
2654
  message.protocol,
2737
- message.token,
2738
- message.retryLimitDisconnect,
2739
- message.retryLimitStartup
2655
+ message.token
2740
2656
  );
2741
2657
  postMessage({ type: "connected", sessionId });
2742
2658
  } catch (err) {
@@ -2746,20 +2662,20 @@ var handleMessageFromClient = async ({
2746
2662
  // If any of the messages below are received BEFORE we have connected and created
2747
2663
  // the server - handle accordingly
2748
2664
  case "disconnect":
2749
- server.disconnect();
2750
- ws == null ? void 0 : ws.close();
2665
+ serverProxy.disconnect();
2666
+ webSocketConnection == null ? void 0 : webSocketConnection.close();
2751
2667
  break;
2752
2668
  case "subscribe":
2753
2669
  infoEnabled3 && info4(\`client subscribe: \${JSON.stringify(message)}\`);
2754
- server.subscribe(message);
2670
+ serverProxy.subscribe(message);
2755
2671
  break;
2756
2672
  case "unsubscribe":
2757
2673
  infoEnabled3 && info4(\`client unsubscribe: \${JSON.stringify(message)}\`);
2758
- server.unsubscribe(message.viewport);
2674
+ serverProxy.unsubscribe(message.viewport);
2759
2675
  break;
2760
2676
  default:
2761
2677
  infoEnabled3 && info4(\`client message: \${JSON.stringify(message)}\`);
2762
- server.handleMessageFromClient(message);
2678
+ serverProxy.handleMessageFromClient(message);
2763
2679
  }
2764
2680
  };
2765
2681
  self.addEventListener("message", handleMessageFromClient);