@ancon/wildcat-utils 1.53.0-check-optimizations.2 → 1.53.1

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 (33) hide show
  1. package/check/getOrganizedCheckItemModifications.d.ts +2 -2
  2. package/check/getOrganizedCheckItemModifications.js +1 -1
  3. package/check/getOrganizedCheckItemModifications.mjs +68 -74
  4. package/check/getUniqueCheckItemModificationId.d.ts +2 -2
  5. package/check/getUniqueCheckItemModificationId.js +1 -1
  6. package/check/getUniqueCheckItemModificationId.mjs +5 -5
  7. package/checkout/getCheckoutItemModifications.js +1 -1
  8. package/checkout/getCheckoutItemModifications.mjs +9 -8
  9. package/checkout/getCheckoutProductAddonModifications.js +1 -1
  10. package/checkout/getCheckoutProductAddonModifications.mjs +7 -6
  11. package/checkout/index.js +1 -1
  12. package/checkout/index.mjs +57 -56
  13. package/currency/getFormattedCurrency.js +1 -1
  14. package/currency/getFormattedCurrency.mjs +4 -6
  15. package/currency/index.d.ts +2 -1
  16. package/currency/index.js +1 -1
  17. package/currency/index.mjs +5 -3
  18. package/currency/placeCurrencySymbol.d.ts +8 -0
  19. package/currency/placeCurrencySymbol.js +1 -0
  20. package/currency/placeCurrencySymbol.mjs +12 -0
  21. package/index.js +1 -1
  22. package/index.mjs +167 -165
  23. package/multilingual/createLocalizedCheckDetails.d.ts +2 -2
  24. package/multilingual/createLocalizedCheckDetails.js +1 -1
  25. package/multilingual/createLocalizedCheckDetails.mjs +27 -31
  26. package/package.json +6 -1
  27. package/signalr/SignalR.d.ts +21 -1
  28. package/signalr/SignalR.js +1 -1
  29. package/signalr/SignalR.mjs +108 -74
  30. package/signalr/createUseSignalRHook.d.ts +1 -1
  31. package/signalr/createUseSignalRHook.js +1 -1
  32. package/signalr/createUseSignalRHook.mjs +69 -64
  33. package/signalr/types.d.ts +2 -0
@@ -1,5 +1,5 @@
1
1
  import { IETFLanguageTag as r } from "@ancon/wildcat-types";
