@microsoft/omnichannel-chat-widget 2.0.1-main.84e2c02 → 2.0.1-main.a610fd8

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 (35) hide show
  1. package/README.md +57 -0
  2. package/lib/cjs/common/telemetry/TelemetryConstants.js +6 -0
  3. package/lib/cjs/components/chatbuttonstateful/ChatButtonStateful.js +42 -25
  4. package/lib/cjs/components/livechatwidget/common/endChat.js +39 -0
  5. package/lib/cjs/components/livechatwidget/common/initWebChatComposer.js +33 -9
  6. package/lib/cjs/components/livechatwidget/common/reconnectChatHelper.js +29 -1
  7. package/lib/cjs/components/livechatwidget/common/startChat.js +118 -36
  8. package/lib/cjs/components/livechatwidget/common/updateSessionDataForTelemetry.js +34 -5
  9. package/lib/cjs/components/livechatwidget/livechatwidgetstateful/LiveChatWidgetStateful.js +5 -17
  10. package/lib/cjs/components/webchatcontainerstateful/common/defaultProps/defaultMiddlewareLocalizedTexts.js +2 -1
  11. package/lib/cjs/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.js +159 -0
  12. package/lib/cjs/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachments/AdaptiveCardAccessibilityWrapper.js +16 -2
  13. package/lib/cjs/components/webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentSentAnnouncementMiddleware.js +68 -40
  14. package/lib/cjs/components/webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentUploadValidatorMiddleware.js +0 -27
  15. package/lib/esm/common/telemetry/TelemetryConstants.js +6 -0
  16. package/lib/esm/components/chatbuttonstateful/ChatButtonStateful.js +42 -25
  17. package/lib/esm/components/livechatwidget/common/endChat.js +39 -0
  18. package/lib/esm/components/livechatwidget/common/initWebChatComposer.js +31 -9
  19. package/lib/esm/components/livechatwidget/common/reconnectChatHelper.js +28 -1
  20. package/lib/esm/components/livechatwidget/common/startChat.js +115 -34
  21. package/lib/esm/components/livechatwidget/common/updateSessionDataForTelemetry.js +34 -5
  22. package/lib/esm/components/livechatwidget/livechatwidgetstateful/LiveChatWidgetStateful.js +6 -18
  23. package/lib/esm/components/webchatcontainerstateful/common/defaultProps/defaultMiddlewareLocalizedTexts.js +2 -1
  24. package/lib/esm/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.js +153 -0
  25. package/lib/esm/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachments/AdaptiveCardAccessibilityWrapper.js +16 -2
  26. package/lib/esm/components/webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentSentAnnouncementMiddleware.js +65 -39
  27. package/lib/esm/components/webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentUploadValidatorMiddleware.js +0 -27
  28. package/lib/types/common/telemetry/TelemetryConstants.d.ts +3 -0
  29. package/lib/types/components/livechatwidget/common/initWebChatComposer.d.ts +8 -0
  30. package/lib/types/components/livechatwidget/common/reconnectChatHelper.d.ts +6 -1
  31. package/lib/types/components/livechatwidget/common/startChat.d.ts +5 -1
  32. package/lib/types/components/webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware.d.ts +11 -0
  33. package/lib/types/components/webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentSentAnnouncementMiddleware.d.ts +11 -4
  34. package/lib/types/contexts/common/ILiveChatWidgetLocalizedTexts.d.ts +9 -2
  35. package/package.json +5 -6
@@ -349,14 +349,53 @@ export const closeChatStateCleanUp = dispatch => {
349
349
  });
350
350
  };
351
351
 
352
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
353
+ const logCleanUpDisconnectFailure = error => {
354
+ TelemetryHelper.logActionEvent(LogLevel.WARN, {
355
+ Event: TelemetryEvent.ChatSDKStateCleanUpDisconnectFailed,
356
+ Description: "Failed to disconnect the previous conversation during chat SDK state clean up.",
357
+ ExceptionDetails: {
358
+ exception: (error === null || error === void 0 ? void 0 : error.message) ?? error
359
+ }
360
+ });
361
+ };
362
+
363
+ // Releases the previous session's conversation. Mirrors the cleanup OmnichannelChatSDK.endChat()
364
+ // runs in its finally block (disconnect, then drop the reference). Without it, a conversation
365
+ // left over from a failed or orphaned start chat, or from a chat ended in another tab (which
366
+ // skips the SDK endChat), keeps its messaging session open and leaks into the next chat.
367
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
368
+ const disconnectConversation = chatSDK => {
369
+ const conversation = chatSDK.conversation;
370
+ if (!conversation || typeof conversation.disconnect !== "function") {
371
+ return;
372
+ }
373
+ try {
374
+ // ACS conversations disconnect asynchronously; legacy IC3 conversations may not return a promise.
375
+ const result = conversation.disconnect();
376
+ if (result && typeof result.catch === "function") {
377
+ result.catch(logCleanUpDisconnectFailure);
378
+ }
379
+ } catch (error) {
380
+ logCleanUpDisconnectFailure(error);
381
+ }
382
+ };
383
+
352
384
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
353
385
  export const chatSDKStateCleanUp = chatSDK => {
386
+ if (!chatSDK) {
387
+ return;
388
+ }
389
+
354
390
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
391
  chatSDK.requestId = uuidv4();
356
392
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
393
  chatSDK.chatToken = {};
358
394
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
359
395
  chatSDK.reconnectId = null;
396
+ disconnectConversation(chatSDK);
397
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
398
+ chatSDK.conversation = null;
360
399
  };
