@zeniai/client-epic-state 5.0.33 → 5.0.34-betaRD1

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/lib/esm/init.js CHANGED
@@ -23,14 +23,19 @@ export default function initialize(restEndPoints, userId, sessionId, tenantId, i
23
23
  return store;
24
24
  }
25
25
  let isPusherInitialized = false;
26
+ // Caches an in-flight initializePusher() promise so that concurrent callers
27
+ // share a single Pusher instance instead of each constructing their own and
28
+ // leaking WebSocket connections (see Bugbot review on PR #2983). Cleared in
29
+ // the IIFE's `finally` once construction settles.
30
+ let pusherInitPromise;
26
31
  /**
27
32
  * Call initializePusher before using pusher in web-app
28
33
  */
29
- export function initializePusher(pusherClientSecret, options, headers, reInitialize = false) {
34
+ export async function initializePusher(pusherClientSecret, options, headers, reInitialize = false) {
30
35
  // Pusher subscribes/decrypts only make sense in the browser. `pusher-js/
31
36
  // with-encryption` resolves to a browser-only bundle that references
32
- // `window` at module init, so even *requiring* it on the server crashes.
33
- // Bail out early on SSR/Node so loading this module never triggers that.
37
+ // `window` at module init, so even *importing* it on the server crashes.
38
+ // Bail out early on SSR/Node so the dynamic import below never executes.
34
39
  if (typeof window === 'undefined') {
35
40
  console.warn(`initializePusher called on server-side; pusher-js/with-encryption is browser-only — skipping.`);
36
41
  return undefined;
@@ -45,27 +50,59 @@ export function initializePusher(pusherClientSecret, options, headers, reInitial
45
50
  console.warn(`Already initialized pusher`);
46
51
  return pusher;
47
52
  }
48
- // Lazy-require so the browser-only bundle is loaded only when this function
49
- // actually runs (browser path). The pusher-js UMD wrapper does
50
- // `module.exports = factory()` for CJS, so the require result is the
51
- // Pusher class directly. Some bundlers wrap CJS in `{ default: ... }` for
52
- // ESM interop fall back to the module itself when `.default` is absent.
53
- // eslint-disable-next-line @typescript-eslint/no-require-imports
54
- const pusherModule = require('pusher-js/with-encryption');
55
- const PusherConstructor = 'default' in pusherModule ? pusherModule.default : pusherModule;
56
- const endpoint = `${zeniAPI.apiEndPoints.tenantMicroServiceBaseUrl}/1.0/notifications/push_notification/auth`;
57
- pusher = new PusherConstructor(pusherClientSecret, {
58
- ...options,
59
- channelAuthorization: {
60
- endpoint,
61
- transport: 'ajax',
62
- customHandler: (params, callback) => customHandler(params, headers, callback),
63
- },
64
- }).bind('error', function (err) {
65
- console.warn('Pusher error', err);
66
- });
67
- console.info(`initializing with ${JSON.stringify(options)}`);
68
- return pusher;
53
+ // De-dupe concurrent in-flight calls so we don't construct multiple Pusher
54
+ // instances (each one a live WebSocket) and leak the older ones. We don't
55
+ // de-dupe when reInitialize=true that's the caller asking for a fresh
56
+ // instance, which is the existing contract.
57
+ if (pusherInitPromise && !reInitialize) {
58
+ return pusherInitPromise;
59
+ }
60
+ // The IIFE captures `currentInit` so that, when its `finally` runs, it can
61
+ // identity-check before clearing the module-level `pusherInitPromise`. This
62
+ // matters when a reInitialize=true call overwrites `pusherInitPromise`
63
+ // while we're still in flight: without the identity check, our finally
64
+ // would clobber the newer call's slot and the next concurrent caller
65
+ // would bypass the dedup guard. Capture is safe because the first action
66
+ // inside the try is `await import(...)`, which always yields control —
67
+ // so the finally runs in a future microtask, after `currentInit` has
68
+ // already been assigned below. We declare it as `let … | undefined` so
69
+ // TS's definite-assignment analysis (which doesn't model the await) accepts
70
+ // the closure read; at runtime it's always the IIFE promise by then.
71
+ let currentInit = undefined;
72
+ currentInit = (async () => {
73
+ try {
74
+ // Dynamic import so the browser-only bundle is loaded only when this
75
+ // function actually runs (browser path). Works in both build outputs:
76
+ // • ESM (lib/esm): preserved as native `import()` → Vite/Rollup code-split
77
+ // • CJS (lib): TypeScript lowers to `Promise.resolve().then(() => require(...))`
78
+ // The pusher-js UMD wrapper does `module.exports = factory()` for CJS,
79
+ // so the module result is the Pusher class directly. Some bundlers wrap
80
+ // CJS in `{ default: ... }` for ESM interop — fall back to the module
81
+ // itself when `.default` is absent.
82
+ const pusherModule = (await import('pusher-js/with-encryption'));
83
+ const PusherConstructor = 'default' in pusherModule ? pusherModule.default : pusherModule;
84
+ const endpoint = `${zeniAPI.apiEndPoints.tenantMicroServiceBaseUrl}/1.0/notifications/push_notification/auth`;
85
+ pusher = new PusherConstructor(pusherClientSecret, {
86
+ ...options,
87
+ channelAuthorization: {
88
+ endpoint,
89
+ transport: 'ajax',
90
+ customHandler: (params, callback) => customHandler(params, headers, callback),
91
+ },
92
+ }).bind('error', function (err) {
93
+ console.warn('Pusher error', err);
94
+ });
95
+ console.info(`initializing with ${JSON.stringify(options)}`);
96
+ return pusher;
97
+ }
98
+ finally {
99
+ if (pusherInitPromise === currentInit) {
100
+ pusherInitPromise = undefined;
101
+ }
102
+ }
103
+ })();
104
+ pusherInitPromise = currentInit;
105
+ return currentInit;
69
106
  }
70
107
  const customHandler = async (params, headers, callback) => {
71
108
  const { socketId, channelName } = params;
@@ -1,5 +1,5 @@
1
1
  import { from, of } from 'rxjs';
2
- import { catchError, concatMap, filter, mergeMap, switchMap, } from 'rxjs/operators';
2
+ import { catchError, concatMap, exhaustMap, filter, mergeMap, } from 'rxjs/operators';
3
3
  import { openSnackbar } from '../../../entity/snackbar/snackbarReducer';
4
4
  import { createZeniAPIStatus } from '../../../responsePayload';
5
5
  import { approveOAuthConsent, approveOAuthConsentFailure, approveOAuthConsentSuccess, } from '../zeniOAuthReducer';
@@ -9,10 +9,11 @@ const failureSnackbar = (reason) => openSnackbar({
9
9
  type: 'error',
10
10
  variables: [{ variableName: '__reason__', variableValue: reason }],
11
11
  });
12
- export const approveOAuthConsentEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(approveOAuthConsent.match), switchMap((action) => {
13
- if (state$.value.zeniOAuthViewState.fetchState === 'In-Progress') {
14
- return from([]);
15
- }
12
+ export const approveOAuthConsentEpic = (actions$, _state$, zeniAPI) => actions$.pipe(filter(approveOAuthConsent.match),
13
+ // `approveOAuthConsent` reducer sets fetchState to In-Progress before epics
14
+ // run, so a guard on In-Progress would block every legitimate request.
15
+ // exhaustMap drops duplicate approve clicks while the HTTP call is in flight.
16
+ exhaustMap((action) => {
16
17
  const { userId, zeniSessionId, tenantId, clientId, redirectUri, codeChallenge, codeChallengeMethod, state, responseType, } = action.payload;
17
18
  const authHeaders = {
18
19
  'zeni-user-id': userId,
package/lib/init.d.ts CHANGED
@@ -26,7 +26,7 @@ export declare function initializePusher(pusherClientSecret: ID, options: Option
26
26
  sessionId: ID;
27
27
  tenantId: ID;
28
28
  userId: ID;
29
- }, reInitialize?: boolean): Pusher | undefined;
29
+ }, reInitialize?: boolean): Promise<Pusher | undefined>;
30
30
  export declare function disconnectPusher(): void;
31
31
  export { pusher };
32
32
  export { injectFeatureModules, injectFeatureEpics } from './configureStore';
package/lib/init.js CHANGED
@@ -67,14 +67,19 @@ function initialize(restEndPoints, userId, sessionId, tenantId, isSandboxEnv, on
67
67
  return exports.store;
68
68
  }
69
69
  let isPusherInitialized = false;
70
+ // Caches an in-flight initializePusher() promise so that concurrent callers
71
+ // share a single Pusher instance instead of each constructing their own and
72
+ // leaking WebSocket connections (see Bugbot review on PR #2983). Cleared in
73
+ // the IIFE's `finally` once construction settles.
74
+ let pusherInitPromise;
70
75
  /**
71
76
  * Call initializePusher before using pusher in web-app
72
77
  */
73
- function initializePusher(pusherClientSecret, options, headers, reInitialize = false) {
78
+ async function initializePusher(pusherClientSecret, options, headers, reInitialize = false) {
74
79
  // Pusher subscribes/decrypts only make sense in the browser. `pusher-js/
75
80
  // with-encryption` resolves to a browser-only bundle that references
76
- // `window` at module init, so even *requiring* it on the server crashes.
77
- // Bail out early on SSR/Node so loading this module never triggers that.
81
+ // `window` at module init, so even *importing* it on the server crashes.
82
+ // Bail out early on SSR/Node so the dynamic import below never executes.
78
83
  if (typeof window === 'undefined') {
79
84
  console.warn(`initializePusher called on server-side; pusher-js/with-encryption is browser-only — skipping.`);
80
85
  return undefined;
@@ -89,27 +94,59 @@ function initializePusher(pusherClientSecret, options, headers, reInitialize = f
89
94
  console.warn(`Already initialized pusher`);
90
95
  return pusher;
91
96
  }
92
- // Lazy-require so the browser-only bundle is loaded only when this function
93
- // actually runs (browser path). The pusher-js UMD wrapper does
94
- // `module.exports = factory()` for CJS, so the require result is the
95
- // Pusher class directly. Some bundlers wrap CJS in `{ default: ... }` for
96
- // ESM interop fall back to the module itself when `.default` is absent.
97
- // eslint-disable-next-line @typescript-eslint/no-require-imports
98
- const pusherModule = require('pusher-js/with-encryption');
99
- const PusherConstructor = 'default' in pusherModule ? pusherModule.default : pusherModule;
100
- const endpoint = `${exports.zeniAPI.apiEndPoints.tenantMicroServiceBaseUrl}/1.0/notifications/push_notification/auth`;
101
- exports.pusher = pusher = new PusherConstructor(pusherClientSecret, {
102
- ...options,
103
- channelAuthorization: {
104
- endpoint,
105
- transport: 'ajax',
106
- customHandler: (params, callback) => customHandler(params, headers, callback),
107
- },
108
- }).bind('error', function (err) {
109
- console.warn('Pusher error', err);
110
- });
111
- console.info(`initializing with ${JSON.stringify(options)}`);
112
- return pusher;
97
+ // De-dupe concurrent in-flight calls so we don't construct multiple Pusher
98
+ // instances (each one a live WebSocket) and leak the older ones. We don't
99
+ // de-dupe when reInitialize=true that's the caller asking for a fresh
100
+ // instance, which is the existing contract.
101
+ if (pusherInitPromise && !reInitialize) {
102
+ return pusherInitPromise;
103
+ }
104
+ // The IIFE captures `currentInit` so that, when its `finally` runs, it can
105
+ // identity-check before clearing the module-level `pusherInitPromise`. This
106
+ // matters when a reInitialize=true call overwrites `pusherInitPromise`
107
+ // while we're still in flight: without the identity check, our finally
108
+ // would clobber the newer call's slot and the next concurrent caller
109
+ // would bypass the dedup guard. Capture is safe because the first action
110
+ // inside the try is `await import(...)`, which always yields control —
111
+ // so the finally runs in a future microtask, after `currentInit` has
112
+ // already been assigned below. We declare it as `let … | undefined` so
113
+ // TS's definite-assignment analysis (which doesn't model the await) accepts
114
+ // the closure read; at runtime it's always the IIFE promise by then.
115
+ let currentInit = undefined;
116
+ currentInit = (async () => {
117
+ try {
118
+ // Dynamic import so the browser-only bundle is loaded only when this
119
+ // function actually runs (browser path). Works in both build outputs:
120
+ // • ESM (lib/esm): preserved as native `import()` → Vite/Rollup code-split
121
+ // • CJS (lib): TypeScript lowers to `Promise.resolve().then(() => require(...))`
122
+ // The pusher-js UMD wrapper does `module.exports = factory()` for CJS,
123
+ // so the module result is the Pusher class directly. Some bundlers wrap
124
+ // CJS in `{ default: ... }` for ESM interop — fall back to the module
125
+ // itself when `.default` is absent.
126
+ const pusherModule = (await Promise.resolve().then(() => __importStar(require('pusher-js/with-encryption'))));
127
+ const PusherConstructor = 'default' in pusherModule ? pusherModule.default : pusherModule;
128
+ const endpoint = `${exports.zeniAPI.apiEndPoints.tenantMicroServiceBaseUrl}/1.0/notifications/push_notification/auth`;
129
+ exports.pusher = pusher = new PusherConstructor(pusherClientSecret, {
130
+ ...options,
131
+ channelAuthorization: {
132
+ endpoint,
133
+ transport: 'ajax',
134
+ customHandler: (params, callback) => customHandler(params, headers, callback),
135
+ },
136
+ }).bind('error', function (err) {
137
+ console.warn('Pusher error', err);
138
+ });
139
+ console.info(`initializing with ${JSON.stringify(options)}`);
140
+ return pusher;
141
+ }
142
+ finally {
143
+ if (pusherInitPromise === currentInit) {
144
+ pusherInitPromise = undefined;
145
+ }
146
+ }
147
+ })();
148
+ pusherInitPromise = currentInit;
149
+ return currentInit;
113
150
  }
114
151
  const customHandler = async (params, headers, callback) => {
115
152
  const { socketId, channelName } = params;