2
- function m(e) {
2
+ function u(e) {
3
3
  switch (e) {
4
4
  case "sv":
5
5
  return r.Swedish;
@@ -11,47 +11,43 @@ function m(e) {
11
11
  return null;
12
12
  }
13
13
  }
14
- function u(e, a) {
15
- var t, i;
16
- if (e) {
17
- const c = e, n = (t = e.localizedProductNames) == null ? void 0 : t[a], o = (i = e.localizedVariantNames) == null ? void 0 : i[a];
18
- return n && (c.productName = n), o && (c.variantName = o), c;
19
- }
20
- return e;
14
+ function d(e, c) {
15
+ var i, n;
16
+ const t = e, a = (i = e.localizedProductNames) == null ? void 0 : i[c], o = (n = e.localizedVariantNames) == null ? void 0 : n[c];
17
+ return a && (t.productName = a), o && (t.variantName = o), t;
21
18
  }
22
- function s(e, a) {
23
- var n, o;
24
- const t = e, i = (n = e.localizedNames) == null ? void 0 : n[a], c = (o = e.localizedReplacementNames) == null ? void 0 : o[a];
25
- return i && (t.name = i), c && (t.replacementName = c), t;
19
+ function m(e, c) {
20
+ var i, n;
21
+ const t = e, a = (i = e.localizedNames) == null ? void 0 : i[c], o = (n = e.localizedReplacementNames) == null ? void 0 : n[c];
22
+ return a && (t.name = a), o && (t.replacementName = o), t;
26
23
  }
27
- function f(e, a) {
24
+ function f(e, c) {
28
25
  const t = e;
29
- return t.product = u(
26
+ return t.product = d(
30
27
  e.product,
31
- a
28
+ c
32
29
  ), t;
33
30
  }
34
- function d(e, a) {
35
- const t = e, { product: i, modifications: c, addOnProducts: n, subCheckItems: o } = e;
36
- return t.product = u(i, a), c != null && c.length && (t.modifications = c.map(
37
- (l) => s(l, a)
38
- )), n != null && n.length && (t.addOnProducts = n == null ? void 0 : n.map(
39
- (l) => f(l, a)
40
- )), o != null && o.length && (t.subCheckItems = o.map(
41
- (l) => d(l, a)
31
+ function s(e, c) {
32
+ const t = e, { product: a, modifications: o, addOnProducts: i, subCheckItems: n } = e;
33
+ return t.product = d(a, c), o.length && (t.modifications = o.map(
34
+ (l) => m(l, c)
35
+ )), i != null && i.length && (t.addOnProducts = i.map(
36
+ (l) => f(l, c)
37
+ )), n.length && (t.subCheckItems = n.map(
38
+ (l) => s(l, c)
42
39
  )), t;
43
40
  }
44
- function N(e, a) {
45
- var i;
46
- const t = m(a);
41
+ function p(e, c) {
42
+ const t = u(c);
47
43
  if (t) {
48
- const c = e;
49
- return c.items = (i = e.items) == null ? void 0 : i.map(
50
- (n) => d(n, t)
51
- ), c;
44
+ const a = e;
45
+ return a.items = e.items.map(
46
+ (o) => s(o, t)
47
+ ), a;
52
48
  }
53
49
  return e;
54
50
  }
55
51
  export {
56
- N as default
52
+ p as default
57
53
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancon/wildcat-utils",
3
- "version": "1.53.0-check-optimizations.2",
3
+ "version": "1.53.1",
4
4
  "main": "index.js",
5
5
  "module": "index.mjs",
6
6
  "types": "index.d.ts",
@@ -400,6 +400,11 @@
400
400
  "require": "./currency/index.js",
401
401
  "types": "./currency/index.d.ts"
402
402
  },
403
+ "./currency/placeCurrencySymbol": {
404
+ "import": "./currency/placeCurrencySymbol.mjs",
405
+ "require": "./currency/placeCurrencySymbol.js",
406
+ "types": "./currency/placeCurrencySymbol.d.ts"
407
+ },
403
408
  "./date/convertToLocalTimezone": {
404
409
  "import": "./date/convertToLocalTimezone.mjs",
405
410
  "require": "./date/convertToLocalTimezone.js",
@@ -11,10 +11,17 @@ declare class SignalR {
11
11
  private backoff;
12
12
  private reconnectAttempt;
13
13
  private shouldReconnect;
14
+ private isReconnecting;
15
+ private pendingJoins;
14
16
  groups: string[];
15
17
  constructor(options: SignalRConfig);
16
18
  info: (message: string, data?: any) => void;
17
19
  private generateBackoff;
20
+ private getNextBackoffMs;
21
+ /**
22
+ * Keep trying to connect, with backoff, until connected or `disconnect()` is called.
23
+ * Only one reconnect loop runs at a time.
24
+ */
18
25
  private reconnect;
19
26
  private buildInitialListeners;
20
27
  /**
@@ -26,6 +33,14 @@ declare class SignalR {
26
33
  private skipSignal;
27
34
  private enhanceListener;
28
35
  setClientId: (clientId: string | undefined) => void;
36
+ /**
37
+ * Start the hub connection.
38
+ *
39
+ * @param throwError Rethrow a failed start and do nothing else.
40
+ * Without it, a failed start emits `disconnected` and keeps retrying with backoff
41
+ * until it connects or `disconnect()` is called; the returned promise settles
42
+ * when that happens.
43
+ */
29
44
  connect: (throwError?: boolean) => Promise<void>;
30
45
  disconnect: () => Promise<void>;
31
46
  /**
@@ -52,7 +67,12 @@ declare class SignalR {
52
67
  * @param listener Signal listener function
53
68
  */
54
69
  removeSignalListener: (signal: SignalRSignalName, listener: SignalREventListener) => void;
55
- joinGroup: (group: string) => Promise<void>;
70
+ /**
71
+ * Join a group. A group that is already joined, or being joined, is not joined again.
72
+ * @returns Whether the group is joined
73
+ */
74
+ joinGroup: (group: string) => Promise<boolean>;
75
+ private invokeJoinGroup;
56
76
  leaveGroup: (group: string) => Promise<void>;
57
77
  leaveAllGroups: () => Promise<void>;
58
78
  getHubConnectionId: () => string | null;
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var d=(r,e,t)=>e in r?f(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var n=(r,e,t)=>(d(r,typeof e!="symbol"?e+"":e,t),t);const h=require("@microsoft/signalr"),a=require("@ancon/wildcat-types"),l=require("../shared/wait.js"),u=require("../api/generateBackoffWithEqualJitter.js");require("axios");require("../number/randomIntFromInterval.js");class g{constructor(e){n(this,"internalEvents");n(this,"signalREvents");n(this,"hubConnection");n(this,"clientId");n(this,"logger");n(this,"backoff",[]);n(this,"reconnectAttempt",0);n(this,"shouldReconnect",!0);n(this,"groups");n(this,"info",(e,t)=>{var i;(i=this.logger)==null||i.info(e,t)});n(this,"generateBackoff",()=>{this.backoff=u(50,500,5e3),this.info("Generated new backoff")});n(this,"reconnect",async()=>{if(this.shouldReconnect)try{this.info("Attempting to reconnect...",{attempt:this.reconnectAttempt+1}),await this.connect(!0),this.info("Reconnected"),this.reconnectAttempt=0}catch{if(this.backoff[this.reconnectAttempt]!=null){const t=this.backoff[this.reconnectAttempt];if(t!=null)await l(t);else throw new Error("Could not resolve ms from backoff")}else{this.reconnectAttempt>0&&this.info("Ran out of backoff intervals, restarting backoff..."),this.reconnectAttempt=0,this.generateBackoff();const t=this.backoff[this.reconnectAttempt];if(t!=null)await l(t);else throw new Error("Could not resolve ms from backoff")}this.reconnectAttempt+=1,await this.reconnect()}});n(this,"buildInitialListeners",()=>{this.hubConnection.onclose(()=>{this.groups=[],this.info("Hub connection closed"),this.emitEvent("disconnected"),this.reconnect()}),this.hubConnection.onreconnected(()=>this.emitEvent("reconnected"))});n(this,"emitEvent",(e,...t)=>{if(this.internalEvents.has(e)){this.info(`Emitting event "${e}"`);const i=this.internalEvents.get(e);i&&i.forEach(s=>s(...t))}else this.info(`Failed to emit event "${e}". There were no listeners.`)});n(this,"skipSignal",(e,t)=>{this.info(`Skipped signal "${e}"`,t)});n(this,"enhanceListener",(e,t,i)=>s=>{const o=JSON.parse(s),c=i&&o.clientId&&o.clientId===this.clientId;return c||this.info(`Received signal "${e}"`,s),c?this.skipSignal(e,s):t(o)});n(this,"setClientId",e=>{this.clientId=e});n(this,"connect",async(e=!1)=>{try{this.info("Connecting..."),await this.hubConnection.start(),this.info("Connected"),this.emitEvent("connected")}catch(t){if(this.info("Failed to connect"),e)throw t}});n(this,"disconnect",async()=>{try{this.shouldReconnect=!1,this.info("Disconnecting..."),await this.hubConnection.stop(),this.info("Disconnected"),this.emitEvent("disconnected")}catch{this.info("Failed to disconnect")}});n(this,"addEventListener",(e,t)=>{this.internalEvents.has(e)||this.internalEvents.set(e,[]);const i=this.internalEvents.get(e);return i&&i.push(t),()=>this.removeEventListener(e,t)});n(this,"removeEventListener",(e,t)=>{var i;if(this.internalEvents.has(e)){const s=this.internalEvents.get(e),o=((i=s==null?void 0:s.indexOf)==null?void 0:i.call(s,t))??-1;o>=0?(s.splice(o,1),this.info(`Removed event listener for event "${e}"`)):this.info(`Failed to remove event listener for event "${e}". Specified listener was not found.`)}else this.info(`Failed to remove event listener for event "${e}". Event doesn't have any listeners.`)});n(this,"addSignalListener",(e,t,i=!0)=>{this.signalREvents.has(e)||this.signalREvents.set(e,[]);const s=this.signalREvents.get(e),o=this.enhanceListener(e,t,i);return s&&s.push(o),this.hubConnection.on(e,o),this.info(`Added signal listener for signal "${e}"`),()=>this.removeSignalListener(e,o)});n(this,"removeSignalListener",(e,t)=>{var i;if(this.signalREvents.has(e)){const s=this.signalREvents.get(e),o=((i=s==null?void 0:s.indexOf)==null?void 0:i.call(s,t))??-1;o>=0?(this.hubConnection.off(e,t),s.splice(o,1),this.info(`Removed signal listener for signal "${e}"`)):this.info(`Failed to remove signal listener for signal "${e}". Specified listener was not found.`)}else this.info(`Failed to remove signal listener for signal "${e}". Signal doesn't have any listeners.`)});n(this,"joinGroup",async e=>{this.info(`Joining group "${e}"...`);const t=this.groups.push(e)-1;try{await this.hubConnection.invoke(a.SignalRMethodName.JoinGroup,e),this.info(`Joined group "${e}"`)}catch(i){this.info(`Failed to join group "${e}"`,i),t>=0&&this.groups.splice(t,1)}});n(this,"leaveGroup",async e=>{this.info(`Leaving group "${e}"...`);const t=this.groups.indexOf(e);t>=0&&this.groups.splice(t,1);try{await this.hubConnection.invoke(a.SignalRMethodName.LeaveGroup,e),this.info(`Left group "${e}"`)}catch(i){this.groups.indexOf(e)<0&&this.groups.push(e),this.info(`Failed to leave group "${e}"`,i)}});n(this,"leaveAllGroups",async()=>{this.info(`Leaving all (${this.groups.length}) groups...`);const e=[...this.groups].map(t=>this.leaveGroup(t));await Promise.all(e),this.info("Left all groups")});n(this,"getHubConnectionId",()=>this.hubConnection.connectionId);this.internalEvents=new Map,this.signalREvents=new Map,this.groups=[],e.enableLogging&&(this.logger=e.logger),this.hubConnection=new h.HubConnectionBuilder().withUrl(`${e.signalRApiUrl}/${e.hub}`).configureLogging(h.LogLevel.None).build(),e.serverTimeoutInMilliseconds&&(this.hubConnection.serverTimeoutInMilliseconds=e.serverTimeoutInMilliseconds),this.buildInitialListeners()}}module.exports=g;
1
+ "use strict";var l=Object.defineProperty;var f=(r,e,n)=>e in r?l(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n;var t=(r,e,n)=>(f(r,typeof e!="symbol"?e+"":e,n),n);const h=require("@microsoft/signalr"),a=require("@ancon/wildcat-types"),d=require("../shared/wait.js"),u=require("../api/generateBackoffWithEqualJitter.js");require("axios");require("../number/randomIntFromInterval.js");class g{constructor(e){t(this,"internalEvents");t(this,"signalREvents");t(this,"hubConnection");t(this,"clientId");t(this,"logger");t(this,"backoff",[]);t(this,"reconnectAttempt",0);t(this,"shouldReconnect",!0);t(this,"isReconnecting",!1);t(this,"pendingJoins",new Map);t(this,"groups");t(this,"info",(e,n)=>{var i;(i=this.logger)==null||i.info(e,n)});t(this,"generateBackoff",()=>{this.backoff=u(50,500,5e3),this.info("Generated new backoff")});t(this,"getNextBackoffMs",()=>{this.backoff[this.reconnectAttempt]==null&&(this.reconnectAttempt>0&&this.info("Ran out of backoff intervals, restarting backoff..."),this.reconnectAttempt=0,this.generateBackoff());const e=this.backoff[this.reconnectAttempt];if(e==null)throw new Error("Could not resolve ms from backoff");return e});t(this,"reconnect",async()=>{if(!this.isReconnecting){this.isReconnecting=!0;try{for(;this.shouldReconnect;)try{this.info("Attempting to reconnect...",{attempt:this.reconnectAttempt+1}),await this.connect(!0),this.info("Reconnected"),this.reconnectAttempt=0;return}catch{if(!this.shouldReconnect)break;await d(this.getNextBackoffMs()),this.reconnectAttempt+=1}}finally{this.isReconnecting=!1}}});t(this,"buildInitialListeners",()=>{this.hubConnection.onclose(()=>{this.groups=[],this.info("Hub connection closed"),this.emitEvent("disconnected"),this.reconnect()}),this.hubConnection.onreconnected(()=>this.emitEvent("reconnected"))});t(this,"emitEvent",(e,...n)=>{if(this.internalEvents.has(e)){this.info(`Emitting event "${e}"`);const i=this.internalEvents.get(e);i&&i.forEach(s=>s(...n))}else this.info(`Failed to emit event "${e}". There were no listeners.`)});t(this,"skipSignal",(e,n)=>{this.info(`Skipped signal "${e}"`,n)});t(this,"enhanceListener",(e,n,i)=>s=>{const o=JSON.parse(s),c=i&&o.clientId&&o.clientId===this.clientId;return c||this.info(`Received signal "${e}"`,s),c?this.skipSignal(e,s):n(o)});t(this,"setClientId",e=>{this.clientId=e});t(this,"connect",async(e=!1)=>{try{this.info("Connecting..."),await this.hubConnection.start(),this.info("Connected"),this.emitEvent("connected")}catch(n){if(this.info("Failed to connect"),e)throw n;this.shouldReconnect&&(this.emitEvent("disconnected"),await this.reconnect())}});t(this,"disconnect",async()=>{try{this.shouldReconnect=!1,this.info("Disconnecting..."),await this.hubConnection.stop(),this.info("Disconnected"),this.emitEvent("disconnected")}catch{this.info("Failed to disconnect")}});t(this,"addEventListener",(e,n)=>{this.internalEvents.has(e)||this.internalEvents.set(e,[]);const i=this.internalEvents.get(e);return i&&i.push(n),()=>this.removeEventListener(e,n)});t(this,"removeEventListener",(e,n)=>{var i;if(this.internalEvents.has(e)){const s=this.internalEvents.get(e),o=((i=s==null?void 0:s.indexOf)==null?void 0:i.call(s,n))??-1;o>=0?(s.splice(o,1),this.info(`Removed event listener for event "${e}"`)):this.info(`Failed to remove event listener for event "${e}". Specified listener was not found.`)}else this.info(`Failed to remove event listener for event "${e}". Event doesn't have any listeners.`)});t(this,"addSignalListener",(e,n,i=!0)=>{this.signalREvents.has(e)||this.signalREvents.set(e,[]);const s=this.signalREvents.get(e),o=this.enhanceListener(e,n,i);return s&&s.push(o),this.hubConnection.on(e,o),this.info(`Added signal listener for signal "${e}"`),()=>this.removeSignalListener(e,o)});t(this,"removeSignalListener",(e,n)=>{var i;if(this.signalREvents.has(e)){const s=this.signalREvents.get(e),o=((i=s==null?void 0:s.indexOf)==null?void 0:i.call(s,n))??-1;o>=0?(this.hubConnection.off(e,n),s.splice(o,1),this.info(`Removed signal listener for signal "${e}"`)):this.info(`Failed to remove signal listener for signal "${e}". Specified listener was not found.`)}else this.info(`Failed to remove signal listener for signal "${e}". Signal doesn't have any listeners.`)});t(this,"joinGroup",async e=>{const n=this.pendingJoins.get(e);if(n)return n;if(this.groups.includes(e))return!0;const i=this.invokeJoinGroup(e).finally(()=>{this.pendingJoins.delete(e)});return this.pendingJoins.set(e,i),i});t(this,"invokeJoinGroup",async e=>{this.info(`Joining group "${e}"...`),this.groups.push(e);try{return await this.hubConnection.invoke(a.SignalRMethodName.JoinGroup,e),this.info(`Joined group "${e}"`),!0}catch(n){this.info(`Failed to join group "${e}"`,n);const i=this.groups.indexOf(e);return i>=0&&this.groups.splice(i,1),!1}});t(this,"leaveGroup",async e=>{this.info(`Leaving group "${e}"...`);const n=this.groups.indexOf(e);n>=0&&this.groups.splice(n,1);try{await this.hubConnection.invoke(a.SignalRMethodName.LeaveGroup,e),this.info(`Left group "${e}"`)}catch(i){this.groups.indexOf(e)<0&&this.groups.push(e),this.info(`Failed to leave group "${e}"`,i)}});t(this,"leaveAllGroups",async()=>{this.info(`Leaving all (${this.groups.length}) groups...`);const e=[...this.groups].map(n=>this.leaveGroup(n));await Promise.all(e),this.info("Left all groups")});t(this,"getHubConnectionId",()=>this.hubConnection.connectionId);this.internalEvents=new Map,this.signalREvents=new Map,this.groups=[],e.enableLogging&&(this.logger=e.logger),this.hubConnection=new h.HubConnectionBuilder().withUrl(`${e.signalRApiUrl}/${e.hub}`).configureLogging(h.LogLevel.None).build(),e.serverTimeoutInMilliseconds!=null&&(this.hubConnection.serverTimeoutInMilliseconds=e.serverTimeoutInMilliseconds),e.keepAliveIntervalInMilliseconds!=null&&(this.hubConnection.keepAliveIntervalInMilliseconds=e.keepAliveIntervalInMilliseconds),this.buildInitialListeners()}}module.exports=g;
@@ -1,55 +1,64 @@
1
- var f = Object.defineProperty;
2
- var l = (r, e, t) => e in r ? f(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t;
3
- var n = (r, e, t) => (l(r, typeof e != "symbol" ? e + "" : e, t), t);
4
- import { HubConnectionBuilder as d, LogLevel as u } from "@microsoft/signalr";
1
+ var l = Object.defineProperty;
2
+ var a = (r, e, n) => e in r ? l(r, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : r[e] = n;
3
+ var t = (r, e, n) => (a(r, typeof e != "symbol" ? e + "" : e, n), n);
4
+ import { HubConnectionBuilder as f, LogLevel as d } from "@microsoft/signalr";
5
5
  import { SignalRMethodName as h } from "@ancon/wildcat-types";
6
- import a from "../shared/wait.mjs";
6
+ import u from "../shared/wait.mjs";
7
7
  import g from "../api/generateBackoffWithEqualJitter.mjs";
8
8
  import "axios";
9
9
  import "../number/randomIntFromInterval.mjs";
10
- class $ {
10
+ class w {
11
11
  constructor(e) {
12
- n(this, "internalEvents");
13
- n(this, "signalREvents");
14
- n(this, "hubConnection");
15
- n(this, "clientId");
16
- n(this, "logger");
17
- n(this, "backoff", []);
18
- n(this, "reconnectAttempt", 0);
19
- n(this, "shouldReconnect", !0);
20
- n(this, "groups");
21
- n(this, "info", (e, t) => {
12
+ t(this, "internalEvents");
13
+ t(this, "signalREvents");
14
+ t(this, "hubConnection");
15
+ t(this, "clientId");
16
+ t(this, "logger");
17
+ t(this, "backoff", []);
18
+ t(this, "reconnectAttempt", 0);
19
+ t(this, "shouldReconnect", !0);
20
+ t(this, "isReconnecting", !1);
21
+ t(this, "pendingJoins", /* @__PURE__ */ new Map());
22
+ t(this, "groups");
23
+ t(this, "info", (e, n) => {
22
24
  var i;
23
- (i = this.logger) == null || i.info(e, t);
25
+ (i = this.logger) == null || i.info(e, n);
24
26
  });
25
- n(this, "generateBackoff", () => {
27
+ t(this, "generateBackoff", () => {
26
28
  this.backoff = g(50, 500, 5e3), this.info("Generated new backoff");
27
29
  });
28
- n(this, "reconnect", async () => {
29
- if (this.shouldReconnect)
30
+ t(this, "getNextBackoffMs", () => {
31
+ this.backoff[this.reconnectAttempt] == null && (this.reconnectAttempt > 0 && this.info("Ran out of backoff intervals, restarting backoff..."), this.reconnectAttempt = 0, this.generateBackoff());
32
+ const e = this.backoff[this.reconnectAttempt];
33
+ if (e == null)
34
+ throw new Error("Could not resolve ms from backoff");
35
+ return e;
36
+ });
37
+ /**
38
+ * Keep trying to connect, with backoff, until connected or `disconnect()` is called.
39
+ * Only one reconnect loop runs at a time.
40
+ */
41
+ t(this, "reconnect", async () => {
42
+ if (!this.isReconnecting) {
43
+ this.isReconnecting = !0;
30
44
  try {
31
- this.info("Attempting to reconnect...", {
32
- attempt: this.reconnectAttempt + 1
33
- }), await this.connect(!0), this.info("Reconnected"), this.reconnectAttempt = 0;
34
- } catch {
35
- if (this.backoff[this.reconnectAttempt] != null) {
36
- const t = this.backoff[this.reconnectAttempt];
37
- if (t != null)
38
- await a(t);
39
- else
40
- throw new Error("Could not resolve ms from backoff");
41
- } else {
42
- this.reconnectAttempt > 0 && this.info("Ran out of backoff intervals, restarting backoff..."), this.reconnectAttempt = 0, this.generateBackoff();
43
- const t = this.backoff[this.reconnectAttempt];
44
- if (t != null)
45
- await a(t);
46
- else
47
- throw new Error("Could not resolve ms from backoff");
48
- }
49
- this.reconnectAttempt += 1, await this.reconnect();
45
+ for (; this.shouldReconnect; )
46
+ try {
47
+ this.info("Attempting to reconnect...", {
48
+ attempt: this.reconnectAttempt + 1
49
+ }), await this.connect(!0), this.info("Reconnected"), this.reconnectAttempt = 0;
50
+ return;
51
+ } catch {
52
+ if (!this.shouldReconnect)
53
+ break;
54
+ await u(this.getNextBackoffMs()), this.reconnectAttempt += 1;
55
+ }
56
+ } finally {
57
+ this.isReconnecting = !1;
50
58
  }
59
+ }
51
60
  });
52
- n(this, "buildInitialListeners", () => {
61
+ t(this, "buildInitialListeners", () => {
53
62
  this.hubConnection.onclose(() => {
54
63
  this.groups = [], this.info("Hub connection closed"), this.emitEvent("disconnected"), this.reconnect();
55
64
  }), this.hubConnection.onreconnected(() => this.emitEvent("reconnected"));
@@ -59,33 +68,42 @@ class $ {
59
68
  * @param event Event to emit
60
69
  * @param args Arguments to send to the listeners
61
70
  */
62
- n(this, "emitEvent", (e, ...t) => {
71
+ t(this, "emitEvent", (e, ...n) => {
63
72
  if (this.internalEvents.has(e)) {
64
73
  this.info(`Emitting event "${e}"`);
65
74
  const i = this.internalEvents.get(e);
66
- i && i.forEach((s) => s(...t));
75
+ i && i.forEach((s) => s(...n));
67
76
  } else
68
77
  this.info(`Failed to emit event "${e}". There were no listeners.`);
69
78
  });
70
- n(this, "skipSignal", (e, t) => {
71
- this.info(`Skipped signal "${e}"`, t);
79
+ t(this, "skipSignal", (e, n) => {
80
+ this.info(`Skipped signal "${e}"`, n);
72
81
  });
73
- n(this, "enhanceListener", (e, t, i) => (s) => {
82
+ t(this, "enhanceListener", (e, n, i) => (s) => {
74
83
  const o = JSON.parse(s), c = i && o.clientId && o.clientId === this.clientId;
75
- return c || this.info(`Received signal "${e}"`, s), c ? this.skipSignal(e, s) : t(o);
84
+ return c || this.info(`Received signal "${e}"`, s), c ? this.skipSignal(e, s) : n(o);
76
85
  });
77
- n(this, "setClientId", (e) => {
86
+ t(this, "setClientId", (e) => {
78
87
  this.clientId = e;
79
88
  });
80
- n(this, "connect", async (e = !1) => {
89
+ /**
90
+ * Start the hub connection.
91
+ *
92
+ * @param throwError Rethrow a failed start and do nothing else.
93
+ * Without it, a failed start emits `disconnected` and keeps retrying with backoff
94
+ * until it connects or `disconnect()` is called; the returned promise settles
95
+ * when that happens.
96
+ */
97
+ t(this, "connect", async (e = !1) => {
81
98
  try {
82
99
  this.info("Connecting..."), await this.hubConnection.start(), this.info("Connected"), this.emitEvent("connected");
83
- } catch (t) {
100
+ } catch (n) {
84
101
  if (this.info("Failed to connect"), e)
85
- throw t;
102
+ throw n;
103
+ this.shouldReconnect && (this.emitEvent("disconnected"), await this.reconnect());
86
104
  }
87
105
  });
88
- n(this, "disconnect", async () => {
106
+ t(this, "disconnect", async () => {
89
107
  try {
90
108
  this.shouldReconnect = !1, this.info("Disconnecting..."), await this.hubConnection.stop(), this.info("Disconnected"), this.emitEvent("disconnected");
91
109
  } catch {
@@ -97,20 +115,20 @@ class $ {
97
115
  * @param event Event to listen on
98
116
  * @param listener Event listener function
99
117
  */
100
- n(this, "addEventListener", (e, t) => {
118
+ t(this, "addEventListener", (e, n) => {
101
119
  this.internalEvents.has(e) || this.internalEvents.set(e, []);
102
120
  const i = this.internalEvents.get(e);
103
- return i && i.push(t), () => this.removeEventListener(e, t);
121
+ return i && i.push(n), () => this.removeEventListener(e, n);
104
122
  });
105
123
  /**
106
124
  * Remove internal event listener
107
125
  * @param event Event to stop listening to
108
126
  * @param listener Event listener function
109
127
  */
110
- n(this, "removeEventListener", (e, t) => {
128
+ t(this, "removeEventListener", (e, n) => {
111
129
  var i;
112
130
  if (this.internalEvents.has(e)) {
113
- const s = this.internalEvents.get(e), o = ((i = s == null ? void 0 : s.indexOf) == null ? void 0 : i.call(s, t)) ?? -1;
131
+ const s = this.internalEvents.get(e), o = ((i = s == null ? void 0 : s.indexOf) == null ? void 0 : i.call(s, n)) ?? -1;
114
132
  o >= 0 ? (s.splice(o, 1), this.info(`Removed event listener for event "${e}"`)) : this.info(
115
133
  `Failed to remove event listener for event "${e}". Specified listener was not found.`
116
134
  );
@@ -124,11 +142,11 @@ class $ {
124
142
  * @param signal Signal name
125
143
  * @param listener Signal listener function
126
144
  */
127
- n(this, "addSignalListener", (e, t, i = !0) => {
145
+ t(this, "addSignalListener", (e, n, i = !0) => {
128
146
  this.signalREvents.has(e) || this.signalREvents.set(e, []);
129
147
  const s = this.signalREvents.get(e), o = this.enhanceListener(
130
148
  e,
131
- t,
149
+ n,
132
150
  i
133
151
  );
134
152
  return s && s.push(o), this.hubConnection.on(e, o), this.info(`Added signal listener for signal "${e}"`), () => this.removeSignalListener(e, o);
@@ -138,11 +156,11 @@ class $ {
138
156
  * @param signal Signal name
139
157
  * @param listener Signal listener function
140
158
  */
141
- n(this, "removeSignalListener", (e, t) => {
159
+ t(this, "removeSignalListener", (e, n) => {
142
160
  var i;
143
161
  if (this.signalREvents.has(e)) {
144
- const s = this.signalREvents.get(e), o = ((i = s == null ? void 0 : s.indexOf) == null ? void 0 : i.call(s, t)) ?? -1;
145
- o >= 0 ? (this.hubConnection.off(e, t), s.splice(o, 1), this.info(`Removed signal listener for signal "${e}"`)) : this.info(
162
+ const s = this.signalREvents.get(e), o = ((i = s == null ? void 0 : s.indexOf) == null ? void 0 : i.call(s, n)) ?? -1;
163
+ o >= 0 ? (this.hubConnection.off(e, n), s.splice(o, 1), this.info(`Removed signal listener for signal "${e}"`)) : this.info(
146
164
  `Failed to remove signal listener for signal "${e}". Specified listener was not found.`
147
165
  );
148
166
  } else
@@ -150,34 +168,50 @@ class $ {
150
168
  `Failed to remove signal listener for signal "${e}". Signal doesn't have any listeners.`
151
169
  );
152
170
  });
153
- n(this, "joinGroup", async (e) => {
154
- this.info(`Joining group "${e}"...`);
155
- const t = this.groups.push(e) - 1;
171
+ /**
172
+ * Join a group. A group that is already joined, or being joined, is not joined again.
173
+ * @returns Whether the group is joined
174
+ */
175
+ t(this, "joinGroup", async (e) => {
176
+ const n = this.pendingJoins.get(e);
177
+ if (n)
178
+ return n;
179
+ if (this.groups.includes(e))
180
+ return !0;
181
+ const i = this.invokeJoinGroup(e).finally(() => {
182
+ this.pendingJoins.delete(e);
183
+ });
184
+ return this.pendingJoins.set(e, i), i;
185
+ });
186
+ t(this, "invokeJoinGroup", async (e) => {
187
+ this.info(`Joining group "${e}"...`), this.groups.push(e);
156
188
  try {
157
- await this.hubConnection.invoke(h.JoinGroup, e), this.info(`Joined group "${e}"`);
158
- } catch (i) {
159
- this.info(`Failed to join group "${e}"`, i), t >= 0 && this.groups.splice(t, 1);
189
+ return await this.hubConnection.invoke(h.JoinGroup, e), this.info(`Joined group "${e}"`), !0;
190
+ } catch (n) {
191
+ this.info(`Failed to join group "${e}"`, n);
192
+ const i = this.groups.indexOf(e);
193
+ return i >= 0 && this.groups.splice(i, 1), !1;
160
194
  }
161
195
  });
162
- n(this, "leaveGroup", async (e) => {
196
+ t(this, "leaveGroup", async (e) => {
163
197
  this.info(`Leaving group "${e}"...`);
164
- const t = this.groups.indexOf(e);
165
- t >= 0 && this.groups.splice(t, 1);
198
+ const n = this.groups.indexOf(e);
199
+ n >= 0 && this.groups.splice(n, 1);
166
200
  try {
167
201
  await this.hubConnection.invoke(h.LeaveGroup, e), this.info(`Left group "${e}"`);
168
202
  } catch (i) {
169
203
  this.groups.indexOf(e) < 0 && this.groups.push(e), this.info(`Failed to leave group "${e}"`, i);
170
204
  }
171
205
  });
172
- n(this, "leaveAllGroups", async () => {
206
+ t(this, "leaveAllGroups", async () => {
173
207
  this.info(`Leaving all (${this.groups.length}) groups...`);
174
- const e = [...this.groups].map((t) => this.leaveGroup(t));
208
+ const e = [...this.groups].map((n) => this.leaveGroup(n));
175
209
  await Promise.all(e), this.info("Left all groups");
176
210
  });
177
- n(this, "getHubConnectionId", () => this.hubConnection.connectionId);
178
- this.internalEvents = /* @__PURE__ */ new Map(), this.signalREvents = /* @__PURE__ */ new Map(), this.groups = [], e.enableLogging && (this.logger = e.logger), this.hubConnection = new d().withUrl(`${e.signalRApiUrl}/${e.hub}`).configureLogging(u.None).build(), e.serverTimeoutInMilliseconds && (this.hubConnection.serverTimeoutInMilliseconds = e.serverTimeoutInMilliseconds), this.buildInitialListeners();
211
+ t(this, "getHubConnectionId", () => this.hubConnection.connectionId);
212
+ this.internalEvents = /* @__PURE__ */ new Map(), this.signalREvents = /* @__PURE__ */ new Map(), this.groups = [], e.enableLogging && (this.logger = e.logger), this.hubConnection = new f().withUrl(`${e.signalRApiUrl}/${e.hub}`).configureLogging(d.None).build(), e.serverTimeoutInMilliseconds != null && (this.hubConnection.serverTimeoutInMilliseconds = e.serverTimeoutInMilliseconds), e.keepAliveIntervalInMilliseconds != null && (this.hubConnection.keepAliveIntervalInMilliseconds = e.keepAliveIntervalInMilliseconds), this.buildInitialListeners();
179
213
  }
180
214
  }
181
215
  export {
182
- $ as default
216
+ w as default
183
217
  };
@@ -19,7 +19,7 @@ declare type ReduxHooksArg = Partial<{
19
19
  declare function createUseSignalRHook<RootState = unknown>(signalRConfig: SignalRHookConfig, selectors?: ReduxSelectorsArg<RootState>, actions?: ReduxActionsArg, hooks?: ReduxHooksArg): {
20
20
  useSignalR: (hub: SignalRHubName) => {
21
21
  isHubConnected: boolean;
22
- join: (group: string) => Promise<void>;
22
+ join: (group: string) => Promise<boolean>;
23
23
  leave: (group: string) => Promise<void>;
24
24
  subscribe: (signal: SignalRSignalName, listener: SignalREventListener, shouldSkipOwnClient?: boolean) => (() => void);
25
25
  unsubscribe: (signal: SignalRSignalName, listener: SignalREventListener) => void;
@@ -1 +1 @@
1
- "use strict";const n=require("react"),h=require("react-redux"),C=require("../noop-7ea3b37b.js"),B=a=>Object.freeze(Object.defineProperty({__proto__:null,default:a},Symbol.toStringTag,{value:"Module"}));function F(a,_,g,j){const{logger:q,enableLogging:x}=a;let{signalRApiUrl:I}=a;const{clientIdSelector:D,isSignalROnlineSelector:s}=_??{},{setIsSignalROnlineAction:l}=g??{},{useAppStore:G=h.useStore,useAppDispatch:m=h.useDispatch,useAppSelector:M=h.useSelector}=j??{},b=new Set;function P(o){const[f,z]=n.useState(I),[e,N]=n.useState(null),d=G(),p=m(),E=M(D??(()=>{})),[u,T]=n.useState(!1),[r,v]=n.useState(!1),O=n.useRef(u),S=n.useCallback(()=>{(s==null?void 0:s(d.getState()))===!1&&l&&p(l({isSignalROnline:!0})),r||v(!0)},[p,r,d]),k=S,H=n.useCallback(()=>{(s==null?void 0:s(d.getState()))===!0&&l&&p(l({isSignalROnline:!1})),r&&v(!1)},[p,r,d]),y=n.useCallback(async t=>{e&&e.groups.indexOf(t)<0&&await(e==null?void 0:e.joinGroup(t))},[e]),A=n.useCallback(async t=>{e&&e.groups.indexOf(t)>=0&&await(e==null?void 0:e.leaveGroup(t))},[e]),L=n.useCallback((t,c,i)=>e?e==null?void 0:e.addSignalListener(t,c,i):C.noop,[e]),U=n.useCallback((t,c)=>{e&&e.removeSignalListener(t,c)},[e]),w=n.useCallback(()=>e?e.getHubConnectionId():null,[e]);return n.useEffect(()=>{let t=!1;return Promise.resolve().then(()=>B(require("./SignalR.js"))).then(({default:c})=>{t||N(new c({signalRApiUrl:f,hub:o,logger:q,enableLogging:x}))}),()=>{t=!0}},[o,f]),n.useEffect(()=>{function t(c){z(c)}return b.add(t),()=>{b.delete(t)}},[]),n.useEffect(()=>{O.current=u},[u]),n.useEffect(()=>{const t=e==null?void 0:e.addEventListener("connected",S),c=e==null?void 0:e.addEventListener("reconnected",k),i=e==null?void 0:e.addEventListener("disconnected",H);return e&&!O.current&&T(!0),()=>{t==null||t(),c==null||c(),i==null||i()}},[e,S,H,k]),n.useEffect(()=>{e==null||e.setClientId(E||void 0)},[e,E]),n.useEffect(()=>{async function t(){await(e==null?void 0:e.connect())}u&&t()},[e,u]),n.useEffect(()=>()=>{e==null||e.leaveAllGroups().then(()=>{e==null||e.disconnect()}).catch(C.noop).finally(()=>{e==null||e.disconnect().catch(C.noop)})},[e]),n.useMemo(()=>({isHubConnected:r,join:y,leave:A,subscribe:L,unsubscribe:U,getHubConnectionId:w}),[r,y,A,L,U,w])}return{useSignalR:P,setUrl(o){I=o,b.forEach(f=>{f(o)})}}}module.exports=F;
1
+ "use strict";const n=require("react"),I=require("react-redux"),h=require("../noop-7ea3b37b.js"),J=l=>Object.freeze(Object.defineProperty({__proto__:null,default:l},Symbol.toStringTag,{value:"Module"}));function K(l,_,j,q){const{logger:w,enableLogging:D,serverTimeoutInMilliseconds:M,keepAliveIntervalInMilliseconds:m}=l;let{signalRApiUrl:v}=l;const{clientIdSelector:x,isSignalROnlineSelector:c}=_??{},{setIsSignalROnlineAction:a}=j??{},{useAppStore:G=I.useStore,useAppDispatch:P=I.useDispatch,useAppSelector:T=I.useSelector}=q??{},b=new Set;function z(o){const[f,N]=n.useState(v),[e,B]=n.useState(null),d=G(),p=P(),C=T(x??(()=>{})),[u,F]=n.useState(!1),[r,E]=n.useState(!1),k=n.useRef(u),S=n.useCallback(()=>{(c==null?void 0:c(d.getState()))===!1&&a&&p(a({isSignalROnline:!0})),r||E(!0)},[p,r,d]),A=S,H=n.useCallback(()=>{(c==null?void 0:c(d.getState()))===!0&&a&&p(a({isSignalROnline:!1})),r&&E(!1)},[p,r,d]),O=n.useCallback(async t=>e?e.joinGroup(t):!1,[e]),y=n.useCallback(async t=>{e&&e.groups.indexOf(t)>=0&&await(e==null?void 0:e.leaveGroup(t))},[e]),L=n.useCallback((t,s,i)=>e?e==null?void 0:e.addSignalListener(t,s,i):h.noop,[e]),U=n.useCallback((t,s)=>{e&&e.removeSignalListener(t,s)},[e]),g=n.useCallback(()=>e?e.getHubConnectionId():null,[e]);return n.useEffect(()=>{let t=!1;return Promise.resolve().then(()=>J(require("./SignalR.js"))).then(({default:s})=>{t||B(new s({signalRApiUrl:f,hub:o,logger:w,enableLogging:D,serverTimeoutInMilliseconds:M,keepAliveIntervalInMilliseconds:m}))}),()=>{t=!0}},[o,f]),n.useEffect(()=>{function t(s){N(s)}return b.add(t),()=>{b.delete(t)}},[]),n.useEffect(()=>{k.current=u},[u]),n.useEffect(()=>{const t=e==null?void 0:e.addEventListener("connected",S),s=e==null?void 0:e.addEventListener("reconnected",A),i=e==null?void 0:e.addEventListener("disconnected",H);return e&&!k.current&&F(!0),()=>{t==null||t(),s==null||s(),i==null||i()}},[e,S,H,A]),n.useEffect(()=>{e==null||e.setClientId(C||void 0)},[e,C]),n.useEffect(()=>{async function t(){await(e==null?void 0:e.connect())}u&&t()},[e,u]),n.useEffect(()=>()=>{e==null||e.leaveAllGroups().then(()=>{e==null||e.disconnect()}).catch(h.noop).finally(()=>{e==null||e.disconnect().catch(h.noop)})},[e]),n.useMemo(()=>({isHubConnected:r,join:O,leave:y,subscribe:L,unsubscribe:U,getHubConnectionId:g}),[r,O,y,L,U,g])}return{useSignalR:z,setUrl(o){v=o,b.forEach(f=>{f(o)})}}}module.exports=K;