361
400
 
362
401
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -11,10 +11,11 @@ import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidge
11
11
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
12
12
  import { WebChatStoreLoader } from "../../webchatcontainerstateful/webchatcontroller/WebChatStoreLoader";
13
13
  import attachmentProcessingMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentProcessingMiddleware";
14
- import attachmentSentAnnouncementMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentSentAnnouncementMiddleware";
14
+ import createAttachmentSentAnnouncementMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentSentAnnouncementMiddleware";
15
15
  import channelDataMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/channelDataMiddleware";
16
16
  import { createActivityMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityMiddleware";
17
17
  import { createActivityStatusMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/activityStatusMiddleware";
18
+ import { createAttachmentForScreenReaderMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentForScreenReaderMiddleware";
18
19
  import { createAttachmentMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/attachmentMiddleware";
19
20
  import createAttachmentUploadValidatorMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/attachmentUploadValidatorMiddleware";
20
21
  import { createAvatarMiddleware } from "../../webchatcontainerstateful/webchatcontroller/middlewares/renderingmiddlewares/avatarMiddleware";
@@ -42,6 +43,31 @@ import htmlPlayerMiddleware from "../../webchatcontainerstateful/webchatcontroll
42
43
  import htmlTextMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/htmlTextMiddleware";
43
44
  import preProcessingMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/preProcessingMiddleware";
44
45
  import sanitizationMiddleware from "../../webchatcontainerstateful/webchatcontroller/middlewares/storemiddlewares/sanitizationMiddleware";
46
+ const markdownSanitizeConfig = {
47
+ FORBID_TAGS: ["form", "button", "script", "div", "input"],
48
+ FORBID_ATTR: ["action"],
49
+ ADD_ATTR: ["target"]
50
+ };
51
+
52
+ /**
53
+ * Renders Markdown for the screen reader text of Adaptive Cards, from the same pieces as the visible card:
54
+ * the host renderMarkdown when set, the hyperlink text override, and the same sanitization.
55
+ * Markdown is always formatted, also when the widget shows Markdown unformatted, so that screen readers do not read the syntax.
56
+ * Styles are removed with their content because the card does not show them.
57
+ */
58
+ export const createScreenReaderMarkdownRenderer = webChatContainerProps => {
59
+ var _webChatContainerProp;
60
+ const hostRenderMarkdown = webChatContainerProps === null || webChatContainerProps === void 0 || (_webChatContainerProp = webChatContainerProps.webChatProps) === null || _webChatContainerProp === void 0 ? void 0 : _webChatContainerProp.renderMarkdown;
61
+ const markdown = createMarkdown(false, (webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.disableNewLineMarkdownSupport) ?? defaultWebChatContainerStatefulProps.disableNewLineMarkdownSupport, webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.opensMarkdownLinksInSameTab);
62
+ const hyperlinkTextOverrideRenderer = new HyperlinkTextOverrideRenderer((webChatContainerProps === null || webChatContainerProps === void 0 ? void 0 : webChatContainerProps.hyperlinkTextOverride) ?? defaultWebChatContainerStatefulProps.hyperlinkTextOverride);
63
+ return text => {
64
+ const html = hostRenderMarkdown ? hostRenderMarkdown(text) : markdown.render(text);
65
+ return DOMPurify.sanitize(hyperlinkTextOverrideRenderer.render(html), {
66
+ ...markdownSanitizeConfig,
67
+ FORBID_TAGS: [...markdownSanitizeConfig.FORBID_TAGS, "style"]
68
+ });
69
+ };
70
+ };
45
71
 
46
72
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
73
  export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endChat) => {
@@ -62,7 +88,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
62
88
  // Initialize Web Chat's redux store
63
89
  let webChatStore = WebChatStoreLoader.store;
64
90
  if (!webChatStore) {
65
- var _state$domainStates$l, _state$domainStates$l2, _state$domainStates$l3, _props$webChatContain7;
91
+ var _state$domainStates$l, _state$domainStates$l2, _props$controlProps, _state$domainStates$l3, _props$webChatContain7;
66
92
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
67
93
  const addConversationalSurveyTagsCallback = action => {
68
94
  var _inMemoryState$appSta;
@@ -121,7 +147,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
121
147
  };
122
148
  webChatStore = createStore({},
123
149
  //initial state
124
- preProcessingMiddleware, attachmentProcessingMiddleware, createAttachmentUploadValidatorMiddleware((_state$domainStates$l = state.domainStates.liveChatConfig) === null || _state$domainStates$l === void 0 ? void 0 : _state$domainStates$l.allowedFileExtensions, (_state$domainStates$l2 = state.domainStates.liveChatConfig) === null || _state$domainStates$l2 === void 0 ? void 0 : _state$domainStates$l2.maxUploadFileSize, localizedTexts), attachmentSentAnnouncementMiddleware, createCustomEventMiddleware(BroadcastService), createQueueOverflowMiddleware(state, dispatch), channelDataMiddleware(addConversationalSurveyTagsCallback), createConversationEndMiddleware(conversationEndCallback, startConversationalSurveyCallback, endConversationalSurveyCallback), createDataMaskingMiddleware((_state$domainStates$l3 = state.domainStates.liveChatConfig) === null || _state$domainStates$l3 === void 0 ? void 0 : _state$domainStates$l3.DataMaskingInfo), createMessageTimeStampMiddleware, createMessageSequenceIdOverrideMiddleware, createCitationsMiddleware(state, dispatch), gifUploadMiddleware, htmlPlayerMiddleware, htmlTextMiddleware(honorsTargetInHTMLLinks), createMaxMessageSizeValidator(localizedTexts), sanitizationMiddleware, createCallActionMiddleware(),
150
+ preProcessingMiddleware, attachmentProcessingMiddleware, createAttachmentUploadValidatorMiddleware((_state$domainStates$l = state.domainStates.liveChatConfig) === null || _state$domainStates$l === void 0 ? void 0 : _state$domainStates$l.allowedFileExtensions, (_state$domainStates$l2 = state.domainStates.liveChatConfig) === null || _state$domainStates$l2 === void 0 ? void 0 : _state$domainStates$l2.maxUploadFileSize, localizedTexts), createAttachmentSentAnnouncementMiddleware(localizedTexts, ((_props$controlProps = props.controlProps) === null || _props$controlProps === void 0 ? void 0 : _props$controlProps.id) || "oc-lcw"), createCustomEventMiddleware(BroadcastService), createQueueOverflowMiddleware(state, dispatch), channelDataMiddleware(addConversationalSurveyTagsCallback), createConversationEndMiddleware(conversationEndCallback, startConversationalSurveyCallback, endConversationalSurveyCallback), createDataMaskingMiddleware((_state$domainStates$l3 = state.domainStates.liveChatConfig) === null || _state$domainStates$l3 === void 0 ? void 0 : _state$domainStates$l3.DataMaskingInfo), createMessageTimeStampMiddleware, createMessageSequenceIdOverrideMiddleware, createCitationsMiddleware(state, dispatch), gifUploadMiddleware, htmlPlayerMiddleware, htmlTextMiddleware(honorsTargetInHTMLLinks), createMaxMessageSizeValidator(localizedTexts), sanitizationMiddleware, createCallActionMiddleware(),
125
151
  // Pass a callback so middleware can push initials into React context for reactivity
126
152
  localizedStringsBotInitialsMiddleware(initials => {
127
153
  dispatch({
@@ -149,12 +175,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
149
175
  });
150
176
 
151
177
  // EXISTING sanitization (continues to work as before)
152
- const config = {
153
- FORBID_TAGS: ["form", "button", "script", "div", "input"],
154
- FORBID_ATTR: ["action"],
155
- ADD_ATTR: ["target"]
156
- };
157
- text = DOMPurify.sanitize(text, config);
178
+ text = DOMPurify.sanitize(text, markdownSanitizeConfig);
158
179
 
159
180
  // MONITOR-ONLY: Test what the stricter allowlist would remove (Phase 1)
160
181
  // This does NOT modify the text, only logs telemetry
@@ -358,6 +379,7 @@ export const initWebChatComposer = (props, state, dispatch, facadeChatSDK, endCh
358
379
  store: webChatStore,
359
380
  activityMiddleware: (_props$webChatContain0 = props.webChatContainerProps) !== null && _props$webChatContain0 !== void 0 && (_props$webChatContain0 = _props$webChatContain0.renderingMiddlewareProps) !== null && _props$webChatContain0 !== void 0 && _props$webChatContain0.disableActivityMiddleware ? undefined : createActivityMiddleware(renderMarkdown, (_state$domainStates$r = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r === void 0 ? void 0 : _state$domainStates$r.systemMessageStyleProps, (_state$domainStates$r2 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r2 === void 0 ? void 0 : _state$domainStates$r2.userMessageStyleProps, localizedTexts),
360
381
  attachmentMiddleware: (_props$webChatContain1 = props.webChatContainerProps) !== null && _props$webChatContain1 !== void 0 && (_props$webChatContain1 = _props$webChatContain1.renderingMiddlewareProps) !== null && _props$webChatContain1 !== void 0 && _props$webChatContain1.disableAttachmentMiddleware ? undefined : createAttachmentMiddleware(((_state$domainStates$r3 = state.domainStates.renderingMiddlewareProps) === null || _state$domainStates$r3 === void 0 || (_state$domainStates$r3 = _state$domainStates$r3.attachmentProps) === null || _state$domainStates$r3 === void 0 ? void 0 : _state$domainStates$r3.enableInlinePlaying) ?? defaultAttachmentProps.enableInlinePlaying),
382
+ attachmentForScreenReaderMiddleware: createAttachmentForScreenReaderMiddleware(createScreenReaderMarkdownRenderer(props.webChatContainerProps)),
361
383
  activityStatusMiddleware: (_props$webChatContain10 = props.webChatContainerProps) !== null && _props$webChatContain10 !== void 0 && (_props$webChatContain10 = _props$webChatContain10.renderingMiddlewareProps) !== null && _props$webChatContain10 !== void 0 && _props$webChatContain10.disableActivityStatusMiddleware ? undefined : createActivityStatusMiddleware(getLocaleStringFromId((_state$domainStates$l5 = state.domainStates.liveChatConfig) === null || _state$domainStates$l5 === void 0 || (_state$domainStates$l5 = _state$domainStates$l5.ChatWidgetLanguage) === null || _state$domainStates$l5 === void 0 ? void 0 : _state$domainStates$l5.msdyn_localeid)),
362
384
  toastMiddleware: (_props$webChatContain11 = props.webChatContainerProps) !== null && _props$webChatContain11 !== void 0 && (_props$webChatContain11 = _props$webChatContain11.renderingMiddlewareProps) !== null && _props$webChatContain11 !== void 0 && _props$webChatContain11.disableToastMiddleware ? undefined : createToastMiddleware(props.notificationPaneProps, endChat),
363
385
  renderMarkdown,
@@ -7,6 +7,7 @@ import { BroadcastService } from "@microsoft/omnichannel-chat-components";
7
7
  import { ConversationState } from "../../../contexts/common/ConversationState";
8
8
  import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
9
9
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
10
+ import { executeReducer } from "../../../contexts/createReducer";
10
11
  import { handleStartChatError } from "./startChatErrorHandler";
11
12
 
12
13
  // Return value: should start normal chat flow when reconnect is enabled
@@ -50,6 +51,32 @@ const handleChatReconnect = async (facadeChatSDK, props, dispatch, setAdapter, i
50
51
  return true;
51
52
  };
52
53
 
54
+ /**
55
+ * Returns true when chat reconnect took over the start: it started the chat itself or showed the reconnect pane.
56
+ * In that case the caller must not start another chat.
57
+ */
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ const isReconnectTriggered = async (facadeChatSDK, props, dispatch, setAdapter, initStartChat, state) => {
60
+ if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
61
+ let reconnectChatStarted = false;
62
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
63
+ const initStartChatAndTrack = async function () {
64
+ reconnectChatStarted = await initStartChat(...arguments);
65
+ };
66
+ const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChatAndTrack, state);
67
+ // initStartChat resolves before React renders Active, so the in-memory state can still read Loading here.
68
+ // Its result tells whether reconnect started the chat; the in-memory state covers the reconnect pane.
69
+ const inMemoryState = executeReducer(state, {
70
+ type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
71
+ payload: null
72
+ });
73
+ if (!noValidReconnectId && (reconnectChatStarted || inMemoryState.appStates.conversationState === ConversationState.Active || inMemoryState.appStates.conversationState === ConversationState.ReconnectChat)) {
74
+ return true;
75
+ }
76
+ }
77
+ return false;
78
+ };
79
+
53
80
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
81
  const getChatReconnectContext = async (facadeChatSDK, chatConfig, props, isAuthenticatedChat, dispatch) => {
55
82
  try {
@@ -143,4 +170,4 @@ const isPersistentEnabled = chatConfig => {
143
170
  const hasReconnectId = reconnectAvailabilityResponse => {
144
171
  return reconnectAvailabilityResponse && !isNullOrUndefined(reconnectAvailabilityResponse.reconnectId);
145
172
  };
146
- export { handleChatReconnect, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
173
+ export { handleChatReconnect, isReconnectTriggered, isReconnectEnabled, isPersistentEnabled, getChatReconnectContext };
@@ -18,19 +18,86 @@ import { isMidAuthEnabled } from "./authHelper";
18
18
  import { setPostChatContextAndLoadSurvey } from "./setPostChatContextAndLoadSurvey";
19
19
  import { shouldSetPreChatIfPersistentChat } from "./persistentChatHelper";
20
20
  import { updateTelemetryData } from "./updateSessionDataForTelemetry";
21
+ /**
22
+ * Per widget instance mutexes for the two chat creation entry points.
23
+ *
24
+ * Every guard in the prepareStartChat -> setPreChatAndInitiateChat -> initStartChat chain
25
+ * checks `conversationState === Closed`, but React state is updated asynchronously. A second
26
+ * invocation fired within the same render cycle (for example a rapid double click on the chat
27
+ * button, or a chat button click racing a BroadcastEvent.StartChat) therefore still observes
28
+ * the stale `Closed` state, reaches `facadeChatSDK.startChat()` and creates a second
29
+ * conversation on the backend which is then orphaned and never ended.
30
+ *
31
+ * The locks are keyed by FacadeChatSDK instance rather than being module wide, because a host
32
+ * page can mount several independent widgets, each with its own widgetInstanceId and its own
33
+ * FacadeChatSDK (created once per widget in LiveChatWidget.tsx). A module wide lock would make
34
+ * widget A's start chat silently drop widget B's legitimate simultaneous start chat.
35
+ *
36
+ * The two maps are separate because prepareStartChat calls initStartChat; sharing a single lock
37
+ * would make the nested call see its own parent as in flight and drop it. prepareStartChat is
38
+ * additionally blocked by an in flight initStartChat (pre-chat submit, reconnect, or the
39
+ * hideStartChatButton bootstrap call initStartChat directly). Otherwise a later prepareStartChat
40
+ * would dispatch Loading and maximize the widget, and only then have its nested initStartChat
41
+ * dropped.
42
+ */
43
+ const prepareStartChatGuards = new WeakMap();
44
+ const initStartChatGuards = new WeakMap();
21
45
 
22
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
- let optionalParams = {};
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
- let widgetInstanceId;
26
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
- let popoutWidgetInstanceId;
46
+ // Fallback owner used only when no FacadeChatSDK instance is available to key on, so the guard
47
+ // degrades to the module wide behaviour instead of disappearing altogether.
48
+ const unkeyedGuardOwner = {};
49
+ const getGuard = (guards, facadeChatSDK) => {
50
+ const owner = facadeChatSDK ?? unkeyedGuardOwner;
51
+ let guard = guards.get(owner);
52
+ if (!guard) {
53
+ guard = {
54
+ inFlight: false
55
+ };
56
+ guards.set(owner, guard);
57
+ }
58
+ return guard;
59
+ };
60
+
61
+ /**
62
+ * Runs `operation` only if no other invocation for the same widget instance is already in
63
+ * flight. Concurrent invocations are dropped (and reported through telemetry) rather than
64
+ * awaiting the in-flight promise, so a future re-entrant call can never deadlock on itself.
65
+ * A dropped invocation resolves to `undefined`.
66
+ *
67
+ * `blockedBy` lets an operation also yield to a different, already running operation for the
68
+ * same widget instance without claiming that operation's lock.
69
+ */
70
+ const runExclusively = async (guards, facadeChatSDK, description, operation, props, blockedBy) => {
71
+ const guard = getGuard(guards, facadeChatSDK);
72
+ const blockingGuard = blockedBy ? getGuard(blockedBy, facadeChatSDK) : undefined;
73
+ if (guard.inFlight || blockingGuard !== null && blockingGuard !== void 0 && blockingGuard.inFlight) {
74
+ TelemetryHelper.logActionEvent(LogLevel.WARN, {
75
+ Event: TelemetryEvent.ConcurrentStartChatRejected,
76
+ Description: description,
77
+ CustomProperties: {
78
+ WidgetCacheId: props ? getWidgetCacheIdfromProps(props) : undefined
79
+ }
80
+ });
81
+ return undefined;
82
+ }
83
+
84
+ // Claim the lock before invoking the operation, so a re-entrant call made from the
85
+ // operation's synchronous preamble (before its first await) cannot slip past the check above.
86
+ guard.inFlight = true;
87
+ try {
88
+ return await operation();
89
+ } finally {
90
+ guard.inFlight = false;
91
+ }
92
+ };
28
93
 
29
94
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
95
  const prepareStartChat = async (props, facadeChatSDK, state, dispatch, setAdapter) => {
31
- optionalParams = {}; //Resetting to ensure no stale values
32
- widgetInstanceId = getWidgetCacheIdfromProps(props);
96
+ return runExclusively(prepareStartChatGuards, facadeChatSDK, "Concurrent prepareStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => prepareStartChatInternal(props, facadeChatSDK, state, dispatch, setAdapter), props, initStartChatGuards);
97
+ };
33
98
 
99
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
100
+ const prepareStartChatInternal = async (props, facadeChatSDK, state, dispatch, setAdapter) => {
34
101
  // reconnect > chat from cache
35
102
  if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
36
103
  const shouldStartChatNormally = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
@@ -154,8 +221,18 @@ const setPreChatAndInitiateChat = async (facadeChatSDK, dispatch, setAdapter, is
154
221
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
155
222
  };
156
223
 
224
+ /**
225
+ * Resolves to `true` when the chat reached Active, and `false` when it failed or the call was dropped.
226
+ * It resolves before React renders Active, so callers must use this value rather than reading the conversation state.
227
+ */
157
228
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
229
  const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState) => {
230
+ const chatStarted = await runExclusively(initStartChatGuards, facadeChatSDK, "Concurrent initStartChat call ignored, a start chat operation is already in progress for this widget instance.", () => initStartChatInternal(facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState), props);
231
+ return chatStarted === true;
232
+ };
233
+
234
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
235
+ const initStartChatInternal = async (facadeChatSDK, dispatch, setAdapter, state, props, params, persistedState) => {
159
236
  var _state$domainStates7;
160
237
  let isStartChatSuccessful = false;
161
238
  const persistentChatEnabled = isPersistentChatEnabled(state === null || state === void 0 || (_state$domainStates7 = state.domainStates) === null || _state$domainStates7 === void 0 || (_state$domainStates7 = _state$domainStates7.liveChatConfig) === null || _state$domainStates7 === void 0 || (_state$domainStates7 = _state$domainStates7.LiveWSAndLiveChatEngJoin) === null || _state$domainStates7 === void 0 ? void 0 : _state$domainStates7.msdyn_conversationmode);
@@ -194,14 +271,15 @@ const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props,
194
271
  }
195
272
  try {
196
273
  var _window$Microsoft, _state$domainStates8;
197
- // Set custom context params
198
- await setCustomContextParams(state, props);
274
+ // Set custom context params. Returned (not stored module-side) so that concurrent
275
+ // widget instances cannot overwrite each other's custom context.
276
+ const customContextParams = await setCustomContextParams(state, props);
199
277
  const defaultOptionalParams = {
200
278
  sendDefaultInitContext: true,
201
279
  isProactiveChat: !!(params !== null && params !== void 0 && params.isProactiveChat),
202
280
  portalContactId: (_window$Microsoft = window.Microsoft) === null || _window$Microsoft === void 0 || (_window$Microsoft = _window$Microsoft.Dynamic365) === null || _window$Microsoft === void 0 || (_window$Microsoft = _window$Microsoft.Portal) === null || _window$Microsoft === void 0 || (_window$Microsoft = _window$Microsoft.User) === null || _window$Microsoft === void 0 ? void 0 : _window$Microsoft.contactId
203
281
  };
204
- const startChatOptionalParams = Object.assign({}, params, optionalParams, defaultOptionalParams);
282
+ const startChatOptionalParams = Object.assign({}, params, customContextParams, defaultOptionalParams);
205
283
 
206
284
  // MID-AUTH: Add wasAuthenticated flag for reconnect scenarios
207
285
  // Tells FacadeChatSDK whether the previous session was authenticated
@@ -264,7 +342,7 @@ const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props,
264
342
  logWidgetLoadComplete(WidgetLoadTelemetryMessage.PersistedStateRetrievedMessage);
265
343
  // Set post chat context in state, load in background to do not block the load
266
344
  setPostChatContextAndLoadSurvey(facadeChatSDK, dispatch, true);
267
- return;
345
+ return true;
268
346
  }
269
347
 
270
348
  // Persistent Chat relies on the `reconnectId` retrieved from reconnectablechats API to reconnect upon start chat and not `liveChatContext`
@@ -280,13 +358,13 @@ const initStartChat = async (facadeChatSDK, dispatch, setAdapter, state, props,
280
358
  logWidgetLoadComplete();
281
359
  // Set post chat context in state, load in background to do not block the load
282
360
  setPostChatContextAndLoadSurvey(facadeChatSDK, dispatch);
283
- // Updating chat session detail for telemetry
284
- await updateTelemetryData(facadeChatSDK, dispatch);
361
+ // Updating chat session detail for telemetry, in background: getConversationDetails retries until the
362
+ // live work item exists (several seconds), and awaiting it would hold the start chat locks and drop the next start chat
363
+ updateTelemetryData(facadeChatSDK, dispatch);
364
+ return true;
285
365
  } catch (ex) {
286
366
  handleStartChatError(dispatch, facadeChatSDK, props, ex, isStartChatSuccessful);
287
- } finally {
288
- optionalParams = {};
289
- widgetInstanceId = "";
367
+ return false;
290
368
  }
291
369
  };
292
370
 
@@ -330,19 +408,22 @@ const canConnectToExistingChat = async (props, facadeChatSDK, state, dispatch, s
330
408
  return false;
331
409
  };
332
410
 
333
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
411
+ /**
412
+ * Resolves the custom context to start the chat with.
413
+ *
414
+ * Returns the resolved params instead of mutating module-level state: a page can host several
415
+ * independent widgets, and once per-instance start-chat guards allow them to run concurrently,
416
+ * shared mutable state would let one widget overwrite another widget's custom context.
417
+ */
334
418
  const setCustomContextParams = async (state, props) => {
335
419
  var _state$domainStates9, _persistedState$domai5;
336
420
  if (state !== null && state !== void 0 && (_state$domainStates9 = state.domainStates) !== null && _state$domainStates9 !== void 0 && _state$domainStates9.customContext) {
337
421
  var _state$domainStates0;
338
- optionalParams = Object.assign({}, optionalParams, {
422
+ return {
339
423
  customContext: JSON.parse(JSON.stringify(state === null || state === void 0 || (_state$domainStates0 = state.domainStates) === null || _state$domainStates0 === void 0 ? void 0 : _state$domainStates0.customContext))
340
- });
341
- return;
342
- }
343
- if (isNullOrEmptyString(widgetInstanceId)) {
344
- widgetInstanceId = getWidgetCacheIdfromProps(props);
424
+ };
345
425
  }
426
+ const widgetInstanceId = props ? getWidgetCacheIdfromProps(props) : "";
346
427
  // Add custom context only for unauthenticated chat
347
428
  const persistedState = getStateFromCache(widgetInstanceId);
348
429
  const customContextLocal = (persistedState === null || persistedState === void 0 || (_persistedState$domai5 = persistedState.domainStates) === null || _persistedState$domai5 === void 0 ? void 0 : _persistedState$domai5.customContext) ?? (props === null || props === void 0 ? void 0 : props.initialCustomContext);
@@ -351,23 +432,23 @@ const setCustomContextParams = async (state, props) => {
351
432
  Event: TelemetryEvent.SettingCustomContext,
352
433
  Description: "Setting custom context for unauthenticated chat"
353
434
  });
354
- optionalParams = Object.assign({}, optionalParams, {
435
+ return {
355
436
  customContext: JSON.parse(JSON.stringify(customContextLocal))
356
- });
357
- } else {
358
- const customContextFromParent = await getInitContextParamsForPopout();
359
- if (!isUndefinedOrEmpty(customContextFromParent === null || customContextFromParent === void 0 ? void 0 : customContextFromParent.contextVariables)) {
360
- optionalParams = Object.assign({}, optionalParams, {
361
- customContext: JSON.parse(JSON.stringify(customContextFromParent.contextVariables))
362
- });
363
- }
437
+ };
438
+ }
439
+ const customContextFromParent = await getInitContextParamsForPopout();
440
+ if (!isUndefinedOrEmpty(customContextFromParent === null || customContextFromParent === void 0 ? void 0 : customContextFromParent.contextVariables)) {
441
+ return {
442
+ customContext: JSON.parse(JSON.stringify(customContextFromParent.contextVariables))
443
+ };
364
444
  }
445
+ return {};
365
446
  };
366
447
  const canStartPopoutChat = async props => {
367
448
  if (props.allowSdkChatSupport === false) {
368
449
  return false;
369
450
  }
370
- popoutWidgetInstanceId = getWidgetCacheIdfromProps(props, true);
451
+ const popoutWidgetInstanceId = getWidgetCacheIdfromProps(props, true);
371
452
  if (!isNullOrEmptyString(popoutWidgetInstanceId)) {
372
453
  var _persistedState$domai6, _persistedState$appSt3;
373
454
  const persistedState = getStateFromCache(popoutWidgetInstanceId);
@@ -1,4 +1,4 @@
1
- import { BroadcastEvent } from "../../../common/telemetry/TelemetryConstants";
1
+ import { BroadcastEvent, LogLevel, TelemetryEvent } from "../../../common/telemetry/TelemetryConstants";
2
2
  import { BroadcastService } from "@microsoft/omnichannel-chat-components";
3
3
  import { LiveChatWidgetActionType } from "../../../contexts/common/LiveChatWidgetActionType";
4
4
  import { TelemetryHelper } from "../../../common/telemetry/TelemetryHelper";
@@ -7,15 +7,41 @@ import { getConversationDetailsCall } from "../../../common/utils";
7
7
 
8
8
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
9
  export const updateTelemetryData = async (facadeChatSDK, dispatch) => {
10
- // load it concurrently, this will reduce the load time
11
- await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch), updateConversationDataForTelemetry(facadeChatSDK, dispatch)]);
10
+ var _facadeChatSDK$getCha;
11
+ // startChat no longer waits for this, so the next chat can start (chatSDKStateCleanUp assigns a new requestId)
12
+ // before these calls resolve. Results for an earlier chat must not overwrite the current chat's data.
13
+ // endChat also assigns a new requestId, so the chat that just ended still applies its own results.
14
+ const requestId = facadeChatSDK === null || facadeChatSDK === void 0 || (_facadeChatSDK$getCha = facadeChatSDK.getChatSDK()) === null || _facadeChatSDK$getCha === void 0 ? void 0 : _facadeChatSDK$getCha.requestId;
15
+ try {
16
+ // load it concurrently, this will reduce the load time
17
+ await Promise.all([updateSessionDataForTelemetry(facadeChatSDK, dispatch, requestId), updateConversationDataForTelemetry(facadeChatSDK, dispatch, requestId)]);
18
+ } catch (error) {
19
+ TelemetryHelper.logSDKEvent(LogLevel.ERROR, {
20
+ Event: TelemetryEvent.UpdateTelemetryDataFailed,
21
+ ExceptionDetails: {
22
+ exception: `Update telemetry data failed: ${error}`
23
+ }
24
+ });
25
+ }
26
+ };
27
+
28
+ // The requestId alone isn't enough: endChat also replaces it. Only the next chat's startChat gets a new chat token
29
+ // (endChat and chatSDKStateCleanUp clear it), so drop the result only when the SDK holds that next chat.
30
+ const isFromEarlierChat = (facadeChatSDK, requestId) => {
31
+ var _chatSDK$chatToken;
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const chatSDK = facadeChatSDK.getChatSDK();
34
+ return (chatSDK === null || chatSDK === void 0 ? void 0 : chatSDK.requestId) !== requestId && !!(chatSDK !== null && chatSDK !== void 0 && (_chatSDK$chatToken = chatSDK.chatToken) !== null && _chatSDK$chatToken !== void 0 && _chatSDK$chatToken.chatId);
12
35
  };
13
36
 
14
37
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
- const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
38
+ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
16
39
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
17
40
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
41
  const chatSession = await facadeChatSDK.getCurrentLiveChatContext();
42
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
43
+ return;
44
+ }
19
45
  const telemetryData = TelemetryHelper.addSessionDataToTelemetry(chatSession, TelemetryManager.InternalTelemetryData);
20
46
  dispatch({
21
47
  type: LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -31,10 +57,13 @@ const updateSessionDataForTelemetry = async (facadeChatSDK, dispatch) => {
31
57
  };
32
58
 
33
59
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
- const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch) => {
60
+ const updateConversationDataForTelemetry = async (facadeChatSDK, dispatch, requestId) => {
35
61
  if (facadeChatSDK && facadeChatSDK.getChatSDK()) {
36
62
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
63
  const liveWorkItem = await getConversationDetailsCall(facadeChatSDK);
64
+ if (isFromEarlierChat(facadeChatSDK, requestId)) {
65
+ return;
66
+ }
38
67
  const telemetryData = TelemetryHelper.addConversationDataToTelemetry(liveWorkItem, TelemetryManager.InternalTelemetryData);
39
68
  dispatch({
40
69
  type: LiveChatWidgetActionType.SET_TELEMETRY_DATA,
@@ -17,7 +17,7 @@ import { checkIfConversationStillValid, initStartChat, prepareStartChat, setPreC
17
17
  import { createTimer, getBroadcastChannelName, getConversationDetailsCall, getLocaleDirection, getStateFromCache, getWidgetCacheIdfromProps, getWidgetEndChatEventName, isNullOrEmptyString, isNullOrUndefined, isThisSessionPopout, isUndefinedOrEmpty, setAriaHiddenForSiblings, setOcUserAgent } from "../../../common/utils";
18
18
  import { customEventCallback, subscribeToSendCustomEvent } from "../common/customEventHandler";
19
19
  import { defaultClientDataStoreProvider, isCookieAllowed } from "../../../common/storage/default/defaultClientDataStoreProvider";
20
- import { handleChatReconnect, isPersistentEnabled, isReconnectEnabled } from "../common/reconnectChatHelper";
20
+ import { isPersistentEnabled, isReconnectTriggered } from "../common/reconnectChatHelper";
21
21
  import { shouldShowCallingContainer, shouldShowChatButton, shouldShowConfirmationPane, shouldShowEmailTranscriptPane, shouldShowHeader, shouldShowLoadingPane, shouldShowOutOfOfficeHoursPane, shouldShowPostChatLoadingPane, shouldShowPostChatSurveyPane, shouldShowPreChatSurveyPane, shouldShowProactiveChatPane, shouldShowReconnectChatPane, shouldShowStartChatErrorPane, shouldShowWebChatContainer } from "../../../controller/componentController";
22
22
  import { ActivityStreamHandler } from "../common/ActivityStreamHandler";
23
23
  import CallingContainerStateful from "../../callingcontainerstateful/CallingContainerStateful";
@@ -156,20 +156,6 @@ export const LiveChatWidgetStateful = props => {
156
156
 
157
157
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
158
158
  const startChat = async (props, localState) => {
159
- const isReconnectTriggered = async () => {
160
- if (isReconnectEnabled(props.chatConfig) === true && !isPersistentEnabled(props.chatConfig)) {
161
- const noValidReconnectId = await handleChatReconnect(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
162
- const inMemoryState = executeReducer(state, {
163
- type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
164
- payload: null
165
- });
166
- // If chat reconnect has kicked in chat state will become Active or Reconnect. So just exit, else go next
167
- if (!noValidReconnectId && (inMemoryState.appStates.conversationState === ConversationState.Active || inMemoryState.appStates.conversationState === ConversationState.ReconnectChat)) {
168
- return true;
169
- }
170
- }
171
- return false;
172
- };
173
159
  let isChatValid = false;
174
160
  //Start a chat from cache/reconnectid
175
161
  if (activeCachedChatExist === true) {
@@ -181,7 +167,7 @@ export const LiveChatWidgetStateful = props => {
181
167
  //Check if conversation state is not in wrapup or closed state
182
168
  isChatValid = await checkIfConversationStillValid(facadeChatSDK, dispatch, state);
183
169
  if (isChatValid === true) {
184
- const reconnectTriggered = await isReconnectTriggered();
170
+ const reconnectTriggered = await isReconnectTriggered(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
185
171
  if (!reconnectTriggered) {
186
172
  await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams);
187
173
  }
@@ -197,7 +183,7 @@ export const LiveChatWidgetStateful = props => {
197
183
  if (isChatValid === false) {
198
184
  if (localState) {
199
185
  // adding the reconnect logic for the case when customer tries to reconnect from a new browser or InPrivate browser
200
- const reconnectTriggered = await isReconnectTriggered();
186
+ const reconnectTriggered = await isReconnectTriggered(facadeChatSDK, props, dispatch, setAdapter, initStartChat, state);
201
187
  if (!reconnectTriggered) {
202
188
  const inMemoryState = executeReducer(state, {
203
189
  type: LiveChatWidgetActionType.GET_IN_MEMORY_STATE,
@@ -993,7 +979,9 @@ export const LiveChatWidgetStateful = props => {
993
979
  const endChatRelay = (adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab) => endChat(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter, skipEndChatSDK, skipCloseChat, postMessageToOtherTab);
994
980
  const prepareStartChatRelay = () => prepareStartChat(props, facadeChatSDK, state, dispatch, setAdapter);
995
981
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
996
- const initStartChatRelay = (optionalParams, persistedState) => initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
982
+ const initStartChatRelay = async (optionalParams, persistedState) => {
983
+ await initStartChat(facadeChatSDK, dispatch, setAdapter, state, props, optionalParams, persistedState);
984
+ };
997
985
  const confirmationPaneProps = initConfirmationPropsComposer(props);
998
986
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
999
987
  const prepareEndChatRelay = () => prepareEndChat(props, facadeChatSDK, state, dispatch, setAdapter, setWebChatStyles, adapter);
@@ -27,7 +27,8 @@ export const defaultMiddlewareLocalizedTexts = {
27
27
  MIDDLEWARE_BANNER_CHAT_DISCONNECT: "Your conversation has been disconnected. For additional assistance, please start a new chat.",
28
28
  THIRD_PARTY_COOKIES_BLOCKED_ALERT_MESSAGE: "Allow sites to save/read cookies in browser settings. Reloading page starts a new chat.",
29
29
  MIDDLEWARE_BANNER_FILE_IS_MALICIOUS: "{0} has been blocked because the file may contain a malware.",
30
- MIDDLEWARE_BANNER_FILE_SENT: "File sent successfully.",
30
+ MIDDLEWARE_BANNER_FILE_SENT: "File {2} sent",
31
+ MIDDLEWARE_BANNER_FILES_SENT: "{0} files sent",
31
32
  MIDDLEWARE_BANNER_FILE_EMAIL_ADDRESS_RECORDED_SUCCESS: "Email will be sent after chat ends!",
32
33
  MIDDLEWARE_BANNER_FILE_EMAIL_ADDRESS_RECORDED_ERROR: "Email {0} could not be saved, try again later.",
33
34
  MIDDLEWARE_SR_PREFIX_SUCCESS: "Success. ",